List of usage examples for java.net URLClassLoader getURLs
public URL[] getURLs()
From source file:org.springframework.cloud.dataflow.app.utils.ClassloaderUtils.java
/** * Creates a ClassLoader for the launched modules by merging the URLs supplied as argument with the URLs that * make up the additional classpath of the launched JVM (retrieved from the application classloader), and * setting the extension classloader of the JVM as parent, if accessible. * * @param urls a list of library URLs// w w w. j ava2 s .c o m * @return the resulting classloader */ public static ClassLoader createModuleClassloader(URL[] urls) { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); if (log.isDebugEnabled()) { log.debug("systemClassLoader is " + systemClassLoader); } if (systemClassLoader instanceof URLClassLoader) { // add the URLs of the application classloader to the created classloader // to compensate for LaunchedURLClassLoader not delegating to parent to retrieve resources @SuppressWarnings("resource") URLClassLoader systemUrlClassLoader = (URLClassLoader) systemClassLoader; URL[] mergedUrls = new URL[urls.length + systemUrlClassLoader.getURLs().length]; if (log.isDebugEnabled()) { log.debug("Original URLs: " + StringUtils.arrayToCommaDelimitedString(urls)); log.debug("Java Classpath URLs: " + StringUtils.arrayToCommaDelimitedString(systemUrlClassLoader.getURLs())); } System.arraycopy(urls, 0, mergedUrls, 0, urls.length); System.arraycopy(systemUrlClassLoader.getURLs(), 0, mergedUrls, urls.length, systemUrlClassLoader.getURLs().length); // add the extension classloader as parent to the created context, if accessible if (log.isDebugEnabled()) { log.debug("Classloader URLs: " + StringUtils.arrayToCommaDelimitedString(mergedUrls)); } return new LaunchedURLClassLoader(mergedUrls, systemUrlClassLoader.getParent()); } return new LaunchedURLClassLoader(urls, systemClassLoader); }
From source file:org.springframework.cloud.function.deployer.ApplicationBootstrap.java
private URL[] findClassPath(Class<?> mainClass) { ClassLoader base = mainClass.getClassLoader(); if (!(base instanceof URLClassLoader)) { try {// www .j a v a 2 s. c o m // Guess the classpath, based on where we can resolve existing resources List<URL> list = Collections.list(mainClass.getClassLoader().getResources("META-INF")); List<URL> result = new ArrayList<>(); result.add(mainClass.getProtectionDomain().getCodeSource().getLocation()); for (URL url : list) { String path = url.toString(); path = path.substring(0, path.length() - "/META-INF".length()) + "/"; result.add(new URL(path)); } return result.toArray(new URL[result.size()]); } catch (IOException e) { throw new IllegalStateException("Cannot find class path", e); } } else { @SuppressWarnings("resource") URLClassLoader urlClassLoader = (URLClassLoader) base; return urlClassLoader.getURLs(); } }
From source file:org.springframework.xd.dirt.plugins.spark.streaming.SparkStreamingPlugin.java
/** * Get the list of jars that this spark module requires. * * @return the list of spark application jars *///from w ww . j ava 2 s .c om private List<String> getApplicationJars(Module module) { // Get jars from module classpath URLClassLoader classLoader = (URLClassLoader) ((SimpleModule) module).getClassLoader(); List<String> jars = new ArrayList<String>(); for (URL url : classLoader.getURLs()) { String file = url.getFile().split("\\!", 2)[0]; if (file.endsWith(".jar")) { jars.add(file); } } // Get message bus libraries Environment env = this.getApplicationContext().getEnvironment(); String jarsLocation = env.resolvePlaceholders(MessageBusClassLoaderFactory.MESSAGE_BUS_JARS_LOCATION); try { Resource[] resources = resolver.getResources(jarsLocation); for (Resource resource : resources) { URL url = resource.getURL(); jars.add(url.getFile()); } } catch (IOException ioe) { throw new RuntimeException(ioe); } // Get necessary dependencies from XD DIRT. URLClassLoader parentClassLoader = (URLClassLoader) classLoader.getParent(); URL[] urls = parentClassLoader.getURLs(); for (URL url : urls) { String file = FilenameUtils.getName(url.getFile()); String fileToAdd = url.getFile().split("\\!", 2)[0]; if (file.endsWith(".jar") && (// Add spark jars file.contains("spark") || // Add SpringXD dependencies file.contains("spring-xd-") || // Add Spring dependencies file.contains("spring-core") || file.contains("spring-integration-core") || file.contains("spring-beans") || file.contains("spring-context") || file.contains("spring-boot") || file.contains("spring-aop") || file.contains("spring-expression") || file.contains("spring-messaging") || file.contains("spring-retry") || file.contains("spring-tx") || file.contains("spring-data-commons") || file.contains("spring-data-redis") || file.contains("commons-pool") || file.contains("jedis") || // Add codec dependency file.contains("kryo") || file.contains("gs-collections"))) { jars.add(fileToAdd); } } return jars; }
From source file:org.tolven.command.TolvenApplication.java
private static URL loadRemoteLibrary(String library, PluginManager pluginManager, URLClassLoader urlClassLoader) { ExtensionPoint extensionPoint = pluginManager.getRegistry().getExtensionPoint(COMMAND_PLUGIN_ID, EXTENSION_POINT_DOWNLOAD_WEB); String hostname = TPFBoot.pluginsWrapper.evaluate( extensionPoint.getParameterDefinition("download.web.hostname").getDefaultValue(), COMMAND_PLUGIN_ID);// ww w . jav a 2s. c o m if (hostname == null) { throw new RuntimeException( "The property download.web.hostname for " + COMMAND_PLUGIN_ID + " evaluated to null"); } String port = TPFBoot.pluginsWrapper.evaluate( extensionPoint.getParameterDefinition("download.web.http.port").getDefaultValue(), COMMAND_PLUGIN_ID); if (port == null) { throw new RuntimeException( "The property download.web.http.port for " + COMMAND_PLUGIN_ID + " evaluated to null"); } String downloadURLString = "http://" + hostname + ":" + port + "/Tolven/download"; String installDirname = TPFBoot.pluginsWrapper.evaluate("#{globalProperty['installation.dir']}"); try { File installRemoteLibDir = new File(installDirname, "remoteLib"); if (!installRemoteLibDir.exists()) { installRemoteLibDir.mkdirs(); } File destFile = new File(installRemoteLibDir, library); URL localURL = destFile.toURI().toURL(); if (Arrays.asList(urlClassLoader.getURLs()).contains(localURL)) { return null; } String urlString = downloadURLString + "/" + library; URL url = new URL(urlString); if (destFile.exists()) { String md5sum = getRemoteChecksum(urlString + ".md5"); if (md5sum.equals(TolvenMessageDigest.checksum(localURL, MESSAGE_DIGEST_ALGORITHM))) { updateLibraryPath(localURL, urlClassLoader); return localURL; } } logger.debug("Downloading remote library from: " + downloadURLString + " to " + installDirname); downloadFile(url, destFile); updateLibraryPath(localURL, urlClassLoader); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not retrieve library: " + library, ex); } }
From source file:rapture.dp.DefaultDecisionProcessExecutor.java
private static String dumpClasspath(ClassLoader loader) { StringBuilder sb = new StringBuilder(); sb.append("Classloader ").append(loader).append(":"); if (loader instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader) loader; sb.append("\n").append(Arrays.toString(ucl.getURLs())); } else//w w w.j a va 2s. c o m sb.append("\n(cannot display components as not a URLClassLoader)"); if (loader.getParent() != null) sb.append(dumpClasspath(loader.getParent())); return sb.toString(); }
From source file:ren.hankai.cordwood.core.ApplicationInitializer.java
/** * ??// www .j a v a 2s. com * * @author hankai * @since Oct 13, 2016 9:52:48 AM */ private static void printClassPaths() { logger.info("Class paths:"); final URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader(); final URL[] urls = cl.getURLs(); for (final URL url : urls) { logger.info(url.getPath()); } }
From source file:schemacrawler.tools.integration.maven.SchemaCrawlerMojo.java
/** * The JDBC driver classpath comes from the configuration of the * SchemaCrawler plugin. The current classloader needs to be "fixed" * to include the JDBC driver in the classpath. * * @throws MavenReportException//from w w w . jav a2 s. c om */ private void fixClassPath() throws MavenReportException { final Log logger = getLog(); try { final List<URL> jdbcJarUrls = new ArrayList<URL>(); for (final Object artifact : project.getArtifacts()) { jdbcJarUrls.add(((Artifact) artifact).getFile().toURI().toURL()); } for (final Artifact artifact : pluginArtifacts) { jdbcJarUrls.add(artifact.getFile().toURI().toURL()); } logger.debug("SchemaCrawler - Maven Plugin: classpath: " + jdbcJarUrls); final Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); addUrlMethod.setAccessible(true); final URLClassLoader classLoader = (URLClassLoader) getClass().getClassLoader(); for (final URL jdbcJarUrl : jdbcJarUrls) { addUrlMethod.invoke(classLoader, jdbcJarUrl); } logger.info("Fixed SchemaCrawler classpath: " + Arrays.asList(classLoader.getURLs())); } catch (final Exception e) { throw new MavenReportException("Error fixing classpath", e); } }
From source file:solidbase.Main.java
/** * Reload SolidBase with an extended classpath. Calls {@link #pass2(String...)} when it's done. * * @param args The arguments from the command line. * @param jars The jars that need to be added to the classpath. * @param verbose Show more information. * @throws SQLExecutionException When an {@link SQLException} is thrown during execution of a database change. *///from w w w. ja v a2 s. c om static protected void reload(String[] args, List<String> jars, boolean verbose) throws SQLExecutionException { if (jars == null || jars.isEmpty()) { // No need to add a new classloader pass2(args); return; } if (verbose) console.println("Extending classpath"); // Add the driver jar(s) to the classpath URLClassLoader classLoader = (URLClassLoader) Main.class.getClassLoader(); URL[] orig = classLoader.getURLs(); URL[] urls; urls = new URL[orig.length + jars.size()]; System.arraycopy(orig, 0, urls, 0, orig.length); int i = orig.length; for (String jar : jars) { File driverJarFile = new File(jar); try { urls[i++] = driverJarFile.toURI().toURL(); } catch (MalformedURLException e) { throw new SystemException(e); } if (verbose) console.println("Adding jar to classpath: " + urls[i - 1]); } if (verbose) console.println(); // Create a new classloader with the new classpath classLoader = new URLClassLoader(urls, Main.class.getClassLoader().getParent()); // Execute the main class through the new classloader with reflection Class<?> main; try { main = classLoader.loadClass("solidbase.Main"); } catch (ClassNotFoundException e) { throw new SystemException(e); } Method method; try { method = main.getDeclaredMethod("pass2", String[].class); } catch (SecurityException e) { throw new SystemException(e); } catch (NoSuchMethodException e) { throw new SystemException(e); } // TODO Should we change the contextClassLoader too? try { method.invoke(method, (Object) args); } catch (IllegalArgumentException e) { throw new SystemException(e); } catch (IllegalAccessException e) { throw new SystemException(e); } catch (InvocationTargetException e) { throw new SystemException(e.getCause()); } }
From source file:sx.blah.discord.modules.ModuleLoader.java
/** * Loads a jar file and automatically adds any modules. * To avoid high overhead recursion, specify the attribute "Discord4J-ModuleClass" in your jar manifest. * Multiple classes should be separated by a semicolon ";". * * @param file The jar file to load./* w w w.j av a 2s . c o m*/ */ public static synchronized void loadExternalModules(File file) { // A bit hacky, but oracle be dumb and encapsulates URLClassLoader#addUrl() if (file.isFile() && file.getName().endsWith(".jar")) { // Can't be a directory and must be a jar try (JarFile jar = new JarFile(file)) { Manifest man = jar.getManifest(); String moduleAttrib = man == null ? null : man.getMainAttributes().getValue("Discord4J-ModuleClass"); String[] moduleClasses = new String[0]; if (moduleAttrib != null) { moduleClasses = moduleAttrib.split(";"); } // Executes would should be URLCLassLoader.addUrl(file.toURI().toURL()); URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL url = file.toURI().toURL(); for (URL it : Arrays.asList(loader.getURLs())) { // Ensures duplicate libraries aren't loaded if (it.equals(url)) { return; } } Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(loader, url); if (moduleClasses.length == 0) { // If the Module Developer has not specified the Implementing Class, revert to recursive search // Scans the jar file for classes which have IModule as a super class List<String> classes = new ArrayList<>(); jar.stream() .filter(jarEntry -> !jarEntry.isDirectory() && jarEntry.getName().endsWith(".class")) .map(path -> path.getName().replace('/', '.').substring(0, path.getName().length() - ".class".length())) .forEach(classes::add); for (String clazz : classes) { try { Class classInstance = loadClass(clazz); if (IModule.class.isAssignableFrom(classInstance) && !classInstance.equals(IModule.class)) { addModuleClass(classInstance); } } catch (NoClassDefFoundError ignored) { /* This can happen. Looking recursively looking through the classpath is hackish... */ } } } else { for (String moduleClass : moduleClasses) { Discord4J.LOGGER.info(LogMarkers.MODULES, "Loading Class from Manifest Attribute: {}", moduleClass); Class classInstance = loadClass(moduleClass); if (IModule.class.isAssignableFrom(classInstance)) addModuleClass(classInstance); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException | ClassNotFoundException e) { Discord4J.LOGGER.error(LogMarkers.MODULES, "Unable to load module " + file.getName() + "!", e); } } }
From source file:tr.com.serkanozal.jcommon.util.ClasspathUtil.java
private static Set<URL> findClasspathsByLoader(ClassLoader loader) { Set<URL> urls = new HashSet<URL>(); if (loader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader) loader; urls.addAll(Arrays.asList(urlLoader.getURLs())); } else {/* w ww . j a v a 2 s.c o m*/ Enumeration<URL> urlEnum; try { urlEnum = loader.getResources(""); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); if (url.getProtocol().startsWith("bundleresource")) { continue; } urls.add(url); } } catch (IOException e) { e.printStackTrace(); } } return urls; }