List of usage examples for java.net URLClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:org.dkpro.tc.core.util.SaveModelUtils.java
public static List<ExternalResourceDescription> loadExternalResourceDescriptionOfFeatures(File tcModelLocation, UimaContext aContext) throws Exception { List<ExternalResourceDescription> erd = new ArrayList<>(); File classFile = new File(tcModelLocation + "/" + Constants.MODEL_FEATURE_CLASS_FOLDER); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { classFile.toURI().toURL() }); File file = new File(tcModelLocation, MODEL_FEATURE_EXTRACTOR_CONFIGURATION); for (String l : FileUtils.readLines(file)) { String[] split = l.split("\t"); String name = split[0];/*from w ww . j av a2 s . co m*/ Object[] parameters = getParameters(split); Class<? extends Resource> feClass = urlClassLoader.loadClass(name).asSubclass(Resource.class); List<Object> idRemovedParameters = filterId(parameters); String id = getId(parameters); idRemovedParameters = addModelPathAsPrefixIfParameterIsExistingFile(idRemovedParameters, tcModelLocation.getAbsolutePath()); TcFeature feature = TcFeatureFactory.create(id, feClass, idRemovedParameters.toArray()); ExternalResourceDescription exRes = feature.getActualValue(); // Skip feature extractors that are not dependent on meta collectors if (!MetaDependent.class.isAssignableFrom(feClass)) { erd.add(exRes); continue; } Map<String, String> overrides = loadOverrides(tcModelLocation, META_COLLECTOR_OVERRIDE); configureOverrides(tcModelLocation, exRes, overrides); overrides = loadOverrides(tcModelLocation, META_EXTRACTOR_OVERRIDE); configureOverrides(tcModelLocation, exRes, overrides); erd.add(exRes); } urlClassLoader.close(); return erd; }
From source file:com.navercorp.pinpoint.profiler.instrument.classloading.Java9DefineClassTest.java
@Test public void defineClass() throws ClassNotFoundException, IOException { URL location = CodeSourceUtils.getCodeLocation(Logger.class); logger.debug("location:{}", location); URL[] empty = {};/*from w ww . j a v a 2 s . c o m*/ URLClassLoader classLoader = new URLClassLoader(empty, null); try { classLoader.loadClass(Logger.class.getName()); Assert.fail(); } catch (ClassNotFoundException ignore) { } String className = JavaAssistUtils.javaClassNameToJvmResourceName(Logger.class.getName()); InputStream classStream = Logger.class.getClassLoader().getResourceAsStream(className); byte[] bytes = IOUtils.readFully(classStream, classStream.available()); DefineClass defineClass = new Java9DefineClass(); Class<?> defineClassSlf4jLogger = defineClass.defineClass(classLoader, Logger.class.getName(), bytes); Class<?> slf4jLogger = classLoader.loadClass(Logger.class.getName()); Assert.assertSame(defineClassSlf4jLogger, slf4jLogger); Assert.assertSame(slf4jLogger.getClassLoader(), classLoader); Assert.assertNotSame(slf4jLogger.getClassLoader(), Logger.class.getClassLoader()); }
From source file:com.legstar.jaxb.plugin.EnumCases.java
/** * Check Get Set methods on enumerations. * @throws Exception if test fails/*from w w w. ja va 2 s . c om*/ */ public void testGetSetEnum() throws Exception { /* Load the generated class */ URI loc = GEN_SRC_DIR.toURI(); URL[] ua = { loc.toURL() }; URLClassLoader cl = new URLClassLoader(ua); Class<?> clazzSearchRequestType = cl.loadClass("com.legstar.test.coxb.enumvar.SearchRequestType"); Object searchRequest = clazzSearchRequestType.newInstance(); /* Create an Enum type with a value */ Class<?> clazzSafeSearchOptionsType = cl.loadClass("com.legstar.test.coxb.enumvar.SafeSearchOptionsType"); Field[] fields = clazzSafeSearchOptionsType.getDeclaredFields(); for (Field field : fields) { _log.debug(field.getName()); } /* Create a new enum type with a value */ Method getValueMethod = clazzSafeSearchOptionsType.getMethod("value", (Class[]) null); Method fromValueMethod = clazzSafeSearchOptionsType.getMethod("fromValue", new Class[] { getValueMethod.getReturnType() }); Object safeSearchOption = fromValueMethod.invoke(null, new Object[] { "Strict" }); /* Get the value of an Enum */ getValueMethod.invoke(safeSearchOption, (Object[]) null); /* Set the Enum value*/ Class<?>[] param = { clazzSafeSearchOptionsType }; String setterName = "setSafeSearch"; Method setter = searchRequest.getClass().getMethod(setterName, param); setter.invoke(searchRequest, safeSearchOption); String getterName = "getSafeSearch"; Method getter = searchRequest.getClass().getMethod(getterName); Object result = getter.invoke(searchRequest); assertEquals("Strict", getValueMethod.invoke(result, (Object[]) null)); }
From source file:org.exnebula.bootstrap.BootConfigLocatorTest.java
private Class<?> createClassLoaderAndLoadClass(File jarFile, String classToLoad) throws MalformedURLException, ClassNotFoundException { URL[] urls = { jarFile.toURI().toURL() }; URLClassLoader classLoader = new URLClassLoader(urls, null); return classLoader.loadClass(classToLoad); }
From source file:com.apifest.oauth20.LifecycleEventHandlers.java
@SuppressWarnings("unchecked") public static void loadLifecycleHandlers(URLClassLoader classLoader, String customJar) { try {//from w w w. j av a 2s . c o m if (classLoader != null) { JarFile jarFile = new JarFile(customJar); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // remove .class String className = entry.getName().substring(0, entry.getName().length() - 6); className = className.replace('/', '.'); try { // REVISIT: check for better solution if (className.startsWith("org.jboss.netty") || className.startsWith("org.apache.log4j") || className.startsWith("org.apache.commons")) { continue; } Class<?> clazz = classLoader.loadClass(className); if (clazz.isAnnotationPresent(OnRequest.class) && LifecycleHandler.class.isAssignableFrom(clazz)) { requestEventHandlers.add((Class<LifecycleHandler>) clazz); log.debug("preIssueTokenHandler added {}", className); } if (clazz.isAnnotationPresent(OnResponse.class) && LifecycleHandler.class.isAssignableFrom(clazz)) { responseEventHandlers.add((Class<LifecycleHandler>) clazz); log.debug("postIssueTokenHandler added {}", className); } if (clazz.isAnnotationPresent(OnException.class) && ExceptionEventHandler.class.isAssignableFrom(clazz)) { exceptionHandlers.add((Class<ExceptionEventHandler>) clazz); log.debug("exceptionHandlers added {}", className); } } catch (ClassNotFoundException e1) { // continue } } } } catch (MalformedURLException e) { log.error("cannot load lifecycle handlers", e); } catch (IOException e) { log.error("cannot load lifecycle handlers", e); } catch (IllegalArgumentException e) { log.error(e.getMessage()); } }
From source file:org.adscale.testtodoc.TestToDoc.java
Class<?> loadClass(URLClassLoader loader, String clazzName) { try {// www .j a v a 2 s . c o m return loader.loadClass(clazzName); } catch (ClassNotFoundException e) { throw new RuntimeException("can't find '" + clazzName + "' in loader '" + loader + "'", e); } }
From source file:org.commonjava.test.compile.CompilerFixxxtureTest.java
@Test public void compileDependingOnlyOnJDK_UseServiceLoader() throws Exception { final CompilerResult result = compiler.compileSourceDirWithThisClass("jdk-only-service", "org.test.Hello"); FileUtils.write(Paths.get(result.getClasses().getAbsolutePath(), "META-INF", "services", "org.test.IHello") .toFile(), "org.test.Hello"); final URLClassLoader ucl = result.getClassLoader(); final Class<?> cls = ucl.loadClass("org.test.IHello"); final ServiceLoader<?> loader = ServiceLoader.load(cls, ucl); final Object object = loader.iterator().next(); final Method method = cls.getMethod("hello", new Class[] { String[].class }); System.out.println(method);/*from ww w. j a va2 s. co m*/ method.invoke(object, new Object[] { new String[] { "Tester" } }); }
From source file:net.sf.taverna.raven.launcher.TestPreLauncher.java
@Test public void launchHelloWorld() throws Exception { System.setProperty("raven.launcher.app.name", "helloworld"); System.setProperty("raven.launcher.app.main", "net.sf.taverna.raven.helloworld.HelloWorld"); List<URL> urls = makeClassPath("TestPreLauncher-helloworld/"); URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(classLoader); classLoader.loadClass("org.apache.log4j.Logger"); File outFile = File.createTempFile(getClass().getCanonicalName(), "test"); outFile.deleteOnExit();/*from w w w. j a v a 2s . c o m*/ PreLauncher.main(new String[] { outFile.getAbsolutePath() }); String out = FileUtils.readFileToString(outFile, "utf8"); assertEquals("Did not match expected output", "This is the test data.\n", out); }
From source file:org.echocat.redprecursor.impl.sun.compilertree.SunNodeFactoryIntegrationTest.java
private void executeMethodIn(File classFile) throws Throwable { final URLClassLoader loader = new URLClassLoader(new URL[] { classFile.getParentFile().toURI().toURL() }); final Class<?> testClass = loader.loadClass("Test"); final Object test = testClass.newInstance(); final Method callMethod = testClass.getMethod("call", String.class, Integer.class); try {/*from w w w .j av a 2s. c o m*/ callMethod.invoke(test, new Object[] { "abc", 2 }); } catch (InvocationTargetException e) { throw e.getTargetException(); } }
From source file:com.serotonin.m2m2.Main.java
private static ClassLoader loadModules() throws Exception { Common.documentationManifest.parseManifestFile("web/WEB-INF/dox"); File modulesPath = new File(new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString()); File[] modules = modulesPath.listFiles(); if (modules == null) { modules = new File[0]; }/* w ww .ja va 2 s . c om*/ List classLoaderUrls = new ArrayList(); Map<Module, List<String>> moduleClasses = new HashMap<Module, List<String>>(); VersionData coreVersion = Common.getVersion(); List<ModuleWrapper> moduleWrappers = new ArrayList(); for (File moduleDir : modules) { if (!moduleDir.isDirectory()) { continue; } if (new File(moduleDir, "DELETE").exists()) { deleteDir(moduleDir); LOG.info(new StringBuilder().append("Deleted module directory ").append(moduleDir).toString()); } else { Properties props = null; try { props = getProperties(moduleDir); } catch (ModulePropertiesException e) { LOG.warn(new StringBuilder().append("Error loading properties for module ") .append(moduleDir.getPath()).toString(), e.getCause()); } if (props == null) { continue; } String moduleName = props.getProperty("name"); if (moduleName == null) { throw new RuntimeException(new StringBuilder().append("Module ").append(moduleDir.getPath()) .append(": ").append("name").append(" not defined in module properties").toString()); } if (!ModuleUtils.validateName(moduleName)) { throw new RuntimeException( new StringBuilder().append("Module ").append(moduleDir.getPath()).append(": ") .append("name").append(" has an invalid name: ").append(moduleName).toString()); } String version = props.getProperty("version"); if (version == null) { throw new RuntimeException(new StringBuilder().append("Module ").append(moduleName).append(": ") .append("version").append(" not defined in module properties").toString()); } String moduleCoreVersion = props.getProperty("coreVersion"); if (moduleCoreVersion == null) { throw new RuntimeException(new StringBuilder().append("Module ").append(moduleName).append(": ") .append("coreVersion").append(" not defined in module properties").toString()); } DependencyData moduleCoreDependency = new DependencyData(moduleCoreVersion); if (!moduleCoreDependency.matches(coreVersion)) { LOG.warn(new StringBuilder().append("Module ").append(moduleName) .append(": this module requires a core version of ").append(moduleCoreVersion) .append(", which does not match the current core version of ") .append(coreVersion.getFullString()).append(". Module not loaded.").toString()); } else { String descriptionKey = props.getProperty("descriptionKey"); TranslatableMessage description = null; if (org.apache.commons.lang3.StringUtils.isBlank(descriptionKey)) { String desc = props.getProperty("description"); if (!org.apache.commons.lang3.StringUtils.isBlank(desc)) description = new TranslatableMessage("common.default", new Object[] { desc }); } else { description = new TranslatableMessage(descriptionKey); } String vendor = props.getProperty("vendor"); String vendorUrl = props.getProperty("vendorUrl"); String dependencies = props.getProperty("dependencies"); String loadOrderStr = props.getProperty("loadOrder"); int loadOrder = 50; if (!org.apache.commons.lang3.StringUtils.isBlank(loadOrderStr)) { try { loadOrder = Integer.parseInt(loadOrderStr); } catch (Exception e) { loadOrder = -1; } if ((loadOrder < 1) || (loadOrder > 100)) { LOG.warn(new StringBuilder().append("Module ").append(moduleName) .append(": bad loadOrder value '").append(loadOrderStr) .append("', must be a number between 1 and 100. Defaulting to 50").toString()); loadOrder = 50; } } Module module = new Module(moduleName, version, description, vendor, vendorUrl, dependencies, loadOrder); moduleWrappers.add(new ModuleWrapper(module, props, moduleDir)); } } } Collections.sort(moduleWrappers, new Comparator<ModuleWrapper>() { public int compare(ModuleWrapper m1, ModuleWrapper m2) { return m1.module.getLoadOrder() - m2.module.getLoadOrder(); } }); for (ModuleWrapper moduleWrapper : moduleWrappers) { Module module = moduleWrapper.module; String moduleName = moduleWrapper.module.getName(); String version = moduleWrapper.module.getVersion(); String vendor = moduleWrapper.module.getVendor(); Properties props = moduleWrapper.props; File moduleDir = moduleWrapper.moduleDir; ModuleRegistry.addModule(module); LOG.info( new StringBuilder().append("Loading module '").append(moduleName).append("', v").append(version) .append(" by ").append(vendor == null ? "(unknown vendor)" : vendor).toString()); String classes = props.getProperty("classes"); if (!org.apache.commons.lang3.StringUtils.isBlank(classes)) { String[] parts = classes.split(","); for (String className : parts) { if (!org.apache.commons.lang3.StringUtils.isBlank(className)) { className = className.trim(); List classNames = (List) moduleClasses.get(module); if (classNames == null) { classNames = new ArrayList(); moduleClasses.put(module, classNames); } classNames.add(className); } } } File classesDir = new File(moduleDir, "classes"); if (classesDir.exists()) { classLoaderUrls.add(classesDir.toURI().toURL()); } loadLib(moduleDir, classLoaderUrls); String logo = props.getProperty("logo"); if (!org.apache.commons.lang3.StringUtils.isBlank(logo)) { Common.applicationLogo = new StringBuilder().append("/modules/").append(moduleName).append("/") .append(logo).toString(); } String favicon = props.getProperty("favicon"); if (!org.apache.commons.lang3.StringUtils.isBlank(favicon)) { Common.applicationFavicon = new StringBuilder().append("/modules/").append(moduleName).append("/") .append(favicon).toString(); } String styles = props.getProperty("styles"); if (!org.apache.commons.lang3.StringUtils.isBlank(styles)) { for (String style : styles.split(",")) { style = com.serotonin.util.StringUtils.trimWhitespace(style); if (!org.apache.commons.lang3.StringUtils.isBlank(style)) { Common.moduleStyles.add(new StringBuilder().append("modules/").append(moduleName) .append("/").append(style).toString()); } } } String scripts = props.getProperty("scripts"); if (!org.apache.commons.lang3.StringUtils.isBlank(scripts)) { for (String script : scripts.split(",")) { script = com.serotonin.util.StringUtils.trimWhitespace(script); if (!org.apache.commons.lang3.StringUtils.isBlank(script)) { Common.moduleScripts.add(new StringBuilder().append("modules/").append(moduleName) .append("/").append(script).toString()); } } } String jspfs = props.getProperty("jspfs"); if (!org.apache.commons.lang3.StringUtils.isBlank(jspfs)) { for (String jspf : jspfs.split(",")) { jspf = com.serotonin.util.StringUtils.trimWhitespace(jspf); if (!org.apache.commons.lang3.StringUtils.isBlank(jspf)) { Common.moduleJspfs.add(new StringBuilder().append("/modules/").append(moduleName) .append("/").append(jspf).toString()); } } } String dox = props.getProperty("documentation"); if (!org.apache.commons.lang3.StringUtils.isBlank(dox)) { Common.documentationManifest.parseManifestFile(new StringBuilder().append("web/modules/") .append(moduleName).append("/").append(dox).toString()); } String locales = props.getProperty("locales"); if (!org.apache.commons.lang3.StringUtils.isBlank(locales)) { String[] s = locales.split(","); for (String locale : s) { module.addLocaleDefinition(locale.trim()); } } String tagdir = props.getProperty("tagdir"); if (!org.apache.commons.lang3.StringUtils.isBlank(tagdir)) { File from = new File(moduleDir, tagdir); File to = new File(new StringBuilder().append(Common.MA_HOME).append("/web/WEB-INF/tags/") .append(moduleName).toString()); deleteDir(to); if (from.exists()) { FileUtils.copyDirectory(from, to); } } String graphics = props.getProperty("graphics"); if (!org.apache.commons.lang3.StringUtils.isBlank(graphics)) { graphics = com.serotonin.util.StringUtils.trimWhitespace(graphics); if (!org.apache.commons.lang3.StringUtils.isBlank(graphics)) { module.setGraphicsDir(graphics); } } String emailTemplates = props.getProperty("emailTemplates"); if (!org.apache.commons.lang3.StringUtils.isBlank(emailTemplates)) { emailTemplates = com.serotonin.util.StringUtils.trimWhitespace(emailTemplates); if (!org.apache.commons.lang3.StringUtils.isBlank(emailTemplates)) { module.setEmailTemplatesDir(emailTemplates); } } } for (Module module : ModuleRegistry.getModules()) { String dependenciesStr = module.getDependencies(); if (!org.apache.commons.lang3.StringUtils.isBlank(dependenciesStr)) { String[] parts = dependenciesStr.split(","); for (String dependencyStr : parts) { DependencyData depVer = null; dependencyStr = dependencyStr.trim(); int pos = dependencyStr.lastIndexOf(45); String depName; if (pos == -1) { depName = dependencyStr; } else { depName = dependencyStr.substring(0, pos); String ver = dependenciesStr.substring(pos + 1); try { depVer = new DependencyData(ver); } catch (Exception e) { throw new RuntimeException(new StringBuilder().append("Invalid dependency version in '") .append(dependencyStr).append("'").toString(), e); } } Module depModule = ModuleRegistry.getModule(depName); if (depModule == null) { throw new RuntimeException(new StringBuilder().append("Module '").append(depName) .append("' not found, but required by '").append(module.getName()).append("'") .toString()); } if ((depVer != null) && (!depVer.matches(new VersionData(depModule.getVersion())))) { throw new RuntimeException(new StringBuilder().append("Module '").append(depName) .append("' has version '").append(depModule.getVersion()).append("' but module '") .append(module.getName()).append("' requires version '") .append(depVer.getFullString()).append("'").toString()); } } } } URL[] arr = (URL[]) classLoaderUrls.toArray(new URL[0]); URLClassLoader cl = new URLClassLoader(arr, Main.class.getClassLoader()); Thread.currentThread().setContextClassLoader(cl); for (Map.Entry mod : moduleClasses.entrySet()) { try { for (String className : (List<String>) mod.getValue()) { Class clazz = cl.loadClass(className); boolean used = false; if (ModuleElementDefinition.class.isAssignableFrom(clazz)) { ModuleElementDefinition def = (ModuleElementDefinition) clazz.newInstance(); ((Module) mod.getKey()).addDefinition(def); used = true; } if (!used) LOG.warn(new StringBuilder().append("Unused classes entry: ").append(className).toString()); } } catch (Exception e) { throw new Exception(new StringBuilder().append("Exception loading classes in module ") .append(((Module) mod.getKey()).getName()).toString(), e); } } return cl; }