List of usage examples for java.net URLClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:io.smartspaces.workbench.project.test.IsolatedClassloaderJavaTestRunner.java
/** * Run the given tests in the given class loader. This method is somewhat * complicated, since it needs to use reflsection to isolate the test runner * in a separate class loader that does not derive from the current class. * * @param testCompilationFolder//from w w w .j ava 2 s .co m * the folder containing the test classes * @param classLoader * classLoader to use for running tests * @param context * the build context * * @throws SmartSpacesException * the tests failed */ private void runTestsInIsolation(File testCompilationFolder, URLClassLoader classLoader, ProjectTaskContext context) throws SmartSpacesException { boolean result = false; try { // This code is equivalent to TestRunnerBridge.runTests(testClassNames, // classLoader), except // that it is sanitized through the test class loader. Class<?> testRunnerClass = classLoader.loadClass(ISOLATED_TESTRUNNER_CLASSNAME); Method runner = testRunnerClass.getMethod(ISOLATED_TESTRUNNER_METHODNAME, File.class, URLClassLoader.class, Log.class); Object testRunner = testRunnerClass.newInstance(); result = (Boolean) runner.invoke(testRunner, testCompilationFolder, classLoader, context.getWorkbenchTaskContext().getWorkbench().getLog()); } catch (Exception e) { // This catch here for the reflection errors context.getWorkbenchTaskContext().getWorkbench().getLog().error("Error running tests", e); throw new SmartSpacesException("Error running tests", e); } if (!result) { throw new SimpleSmartSpacesException("Unit tests failed"); } }
From source file:de.xplib.xdbm.ui.dialog.FirstStartSetup.java
/** * @param aeIn ...//from w w w. j a v a 2 s . co m * @return Does the test fail or run? */ private boolean actionPerformedTest(final ActionEvent aeIn) { Locale l = this.config.getLocale(); try { String jar = jfField.getText(); if (!jar.startsWith("file://")) { jar = "file://" + jar; } URLClassLoader ucl = new URLClassLoader(new URL[] { new URL(jar) }); Class clazz = ucl.loadClass(jtfClass.getText()); Database db = (Database) clazz.newInstance(); DatabaseManager.registerDatabase(db); String uri = this.jtfDbURI.getText().trim(); if (uri != null && !uri.equals("")) { try { Collection coll = DatabaseManager.getCollection(uri); coll.close(); } catch (XMLDBException e1) { throw new Exception( MessageManager.getText("setup.dialog.test.error.uri", "text", new Object[] { uri }, l)); } } return true; } catch (Exception e) { String msg = "<html>" + MessageManager.getText("setup.dialog.test.error.label", "text", new Object[0], l) + "<br>" + e.getMessage() + "</html>"; String title = MessageManager.getText("setup.dialog.test.error.title", "text", new Object[0], l); JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE); return false; } }
From source file:com.spotify.docgenerator.DocgeneratorMojo.java
private Class<?> getClassForName(final String name) throws ClassNotFoundException, MalformedURLException { final URLClassLoader loader = getPluginClassLoader(); return loader.loadClass(name); }
From source file:org.stanwood.media.Controller.java
@SuppressWarnings("unchecked") private void registerPlugins() throws ConfigException { for (Plugin plugin : configReader.getPlugins()) { try {//from w w w . ja v a2s . co m Class<?> clazz; if (plugin.getJar() != null) { URL url = new URL("jar:file:" + plugin.getJar() + "!/"); //$NON-NLS-1$//$NON-NLS-2$ URLClassLoader clazzLoader = new URLClassLoader(new URL[] { url }); clazz = clazzLoader.loadClass(plugin.getPluginClass()); } else { clazz = Class.forName(plugin.getPluginClass()); } Class<? extends ExtensionInfo<?>> targetClass = (Class<? extends ExtensionInfo<?>>) clazz .asSubclass(ExtensionInfo.class); ExtensionInfo<?> info = targetClass.newInstance(); registerExtension(info); } catch (MalformedURLException e) { throw new ConfigException(MessageFormat .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$ } catch (ClassNotFoundException e) { throw new ConfigException(MessageFormat .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$ } catch (InstantiationException e) { throw new ConfigException(MessageFormat .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$ } catch (IllegalAccessException e) { throw new ConfigException(MessageFormat .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$ } } }
From source file:com.stratio.explorer.interpreter.InterpreterFactory.java
public Interpreter createRepl(String dirName, String className, Properties property) { logger.info("Create repl {} from {}", className, dirName); ClassLoader oldcl = Thread.currentThread().getContextClassLoader(); try {//ww w . ja v a 2 s . c o m URLClassLoader ccl = cleanCl.get(dirName); if (ccl == null) { // classloader fallback ccl = URLClassLoader.newInstance(new URL[] {}, oldcl); } boolean separateCL = true; try { // check if server's classloader has driver already. Class cls = this.getClass().forName(className); if (cls != null) { separateCL = false; } } catch (Exception e) { // nothing to do. } URLClassLoader cl; if (separateCL == true) { cl = URLClassLoader.newInstance(new URL[] {}, ccl); } else { cl = (URLClassLoader) ccl; } Thread.currentThread().setContextClassLoader(cl); Class<Interpreter> replClass = (Class<Interpreter>) cl.loadClass(className); Constructor<Interpreter> constructor = replClass.getConstructor(new Class[] { Properties.class }); Interpreter repl = constructor.newInstance(property); if (conf.containsKey("args")) { property.put("args", conf.getProperty("args")); } property.put("share", share); property.put("classloaderUrls", ccl.getURLs()); return new ClassloaderInterpreter(repl, cl, property); } catch (SecurityException e) { throw new InterpreterException(e); } catch (NoSuchMethodException e) { throw new InterpreterException(e); } catch (IllegalArgumentException e) { throw new InterpreterException(e); } catch (InstantiationException e) { throw new InterpreterException(e); } catch (IllegalAccessException e) { throw new InterpreterException(e); } catch (InvocationTargetException e) { throw new InterpreterException(e); } catch (ClassNotFoundException e) { throw new InterpreterException(e); } finally { Thread.currentThread().setContextClassLoader(oldcl); } }
From source file:com.sleepcamel.ifdtoutils.MvnPluginMojo.java
@SuppressWarnings("deprecation") public void execute() throws MojoExecutionException { try {//from ww w . j av a 2s. co m if (outputDirectory == null || !outputDirectory.exists()) { throw new MojoExecutionException("Class directory must exist"); } URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { outputDirectory.toURL() }, getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(urlClassLoader); Collection<File> listFiles = FileUtils.listFiles(outputDirectory, new String[] { "class" }, true); for (File file : listFiles) { getLog().debug("\nClass found: " + file.getName()); try { Class<?> loadedClass = urlClassLoader.loadClass(fileToClass(outputDirectory, file)); getLog().debug("Class " + loadedClass.getName() + " loaded"); if (!loadedClass.isInterface()) { getLog().debug("Not an interface :("); continue; } ToDTO annotation = loadedClass.getAnnotation(ToDTO.class); if (annotation == null) { getLog().debug("No annotation not found :("); } else { dtosToGenerate.add(loadedClass); getLog().debug("Annotation found!"); } } catch (ClassNotFoundException e) { } } getLog().info("Found " + dtosToGenerate.size() + " interfaces to generate their DTOs...\n"); for (Class<?> interfaceClass : dtosToGenerate) { String interfaceClassName = interfaceClass.getName(); try { Thread.currentThread().getContextClassLoader() .loadClass(InterfaceDTOInfo.getInfo(interfaceClass).getDTOCanonicalName()); getLog().info("DTO for interface " + interfaceClassName + " exists, skipping generation\n"); } catch (ClassNotFoundException e) { getLog().info("Generating dto for interface " + interfaceClassName + "..."); DTOClassGenerator.generateDTOForInterface(interfaceClass, outputDirectory.getAbsolutePath()); getLog().info("DTO generated for interface " + interfaceClassName + "\n"); } } } catch (Exception e1) { throw new MojoExecutionException(e1.getMessage()); } }
From source file:com.cinchapi.concourse.server.plugin.PluginManager.java
/** * Get all the {@link Plugin plugins} in the {@code bundle} and * {@link #launch(String, Path, Class, List) launch} them each in a separate * JVM.// ww w . j a va2s . co m * * @param bundle the path to a bundle directory, which is a sub-directory of * the {@link #home} directory. * @param runAfterInstallHook a flag that indicates whether the * {@link Plugin#afterInstall()} hook should be run */ protected void activate(String bundle, boolean runAfterInstallHook) { try { String lib = home + File.separator + bundle + File.separator + "lib" + File.separator; Path prefs = Paths.get(home, bundle, PluginConfiguration.PLUGIN_PREFS_FILENAME); Iterator<Path> content = Files.newDirectoryStream(Paths.get(lib)).iterator(); // Go through all the jars in the plugin's lib directory and compile // the appropriate classpath while identifying jars that might // contain plugin endpoints. List<URL> urls = Lists.newArrayList(); List<String> classpath = Lists.newArrayList(); while (content.hasNext()) { String filename = content.next().getFileName().toString(); URL url = new File(lib + filename).toURI().toURL(); if (!SYSTEM_JARS.contains(filename)) { // NOTE: by checking for exact name matches, we will // accidentally include system jars that contain different // versions. urls.add(url); } classpath.add(url.getFile()); } // Create a ClassLoader that only contains jars with possible plugin // endpoints and search for any applicable classes. URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0]), null); Class parent = loader.loadClass(Plugin.class.getName()); Class realTimeParent = loader.loadClass(RealTimePlugin.class.getName()); Reflections reflection = new Reflections(new ConfigurationBuilder().addClassLoader(loader) .addUrls(ClasspathHelper.forClassLoader(loader))); Set<Class<?>> plugins = reflection.getSubTypesOf(parent); for (final Class<?> plugin : plugins) { if (runAfterInstallHook) { Object instance = Reflection.newInstance(plugin); Reflection.call(instance, "afterInstall"); } launch(bundle, prefs, plugin, classpath); startEventLoop(plugin.getName()); if (realTimeParent.isAssignableFrom(plugin)) { initRealTimeStream(plugin.getName()); } } } catch (IOException | ClassNotFoundException e) { Logger.error("An error occurred while trying to activate the plugin bundle '{}'", bundle, e); throw Throwables.propagate(e); } }
From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java
private void executeAntlrInIsolatedClassLoader(String[] args, Artifact antlrArtifact) throws MojoExecutionException { try {/*from ww w . j a v a 2s .com*/ URLClassLoader classLoader = new URLClassLoader(new URL[] { antlrArtifact.getFile().toURL() }, ClassLoader.getSystemClassLoader()); Class toolClass = classLoader.loadClass("antlr.Tool"); toolClass.getMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { args }); } catch (MalformedURLException e) { throw new MojoExecutionException("Unable to resolve antlr:antlr artifact url", e); } catch (ClassNotFoundException e) { throw new MojoExecutionException("could not locate antlr.Tool class"); } catch (NoSuchMethodException e) { throw new MojoExecutionException("error locating antlt.Tool#main", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("error perforing antlt.Tool#main", e.getTargetException()); } catch (IllegalAccessException e) { throw new MojoExecutionException("error perforing antlt.Tool#main", e); } }
From source file:org.ops4j.pax.runner.platform.InProcessJavaRunner.java
/** * {@inheritDoc}/*from w w w . ja v a2s . c om*/ */ public synchronized void exec(final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory) throws PlatformException { if (m_frameworkActive) { throw new PlatformException("Platform already started"); } m_frameworkActive = true; final URLClassLoader classLoader = createClassLoader(classpath); final Properties systemProps = extractSystemProperties(vmOptions); final ClassLoader tcclBackup = Thread.currentThread().getContextClassLoader(); final Properties systemPropsBackup = System.getProperties(); final URLStreamHandlerFactory handlerFactoryBackup = URLUtils.resetURLStreamHandlerFactory(); try { Thread.currentThread().setContextClassLoader(classLoader); System.setProperties(systemProps); final Class<?> clazz = classLoader.loadClass(mainClass); final Method mainMethod = clazz.getMethod("main", String[].class); LOG.info("Runner has successfully finished his job!"); Info.println(); // print an empty line mainMethod.invoke(null, new Object[] { programOptions }); } catch (ClassNotFoundException e) { throw new PlatformException("Cannot find target framework main class", e); } catch (NoSuchMethodException e) { throw new PlatformException("Cannot find target framework main method", e); } catch (IllegalAccessException e) { throw new PlatformException("Cannot run the target framework", e); } catch (InvocationTargetException e) { throw new PlatformException("Cannot run the target framework", e); } finally { URLUtils.setURLStreamHandlerFactory(handlerFactoryBackup); System.setProperties(systemPropsBackup); Thread.currentThread().setContextClassLoader(tcclBackup); } }
From source file:org.radargun.utils.ClassLoadHelper.java
public Object createInstance(String classFqn) throws Exception { if (!useSmartClassLoading) { return Class.forName(classFqn).newInstance(); }/* w w w . j a v a 2s . c o m*/ URLClassLoader classLoader; String prevProduct = (String) state.get(prevProductKey); if (prevProduct == null || !prevProduct.equals(thisProduct)) { classLoader = Utils.buildProductSpecificClassLoader(thisProduct, instantiator.getClassLoader()); state.put(classLoaderKey, classLoader); state.put(prevProductKey, thisProduct); } else {//same product and there is a class loader classLoader = (URLClassLoader) state.get(classLoaderKey); } log.info("Creating newInstance " + classFqn + " with classloader " + classLoader); Thread.currentThread().setContextClassLoader(classLoader); return classLoader.loadClass(classFqn).newInstance(); }