List of usage examples for java.net URLClassLoader URLClassLoader
URLClassLoader(URL[] urls, AccessControlContext acc)
From source file:meme.singularsyntax.mojo.JavaflowEnhanceMojo.java
@SuppressWarnings("unchecked") private void prepareClasspath() throws MojoExecutionException { List<String> runtimeClasspathElements = null; URLClassLoader classLoader = null; try {//ww w . ja va2 s . com runtimeClasspathElements = project.getCompileClasspathElements(); URL[] runtimeUrls = new URL[runtimeClasspathElements.size()]; for (int ii = 0; ii < runtimeClasspathElements.size(); ii++) { String element = runtimeClasspathElements.get(ii); File elementFile = new File(element); runtimeUrls[ii] = elementFile.toURI().toURL(); } classLoader = new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(classLoader); } catch (DependencyResolutionRequiredException e) { throw new MojoExecutionException(e.getMessage()); } catch (MalformedURLException e) { throw new MojoExecutionException(e.getMessage()); } }
From source file:org.eclipse.wb.internal.core.xml.model.EditorContext.java
/** * @return the composite {@link ClassLoader} based on given main {@link ClassLoader} with addition * of {@link BundleClassLoader}'s and {@link IByteCodeProcessor}'s. *///from w w w . jav a2 s . c o m private void addLibraryClassLoaders(CompositeClassLoader compositeClassLoader, ClassLoader mainClassLoader) throws Exception { List<IConfigurationElement> toolkitElements = DescriptionHelper.getToolkitElements(m_toolkitId); for (IConfigurationElement toolkitElement : toolkitElements) { IConfigurationElement[] contributorElements = toolkitElement.getChildren("classLoader-library"); if (contributorElements.length != 0) { URL[] urls = new URL[contributorElements.length]; for (int i = 0; i < contributorElements.length; i++) { IConfigurationElement contributorElement = contributorElements[i]; Bundle bundle = getExistingBundle(contributorElement); // prepare URL for JAR String jarPath = contributorElement.getAttribute("jar"); URL jarEntry = bundle.getEntry(jarPath); Assert.isNotNull(jarEntry, "Unable to find %s in %s", jarPath, bundle.getSymbolicName()); urls[i] = FileLocator.toFileURL(jarEntry); } // add ClassLoader with all libraries compositeClassLoader.add(new URLClassLoader(urls, mainClassLoader), null); } } }
From source file:com.ibm.team.build.internal.hjplugin.RTCFacadeFactory.java
private static RTCFacadeWrapper newFacade(String fullClassName, File toolkitFile, PrintStream debugLog) throws Exception { if (!toolkitFile.exists()) { throw new IllegalArgumentException( Messages.RTCFacadeFactory_toolkit_not_found(toolkitFile.getAbsolutePath())); }//from w w w .j a v a 2 s .c o m if (!toolkitFile.isDirectory()) { throw new IllegalArgumentException( Messages.RTCFacadeFactory_toolkit_path_not_directory(toolkitFile.getAbsolutePath())); } RTCFacadeWrapper result = new RTCFacadeWrapper(); URL[] toolkitURLs = getToolkitJarURLs(toolkitFile, debugLog); Class<?> originalClass = RTCFacadeFactory.class; ClassLoader originalClassLoader = originalClass.getClassLoader(); debug(debugLog, "Original class loader: " + originalClassLoader); //$NON-NLS-1$ // Get the jar for the hjplugin-rtc jar. URL[] combinedURLs; URL hjplugin_rtcJar = getFacadeJarURL(debugLog); if (hjplugin_rtcJar != null) { combinedURLs = new URL[toolkitURLs.length + 1]; combinedURLs[0] = hjplugin_rtcJar; System.arraycopy(toolkitURLs, 0, combinedURLs, 1, toolkitURLs.length); } else { combinedURLs = toolkitURLs; } debug(debugLog, "System class loader " + ClassLoader.getSystemClassLoader()); //$NON-NLS-1$ // We want the parent class loader to exclude the class loader which would normally // load classes from the hjplugin-rtc jar (because that class loader doesn't include // the toolkit jars). ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader(); // Normally the system class loader and the original class loader are different. // However in the case of running the tests within our build, the system class loader // is the original class loader with our single jar (and not its dependencies from the // toolkit) which results in ClassNotFound for classes we depend on (i.e. IProgressMonitor). // So use the parent in this case. if (parentClassLoader == originalClassLoader) { debug(debugLog, "System class loader and original are the same. Using parent " //$NON-NLS-1$ + originalClassLoader.getParent()); parentClassLoader = originalClassLoader.getParent(); } if (Boolean.parseBoolean(System.getProperty(DISABLE_RTC_FACADE_CLASS_LOADER_PROPERTY, "false"))) { //$NON-NLS-1$ debug(debugLog, "RTCFacadeClassLoader disabled, using URLClassLoader"); //$NON-NLS-1$ result.newClassLoader = new URLClassLoader(combinedURLs, parentClassLoader); } else { result.newClassLoader = new RTCFacadeClassLoader(combinedURLs, parentClassLoader); } debug(debugLog, "new classloader: " + result.newClassLoader); //$NON-NLS-1$ Class<?> facadeClass = result.newClassLoader.loadClass(fullClassName); debug(debugLog, "facadeClass: " + facadeClass); //$NON-NLS-1$ debug(debugLog, "facadeClass classloader: " + facadeClass.getClassLoader()); //$NON-NLS-1$ // using the new class loader get the facade instance // then revert immediately back to the original class loader ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(result.newClassLoader); try { result.facade = facadeClass.newInstance(); } finally { Thread.currentThread().setContextClassLoader(originalContextClassLoader); } debug(debugLog, "facade: " + result.facade); //$NON-NLS-1$ return result; }
From source file:org.apache.hadoop.filecache.TaskDistributedCacheManager.java
/** * Creates a class loader that includes the designated * files and archives./*from www .jav a 2 s .c o m*/ */ public ClassLoader makeClassLoader(final ClassLoader parent) throws MalformedURLException { final URL[] urls = new URL[classPaths.size()]; for (int i = 0; i < classPaths.size(); ++i) { urls[i] = new File(classPaths.get(i)).toURI().toURL(); } return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return new URLClassLoader(urls, parent); } }); }
From source file:info.novatec.testit.livingdoc.maven.plugin.SpecificationRunnerMojo.java
private ClassLoader createClassLoader() throws MojoExecutionException { List<URL> urls = new ArrayList<URL>(); for (Iterator<?> it = classpathElements.iterator(); it.hasNext();) { String s = (String) it.next(); urls.add(toURL(new File(s))); }// w w w .j a v a 2s . c om urls.add(toURL(fixtureOutputDirectory)); if (!containsLivingDocCore(urls)) { urls.add(getDependencyURL("livingdoc-core")); } urls.add(getDependencyURL("commons-codec")); URL[] classpath = urls.toArray(new URL[urls.size()]); return new URLClassLoader(classpath, ClassLoader.getSystemClassLoader()); }
From source file:org.easyrec.plugin.container.PluginRegistry.java
@SuppressWarnings({ "unchecked" }) public PluginVO checkPlugin(byte[] file) throws Exception { PluginVO plugin;// ww w. j a v a2s .com FileOutputStream fos = null; URLClassLoader ucl; ClassPathXmlApplicationContext cax = null; File tmpFile = null; try { if (file == null) throw new IllegalArgumentException("Passed file must not be null!"); tmpFile = File.createTempFile("plugin", null); tmpFile.deleteOnExit(); fos = new FileOutputStream(tmpFile); fos.write(file); fos.close(); // check if plugin is valid ucl = new URLClassLoader(new URL[] { tmpFile.toURI().toURL() }, this.getClass().getClassLoader()); if (ucl.getResourceAsStream(DEFAULT_PLUGIN_CONFIG_FILE) != null) { cax = new ClassPathXmlApplicationContext(new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false, appContext); cax.setClassLoader(ucl); logger.info("Classloader: " + cax.getClassLoader()); cax.refresh(); Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class); if (beans.isEmpty()) { logger.debug("No class implementing a generator could be found. Plugin rejected!"); throw new Exception("No class implementing a generator could be found. Plugin rejected!"); } Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next(); logger.info(String.format("Plugin successfully validated! class: %s name: %s, id: %s", generator.getClass(), generator.getDisplayName(), generator.getId())); cax.getAutowireCapableBeanFactory().autowireBeanProperties(generator, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); plugin = new PluginVO(generator.getDisplayName(), generator.getId().getUri(), generator.getId().getVersion(), LifecyclePhase.NOT_INSTALLED.toString(), file, null); if (tmpFile.delete()) logger.info("tmpFile deleted successfully"); return plugin; } else { // config file not found logger.debug("No valid config file found in the supplied .jar file. Plugin rejected!"); throw new Exception("No valid config file found in the supplied .jar file. Plugin rejected!"); } } catch (Exception e) { logger.error("An Exception occurred while checking the plugin!", e); throw e; } finally { if (fos != null) fos.close(); if ((cax != null) && (!cax.isActive())) cax.close(); if (tmpFile != null) try { if (!tmpFile.delete()) logger.warn("could not delete tmpFile"); } catch (SecurityException se) { logger.error("Could not delete temporary file! Please check permissions!", se); } } }
From source file:net.thucydides.maven.plugin.GenerateScenarioStepsMojo.java
private ClassLoader getClassLoader() throws MojoFailureException, MojoExecutionException { ClassLoader pluginClassLoader = getClass().getClassLoader(); Set<URL> projectClasspathList = getUrlsForCustomClasspath(); ClassLoader projectClassLoader = new URLClassLoader( projectClasspathList.toArray(new URL[projectClasspathList.size()]), pluginClassLoader); return projectClassLoader; }
From source file:com.hurence.logisland.service.elasticsearch.Elasticsearch_5_4_0_ClientService.java
private TransportClient getTransportClient(Settings.Builder settingsBuilder, String shieldUrl, String username, String password) throws MalformedURLException { // See if the Elasticsearch Shield JAR location was specified, and add the plugin if so. Also create the // authorization token if username and password are supplied. final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); if (!StringUtils.isBlank(shieldUrl)) { ClassLoader shieldClassLoader = new URLClassLoader(new URL[] { new File(shieldUrl).toURI().toURL() }, this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(shieldClassLoader); try {/*from w w w . j ava2 s . c om*/ //Class shieldPluginClass = Class.forName("org.elasticsearch.shield.ShieldPlugin", true, shieldClassLoader); //builder = builder.addPlugin(shieldPluginClass); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { // Need a couple of classes from the Shield plugin to build the token Class usernamePasswordTokenClass = Class.forName( "org.elasticsearch.shield.authc.support.UsernamePasswordToken", true, shieldClassLoader); Class securedStringClass = Class.forName("org.elasticsearch.shield.authc.support.SecuredString", true, shieldClassLoader); Constructor<?> securedStringCtor = securedStringClass.getConstructor(char[].class); Object securePasswordString = securedStringCtor.newInstance(password.toCharArray()); Method basicAuthHeaderValue = usernamePasswordTokenClass.getMethod("basicAuthHeaderValue", String.class, securedStringClass); authToken = (String) basicAuthHeaderValue.invoke(null, username, securePasswordString); } } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException shieldLoadException) { getLogger().debug( "Did not detect Elasticsearch Shield plugin, secure connections and/or authorization will not be available"); } } else { //logger.debug("No Shield plugin location specified, secure connections and/or authorization will not be available"); } TransportClient transportClient = new PreBuiltTransportClient(settingsBuilder.build()); Thread.currentThread().setContextClassLoader(originalClassLoader); return transportClient; }
From source file:org.apache.jxtadoop.util.GenericOptionsParser.java
/** * Modify configuration according user-specified generic options * @param conf Configuration to be modified * @param line User-specified generic options *///w w w. j av a 2 s .com private void processGeneralOptions(Configuration conf, CommandLine line) { if (line.hasOption("fs")) { FileSystem.setDefaultUri(conf, line.getOptionValue("fs")); } if (line.hasOption("jt")) { conf.set("mapred.job.tracker", line.getOptionValue("jt")); } if (line.hasOption("conf")) { String[] values = line.getOptionValues("conf"); for (String value : values) { conf.addResource(new Path(value)); } } try { if (line.hasOption("libjars")) { conf.set("tmpjars", validateFiles(line.getOptionValue("libjars"), conf)); //setting libjars in client classpath URL[] libjars = getLibJars(conf); if (libjars != null && libjars.length > 0) { conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader())); Thread.currentThread().setContextClassLoader( new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader())); } } if (line.hasOption("files")) { conf.set("tmpfiles", validateFiles(line.getOptionValue("files"), conf)); } if (line.hasOption("archives")) { conf.set("tmparchives", validateFiles(line.getOptionValue("archives"), conf)); } } catch (IOException ioe) { System.err.println(StringUtils.stringifyException(ioe)); } if (line.hasOption('D')) { String[] property = line.getOptionValues('D'); for (String prop : property) { String[] keyval = prop.split("=", 2); if (keyval.length == 2) { conf.set(keyval[0], keyval[1]); } } } conf.setBoolean("mapred.used.genericoptionsparser", true); }
From source file:com.hurence.logisland.service.elasticsearch.Elasticsearch_2_4_0_ClientService.java
private TransportClient getTransportClient(Settings.Builder settingsBuilder, String shieldUrl, String username, String password) throws MalformedURLException { // Create new transport client using the Builder pattern TransportClient.Builder builder = TransportClient.builder(); // See if the Elasticsearch Shield JAR location was specified, and add the plugin if so. Also create the // authorization token if username and password are supplied. final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); if (!StringUtils.isBlank(shieldUrl)) { ClassLoader shieldClassLoader = new URLClassLoader(new URL[] { new File(shieldUrl).toURI().toURL() }, this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(shieldClassLoader); try {/*from w ww . ja v a 2s . c om*/ Class shieldPluginClass = Class.forName("org.elasticsearch.shield.ShieldPlugin", true, shieldClassLoader); builder = builder.addPlugin(shieldPluginClass); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { // Need a couple of classes from the Shield plugin to build the token Class usernamePasswordTokenClass = Class.forName( "org.elasticsearch.shield.authc.support.UsernamePasswordToken", true, shieldClassLoader); Class securedStringClass = Class.forName("org.elasticsearch.shield.authc.support.SecuredString", true, shieldClassLoader); Constructor<?> securedStringCtor = securedStringClass.getConstructor(char[].class); Object securePasswordString = securedStringCtor.newInstance(password.toCharArray()); Method basicAuthHeaderValue = usernamePasswordTokenClass.getMethod("basicAuthHeaderValue", String.class, securedStringClass); authToken = (String) basicAuthHeaderValue.invoke(null, username, securePasswordString); } } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException shieldLoadException) { getLogger().debug( "Did not detect Elasticsearch Shield plugin, secure connections and/or authorization will not be available"); } } else { //logger.debug("No Shield plugin location specified, secure connections and/or authorization will not be available"); } TransportClient transportClient = builder.settings(settingsBuilder.build()).build(); Thread.currentThread().setContextClassLoader(originalClassLoader); return transportClient; }