List of usage examples for java.net URLClassLoader getResource
public URL getResource(String name)
From source file:io.fabric8.maven.core.util.MavenUtil.java
/** * Returns true if any of the given resources could be found on the given class loader *///from w w w.j a v a 2 s .c om public static boolean hasResource(MavenProject project, String... paths) { URLClassLoader compileClassLoader = getCompileClassLoader(project); for (String path : paths) { try { if (compileClassLoader.getResource(path) != null) { return true; } } catch (Throwable e) { // ignore } } return false; }
From source file:com.videobox.web.util.dwr.AutoAnnotationDiscoveryContainer.java
private URL findResource(ClassLoader loader, String pkgPath) { if (loader == null) { return null; }//from w ww. j a v a 2 s .com if (!(loader instanceof URLClassLoader)) { return findResource(loader.getParent(), pkgPath); } URLClassLoader ucl = (URLClassLoader) loader; URL url = ucl.getResource(pkgPath); if (url == null) { logger.warn("Not found in " + ucl + " -> " + Arrays.asList(ucl.getURLs())); return findResource(loader.getParent(), pkgPath); } return url; }
From source file:com.wavemaker.commons.io.ResourceURLTest.java
@Test public void shouldWorkViaClassLoader() throws Exception { Folder jail = this.root.getFolder("jail").jail(); URLClassLoader classLoader = new URLClassLoader(new URL[] { ResourceURL.get(jail) }); assertThat(IOUtils.toString(classLoader.getResourceAsStream("/a/b/c.txt")), Matchers.is(Matchers.equalTo("c"))); assertThat(classLoader.getResource("/x/y/z.txt").toString(), Matchers.is(Matchers.equalTo("rfs:/x/y/z.txt"))); }
From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java
@Override protected void enhanceContext(final Context context) throws MojoExecutionException { super.enhanceContext(context); try {// www .java 2 s. c o m ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() // .setDependencies(dependencies) // .setLog(getLog()) // .setMavenProject(project) // .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) // .setUseTestClassPath(useTestClasspath); final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator .calculateClassPathEntries(request); final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries(); final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories(); final List<String> jarPaths = extractJars(classLoaderEntries); List<URL> urls = new ArrayList<URL>(jarPaths.size()); for (String jarPath : jarPaths) { try { urls.add(new File(jarPath).toURI().toURL()); } catch (MalformedURLException e) { throw new MojoExecutionException(e.getMessage(), e); } } getLog().debug("classLoaderEntriesCalculator urls: " + urls); final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); final ClassRealm pluginRealm = getTomcatClassLoader(); context.setResources( new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), // getPath(), // getLog()) { @Override public WebResource getClassLoaderResource(String path) { log.debug("RunMojo#getClassLoaderResource: " + path); URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/")); // search in parent (plugin) classloader if (url == null) { url = pluginRealm.getResource(StringUtils.removeStart(path, "/")); } if (url == null) { // try in reactors List<WebResource> webResources = findResourcesInDirectories(path, // classLoaderEntriesCalculatorResult.getBuildDirectories()); // so we return the first one if (!webResources.isEmpty()) { return webResources.get(0); } } if (url == null) { return new EmptyResource(this, getPath()); } return urlToWebResource(url, path); } @Override public WebResource getResource(String path) { log.debug("RunMojo#getResource: " + path); return super.getResource(path); } @Override public WebResource[] getResources(String path) { log.debug("RunMojo#getResources: " + path); return super.getResources(path); } @Override protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) { log.debug("RunMojo#getResourcesInternal: " + path); return super.getResourcesInternal(path, useClassLoaderResources); } @Override public WebResource[] getClassLoaderResources(String path) { try { Enumeration<URL> enumeration = urlClassLoader .findResources(StringUtils.removeStart(path, "/")); List<URL> urlsFound = new ArrayList<URL>(); List<WebResource> webResources = new ArrayList<WebResource>(); while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); urlsFound.add(url); webResources.add(urlToWebResource(url, path)); } log.debug("RunMojo#getClassLoaderResources: " + path + " found : " + urlsFound.toString()); webResources.addAll(findResourcesInDirectories(path, classLoaderEntriesCalculatorResult.getBuildDirectories())); return webResources.toArray(new WebResource[webResources.size()]); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } private List<WebResource> findResourcesInDirectories(String path, List<String> directories) { try { List<WebResource> webResources = new ArrayList<WebResource>(); for (String directory : directories) { File file = new File(directory, path); if (file.exists()) { webResources.add(urlToWebResource(file.toURI().toURL(), path)); } } return webResources; } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } } private WebResource urlToWebResource(URL url, String path) { JarFile jarFile = null; try { // url.getFile is // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class int idx = url.getFile().indexOf('!'); if (idx >= 0) { String filePath = StringUtils.removeStart(url.getFile().substring(0, idx), "file:"); jarFile = new JarFile(filePath); JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/")); return new JarResource(this, // getPath(), // filePath, // url.getPath().substring(0, idx), // jarEntry, // "", // null); } else { return new FileResource(this, webAppPath, new File(url.getFile()), true); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(jarFile); } } }); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (File tmpDir : tmpDirectories) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { // ignore } } } }); if (classLoaderEntries != null) { WebResourceSet webResourceSet = new FileResourceSet() { @Override public WebResource getResource(String path) { if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) { File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB")); return new FileResource(context.getResources(), getPath(), file, true); } if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) { return new FileResource(context.getResources(), getPath(), new File(project.getBuild().getOutputDirectory()), true); } File file = new File(project.getBuild().getOutputDirectory(), path); if (file.exists()) { return new FileResource(context.getResources(), getPath(), file, true); } //if ( StringUtils.endsWith( path, ".class" ) ) { // so we search the class file in the jars for (String jarPath : jarPaths) { File jar = new File(jarPath); if (!jar.exists()) { continue; } try (JarFile jarFile = new JarFile(jar)) { JarEntry jarEntry = (JarEntry) jarFile .getEntry(StringUtils.removeStart(path, "/")); if (jarEntry != null) { return new JarResource(context.getResources(), // getPath(), // jarFile.getName(), // jar.toURI().toString(), // jarEntry, // path, // jarFile.getManifest()); } } catch (IOException e) { getLog().debug("skip error building jar file: " + e.getMessage(), e); } } } return new EmptyResource(null, path); } @Override public String[] list(String path) { if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) { return jarPaths.toArray(new String[jarPaths.size()]); } if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) { return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() }; } return super.list(path); } @Override public Set<String> listWebAppPaths(String path) { if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) { // adding outputDirectory as well? return new HashSet<String>(jarPaths); } File filePath = new File(getWarSourceDirectory(), path); if (filePath.isDirectory()) { Set<String> paths = new HashSet<String>(); String[] files = filePath.list(); if (files == null) { return paths; } for (String file : files) { paths.add(file); } return paths; } else { return Collections.emptySet(); } } @Override public boolean mkdir(String path) { return super.mkdir(path); } @Override public boolean write(String path, InputStream is, boolean overwrite) { return super.write(path, is, overwrite); } @Override protected void checkType(File file) { //super.checkType( file ); } }; context.getResources().addJarResources(webResourceSet); } } catch (TomcatRunException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.cloudfoundry.tools.io.ResourceURLTest.java
@Test public void shouldWorkViaClassLoader() throws Exception { Folder jail = this.root.getFolder("jail").jail(); URLClassLoader classLoader = new URLClassLoader(new URL[] { ResourceURL.get(jail) }); assertThat(IOUtils.toString(classLoader.getResourceAsStream("/a/b/c.txt")), is(equalTo("c"))); assertThat(classLoader.getResource("/x/y/z.txt").toString(), startsWith("rfs:")); assertThat(classLoader.getResource("/x/y/z.txt").toString(), endsWith("/x/y/z.txt")); }
From source file:org.hyperic.hq.product.server.session.ProductPluginDeployer.java
private void deployHqu(String plugin, File pluginFile, boolean initializing) throws Exception { URLClassLoader pluginClassloader = new URLClassLoader(new URL[] { pluginFile.toURI().toURL() }); final String prefix = HQU + "/"; URL hqu = pluginClassloader.getResource(prefix); if (hqu == null) { return;/*from ww w. j av a 2 s .c om*/ } File destDir = new File(hquDir, plugin); boolean exists = destDir.exists(); log.info("Deploying " + plugin + " " + HQU + " to: " + destDir); unpackJar(pluginFile, destDir, prefix); if (!(initializing) && exists) { // update ourselves to avoid having to delete,sleep,unpack renditServer.removePluginDir(destDir.getName()); renditServer.addPluginDir(destDir); } // else Rendit watcher will deploy the new plugin }
From source file:org.mule.tck.junit4.AbstractMuleTestCase.java
/** * Reads the mule-exclusion file for the current test class and * @param test/*w w w . j ava 2 s. com*/ */ protected boolean isTestIncludedInExclusionFile(AbstractMuleTestCase test) { boolean result = false; final String testName = test.getClass().getName(); try { // We find the physical classpath root URL of the test class and // use that to find the correct resource. Works fine everywhere, // regardless of classloaders. See MULE-2414 URL classUrl = ClassUtils.getClassPathRoot(test.getClass()); URLClassLoader tempClassLoader = new URLClassLoader(new URL[] { classUrl }); URL fileUrl = tempClassLoader.getResource("mule-test-exclusions.txt"); if (fileUrl != null) { InputStream in = null; try { in = fileUrl.openStream(); // this iterates over all lines in the exclusion file Iterator<?> lines = IOUtils.lineIterator(in, "UTF-8"); // ..and this finds non-comments that match the test case name result = IteratorUtils.filteredIterator(lines, new Predicate() { @Override public boolean evaluate(Object object) { return StringUtils.equals(testName, StringUtils.trimToEmpty((String) object)); } }).hasNext(); } finally { IOUtils.closeQuietly(in); } } } catch (IOException ioex) { // ignore } return result; }