List of usage examples for java.net URLClassLoader findResource
public URL findResource(final String name)
From source file:Which4J.java
/** * Iterate over the system classpath defined by "java.class.path" searching * for all occurrances of the given class name. * /*from w w w . ja va 2 s.com*/ * @param classname the fully qualified class name to search for */ private static void findIt(String classname) { try { // get the system classpath String classpath = System.getProperty("java.class.path", ""); if (classpath.equals("")) { System.err.println("error: classpath is not set"); } if (debug) { System.out.println("classname: " + classname); System.out.println("system classpath = " + classpath); } if (isPrimitiveOrVoid(classname)) { System.out.println("'" + classname + "' primitive"); return; } StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator); while (st.hasMoreTokens()) { String token = st.nextToken(); File classpathElement = new File(token); if (debug) System.out.println(classpathElement.isDirectory() ? "dir: " + token : "jar: " + token); URL[] url = { classpathElement.toURL() }; URLClassLoader cl = URLClassLoader.newInstance(url, null); String classnameAsResource = classname.replace('.', '/') + ".class"; URL it = cl.findResource(classnameAsResource); if (it != null) { System.out.println("found in: " + token); System.out.println(" url: " + it.toString()); System.out.println(""); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.stacksync.desktop.util.FileUtil.java
public static String getPropertyFromManifest(String manifestPath, String property) { try {/*from w ww . jav a2s . c o m*/ URLClassLoader cl = (URLClassLoader) FileUtil.class.getClassLoader(); URL url = cl.findResource(manifestPath); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); return attr.getValue(property); } catch (IOException ex) { logger.debug("Exception: ", ex); return null; } }
From source file:eu.chocolatejar.eclipse.plugin.cleaner.Main.java
/** * Read version from jar manifest, if it fails the exception is swallow and * empty string is returned// ww w .j a v a2 s . c o m */ private String getImplementationVersion() { try { URLClassLoader cl = (URLClassLoader) Main.class.getClassLoader(); URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes mainAttribs = manifest.getMainAttributes(); String version = mainAttribs.getValue("Implementation-Version"); if (version != null) { return version; } } catch (Exception e) { logger.trace("Unable to read a manifest version of this program.", e); } return "X.X.X.X"; }
From source file:dip.world.variant.VariantManager.java
/** * Gets a specific resource for a Variant or a SymbolPack, given a URL to * the package and a reference URI. Threadsafe. * <p>/* w ww.java2s. c om*/ * Typically, getResource(Variant, URI) or getResource(SymbolPack, URI) is * preferred to this method. * */ public static synchronized URL getResource(URL packURL, URI uri) { // ensure we have been initialized... checkVM(); // if we are in webstart, assume that this is a webstart jar. if (vm.isInWebstart) { URL url = getWSResource(packURL, uri); // if cannot get it, fall through. if (url != null) { return url; } } // if URI has a defined scheme, convert to a URL (if possible) and return it. if (uri.getScheme() != null) { try { return uri.toURL(); } catch (MalformedURLException e) { return null; } } // resolve & load. URLClassLoader classLoader = getClassLoader(packURL); return classLoader.findResource(uri.toString()); }
From source file:dip.world.variant.VariantManager.java
/** * Initiaize the VariantManager. /*from w ww . j a va 2 s . c om*/ * <p> * An exception is thrown if no File paths are specified. A "." may be used * to specify th ecurrent directory. * <p> * Loaded XML may be validated if the isValidating flag is set to true. * */ public static synchronized void init(final List<File> searchPaths, boolean isValidating) throws javax.xml.parsers.ParserConfigurationException, NoVariantsException { long ttime = System.currentTimeMillis(); long vptime = ttime; Log.println("VariantManager.init()"); if (searchPaths == null || searchPaths.isEmpty()) { throw new IllegalArgumentException(); } if (vm != null) { // perform cleanup vm.variantMap.clear(); vm.variants = new ArrayList<Variant>(); vm.currentUCL = null; vm.currentPackageURL = null; vm.symbolPacks = new ArrayList<SymbolPack>(); vm.symbolMap.clear(); } vm = new VariantManager(); // find plugins, create plugin loader final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS); // setup document builder DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // this may improve performance, and really only apply to Xerces dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE); dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096)); dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); } catch (Exception e) { Log.println("VM: Could not set XML feature.", e); } dbf.setValidating(isValidating); dbf.setCoalescing(false); dbf.setIgnoringComments(true); // setup variant parser XMLVariantParser variantParser = new XMLVariantParser(dbf); // for each plugin, attempt to find the "variants.xml" file inside. // if it does not exist, we will not load the file. If it does, we will parse it, // and associate the variant with the URL in a hashtable. for (final URL pluginURL : pluginURLs) { URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL }); URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME); if (variantXMLURL != null) { String pluginName = getFile(pluginURL); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; try { is = new BufferedInputStream(variantXMLURL.openStream()); variantParser.parse(is, pluginURL); final List<Variant> variants = variantParser.getVariants(); // add variants; variants with same name (but older versions) are // replaced with same-name newer versioned variants for (final Variant variant : variants) { addVariant(variant, pluginName, pluginURL); } } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, pluginURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if we are in webstart, search for variants within webstart jars Enumeration<URL> enum2 = null; ClassLoader cl = null; if (vm.isInWebstart) { cl = vm.getClass().getClassLoader(); try { enum2 = cl.getResources(VARIANT_FILE_NAME); } catch (IOException e) { enum2 = null; } if (enum2 != null) { while (enum2.hasMoreElements()) { URL variantURL = enum2.nextElement(); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; String pluginName = getWSPluginName(variantURL); try { is = new BufferedInputStream(variantURL.openStream()); variantParser.parse(is, variantURL); final List<Variant> variants = variantParser.getVariants(); // add variants; variants with same name (but older versions) are // replaced with same-name newer versioned variants for (final Variant variant : variants) { addVariant(variant, pluginName, variantURL); } } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, variantURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if(enum2 != null) } // check: did we find *any* variants? Throw an exception. if (vm.variantMap.isEmpty()) { StringBuffer msg = new StringBuffer(256); msg.append("No variants found on path: "); for (final File searchPath : searchPaths) { msg.append(searchPath); msg.append("; "); } throw new NoVariantsException(msg.toString()); } Log.printTimed(vptime, "VariantManager: variant parsing time: "); ///////////////// SYMBOLS ///////////////////////// // now, parse symbol packs XMLSymbolParser symbolParser = new XMLSymbolParser(dbf); // find plugins, create plugin loader final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS); // for each plugin, attempt to find the "variants.xml" file inside. // if it does not exist, we will not load the file. If it does, we will parse it, // and associate the variant with the URL in a hashtable. for (final URL pluginURL : pluginURLs2) { URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL }); URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME); if (symbolXMLURL != null) { String pluginName = getFile(pluginURL); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; try { is = new BufferedInputStream(symbolXMLURL.openStream()); symbolParser.parse(is, pluginURL); addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL); } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, pluginURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if we are in webstart, search for variants within webstart jars enum2 = null; cl = null; if (vm.isInWebstart) { cl = vm.getClass().getClassLoader(); try { enum2 = cl.getResources(SYMBOL_FILE_NAME); } catch (IOException e) { enum2 = null; } if (enum2 != null) { while (enum2.hasMoreElements()) { URL symbolURL = enum2.nextElement(); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; String pluginName = getWSPluginName(symbolURL); try { is = new BufferedInputStream(symbolURL.openStream()); symbolParser.parse(is, symbolURL); addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL); } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, symbolURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if(enum2 != null) } // if(isInWebStart) // check: did we find *any* symbol packs? Throw an exception. if (vm.symbolMap.isEmpty()) { StringBuffer msg = new StringBuffer(256); msg.append("No SymbolPacks found on path: "); for (final File searchPath : searchPaths) { msg.append(searchPath); msg.append("; "); } throw new NoVariantsException(msg.toString()); } Log.printTimed(ttime, "VariantManager: total parsing time: "); }
From source file:com.izforge.izpack.installer.unpacker.UnpackerBase.java
private void logIntro() { final String startMessage = messages.get("installer.started"); char[] chars = new char[startMessage.length()]; Arrays.fill(chars, '='); logger.info(new String(chars)); logger.info(startMessage);//ww w . j ava 2 s. c om URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); InputStream is = null; try { URL url = cl.findResource("META-INF/MANIFEST.MF"); is = url.openStream(); Manifest manifest = new Manifest(is); Attributes attr = manifest.getMainAttributes(); logger.info(messages.get("installer.version", attr.getValue("Created-By"))); } catch (IOException e) { logger.log(Level.WARNING, "IzPack version not found in manifest", e); } finally { IOUtils.closeQuietly(is); } logger.info(messages.get("installer.platform", matcher.getCurrentPlatform())); }
From source file:org.apache.synapse.core.axis2.ExtensionDeployer.java
private <T> List<T> getProviders(Class<T> providerClass, URLClassLoader loader) throws DeploymentException, IOException { List<T> providers = new LinkedList<T>(); String providerClassName = providerClass.getName(); providerClassName = providerClassName.substring(providerClassName.indexOf('.') + 1); URL servicesURL = loader.findResource("META-INF/services/" + providerClass.getName()); if (servicesURL != null) { BufferedReader in = new BufferedReader(new InputStreamReader(servicesURL.openStream())); try {//from ww w . ja v a 2s . c o m String className; while ((className = in.readLine()) != null) { log.info("Loading the " + providerClassName + " implementation: " + className); try { Class<? extends T> clazz = loader.loadClass(className).asSubclass(providerClass); providers.add(clazz.newInstance()); } catch (ClassNotFoundException e) { handleException("Unable to find the specified class on the path or " + "in the jar file", e); } catch (IllegalAccessException e) { handleException("Unable to load the class from the jar", e); } catch (InstantiationException e) { handleException("Unable to instantiate the class specified", e); } } } finally { in.close(); } } return providers; }
From source file:org.apache.synapse.deployers.ExtensionDeployer.java
private <T> List<T> getProviders(Class<T> providerClass, URLClassLoader loader) throws IOException { List<T> providers = new LinkedList<T>(); String providerClassName = providerClass.getName(); providerClassName = providerClassName.substring(providerClassName.indexOf('.') + 1); URL servicesURL = loader.findResource("META-INF/services/" + providerClass.getName()); if (servicesURL != null) { BufferedReader in = new BufferedReader(new InputStreamReader(servicesURL.openStream())); try {//from w ww. j av a 2 s . co m String className; while ((className = in.readLine()) != null && (!className.trim().equals(""))) { log.info("Loading the " + providerClassName + " implementation: " + className); try { Class<? extends T> clazz = loader.loadClass(className).asSubclass(providerClass); providers.add(clazz.newInstance()); } catch (ClassNotFoundException e) { handleException("Unable to find the specified class on the path or " + "in the jar file", e); } catch (IllegalAccessException e) { handleException("Unable to load the class from the jar", e); } catch (InstantiationException e) { handleException("Unable to instantiate the class specified", e); } } } finally { in.close(); } } return providers; }
From source file:org.codehaus.enunciate.modules.BasicAppModule.java
/** * Whether to exclude a file from copying to the WEB-INF/lib directory. * * @param file The file to exclude./*from w w w .j a v a2 s . com*/ * @return Whether to exclude a file from copying to the lib directory. */ protected boolean knownExclude(File file) throws IOException { //instantiate a loader with this library only in its path... URLClassLoader loader = new URLClassLoader(new URL[] { file.toURL() }, null); if (loader.findResource("META-INF/enunciate/preserve-in-war") != null) { debug("%s is a known include because it contains the entry META-INF/enunciate/preserve-in-war.", file); //if a jar happens to have the enunciate "preserve-in-war" file, it is NOT excluded. return false; } else if (loader .findResource(com.sun.tools.apt.Main.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be tools.jar.", file); //exclude tools.jar. return true; } else if (loader.findResource( net.sf.jelly.apt.Context.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be apt-jelly.", file); //exclude apt-jelly-core.jar return true; } else if (loader.findResource(net.sf.jelly.apt.freemarker.FreemarkerModel.class.getName().replace('.', '/') .concat(".class")) != null) { debug("%s is a known exclude because it appears to be the apt-jelly-freemarker libs.", file); //exclude apt-jelly-freemarker.jar return true; } else if (loader.findResource( freemarker.template.Configuration.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be the freemarker libs.", file); //exclude freemarker.jar return true; } else if (loader.findResource(Enunciate.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be the enunciate core jar.", file); //exclude enunciate-core.jar return true; } else if (loader.findResource("javax/servlet/ServletContext.class") != null) { debug("%s is a known exclude because it appears to be the servlet api.", file); //exclude the servlet api. return true; } else if (loader.findResource( "org/codehaus/enunciate/modules/xfire_client/EnunciatedClientSoapSerializerHandler.class") != null) { debug("%s is a known exclude because it appears to be the enunciated xfire client tools jar.", file); //exclude xfire-client-tools return true; } else if (loader.findResource("javax/swing/SwingBeanInfoBase.class") != null) { debug("%s is a known exclude because it appears to be dt.jar.", file); //exclude dt.jar return true; } else if (loader.findResource("HTMLConverter.class") != null) { debug("%s is a known exclude because it appears to be htmlconverter.jar.", file); return true; } else if (loader.findResource("sun/tools/jconsole/JConsole.class") != null) { debug("%s is a known exclude because it appears to be jconsole.jar.", file); return true; } else if (loader.findResource("sun/jvm/hotspot/debugger/Debugger.class") != null) { debug("%s is a known exclude because it appears to be sa-jdi.jar.", file); return true; } else if (loader.findResource("sun/io/ByteToCharDoubleByte.class") != null) { debug("%s is a known exclude because it appears to be charsets.jar.", file); return true; } else if (loader.findResource("com/sun/deploy/ClientContainer.class") != null) { debug("%s is a known exclude because it appears to be deploy.jar.", file); return true; } else if (loader.findResource("com/sun/javaws/Globals.class") != null) { debug("%s is a known exclude because it appears to be javaws.jar.", file); return true; } else if (loader.findResource("javax/crypto/SecretKey.class") != null) { debug("%s is a known exclude because it appears to be jce.jar.", file); return true; } else if (loader.findResource("sun/net/www/protocol/https/HttpsClient.class") != null) { debug("%s is a known exclude because it appears to be jsse.jar.", file); return true; } else if (loader.findResource("sun/plugin/JavaRunTime.class") != null) { debug("%s is a known exclude because it appears to be plugin.jar.", file); return true; } else if (loader.findResource("com/sun/corba/se/impl/activation/ServerMain.class") != null) { debug("%s is a known exclude because it appears to be rt.jar.", file); return true; } else if (ServiceLoader.load(DeploymentModule.class, loader).iterator().hasNext()) { debug("%s is a known exclude because it appears to be an enunciate module.", file); //exclude by default any deployment module libraries. return true; } return false; }
From source file:org.deegree.commons.modules.ModuleInfo.java
/** * Returns the {@link ModuleInfo} for the deegree module on the given classpath. * /*from www.j ava 2 s. co m*/ * @param classpathURL * classpath url, must not be <code>null</code> * @return module info or <code>null</code> (if the module does not have file META-INF/deegree/buildinfo.properties) * @throws IOException * if accessing <code>META-INF/deegree/buildinfo.properties</code> or * <code>META-INF/maven/[..]/pom.properties</code> fails */ public static ModuleInfo extractModuleInfo(URL classpathURL) throws IOException { ModuleInfo moduleInfo = null; ConfigurationBuilder builder = new ConfigurationBuilder(); builder = builder.setUrls(classpathURL); builder = builder.setScanners(new ResourcesScanner()); Reflections r = new Reflections(builder); Set<String> resources = r.getResources(Pattern.compile("buildinfo\\.properties")); if (!resources.isEmpty()) { URLClassLoader classLoader = new URLClassLoader(new URL[] { classpathURL }, null); String resourcePath = resources.iterator().next(); InputStream buildInfoStream = null; try { Properties props = new Properties(); buildInfoStream = classLoader.getResourceAsStream(resourcePath); props.load(buildInfoStream); String buildBy = props.getProperty("build.by"); String buildArtifactId = props.getProperty("build.artifactId"); String buildDate = props.getProperty("build.date"); String buildRev = props.getProperty("build.svnrev"); String pomVersion = null; resources = r.getResources(Pattern.compile("pom\\.properties")); InputStream pomInputStream = null; if (!resources.isEmpty()) { resourcePath = resources.iterator().next(); try { props = new Properties(); pomInputStream = classLoader.findResource(resourcePath).openStream(); props.load(pomInputStream); String pomArtifactId = props.getProperty("artifactId"); if (!pomArtifactId.equals(buildArtifactId)) { LOG.warn("ArtifactId mismatch for module on path: " + classpathURL + " (buildinfo.properties vs. pom.properties)."); } pomVersion = props.getProperty("version"); } finally { closeQuietly(pomInputStream); } } moduleInfo = new ModuleInfo(buildArtifactId, pomVersion, buildRev, buildDate, buildBy); } finally { closeQuietly(buildInfoStream); } } return moduleInfo; }