List of usage examples for java.net URLClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:net.pms.external.ExternalFactory.java
private static String getMainClass(URL jar) { URL[] jarURLs1 = { jar };//w w w . j a v a 2 s .c om URLClassLoader classLoader = new URLClassLoader(jarURLs1); try { Enumeration<URL> resources; try { // Each plugin .jar file has to contain a resource named "plugin" // which should contain the name of the main plugin class. resources = classLoader.getResources("plugin"); if (resources.hasMoreElements()) { URL url = resources.nextElement(); char[] name; // Determine the plugin main class name from the contents of // the plugin file. try (InputStreamReader in = new InputStreamReader(url.openStream())) { name = new char[512]; in.read(name); } return new String(name).trim(); } } catch (IOException e) { LOGGER.error("Can't load plugin resources", e); } } finally { try { classLoader.close(); } catch (IOException e) { LOGGER.error("Error closing plugin finder: {}", e.getMessage()); LOGGER.trace("", e); } } return null; }
From source file:net.pms.external.ExternalFactory.java
/** * This method loads the jar files found in the plugin dir * or if installed from the web./*from w w w . j a v a 2 s.c o m*/ */ public static void loadJAR(URL[] jarURL, boolean download, URL newURL) { /* Create a classloader to take care of loading the plugin classes from * their URL. * * A not on the suppressed warning: The classloader need to remain open as long * as the loaded classes are in use - in our case forever. * @see http://stackoverflow.com/questions/13944868/leaving-classloader-open-after-first-use */ @SuppressWarnings("resource") URLClassLoader classLoader = new URLClassLoader(jarURL); Enumeration<URL> resources; try { // Each plugin .jar file has to contain a resource named "plugin" // which should contain the name of the main plugin class. resources = classLoader.getResources("plugin"); } catch (IOException e) { LOGGER.error("Can't load plugin resources: {}", e.getMessage()); LOGGER.trace("", e); try { classLoader.close(); } catch (IOException e2) { // Just swallow } return; } while (resources.hasMoreElements()) { URL url = resources.nextElement(); try { // Determine the plugin main class name from the contents of // the plugin file. char[] name; try (InputStreamReader in = new InputStreamReader(url.openStream())) { name = new char[512]; in.read(name); } String pluginMainClassName = new String(name).trim(); LOGGER.info("Found plugin: " + pluginMainClassName); if (download) { // Only purge code when downloading! purgeCode(pluginMainClassName, newURL); } // Try to load the class based on the main class name Class<?> clazz = classLoader.loadClass(pluginMainClassName); registerListenerClass(clazz); if (download) { downloadedListenerClasses.add(clazz); } } catch (Exception | NoClassDefFoundError e) { LOGGER.error("Error loading plugin", e); } } }
From source file:org.apache.blur.command.BaseCommandManager.java
protected void loadNewCommand(FileSystem fileSystem, FileStatus fileStatus, BigInteger hashOfContents) throws IOException { File file = new File(_tmpPath, UUID.randomUUID().toString()); if (!file.mkdirs()) { LOG.error("Error while trying to create a tmp directory for loading a new command set from [{0}].", fileStatus.getPath());/*w w w. ja va 2 s . com*/ return; } LOG.info("Copying new command with hash [{2}] set from [{0}] into [{1}].", fileStatus.getPath(), file.getAbsolutePath(), hashOfContents.toString(Character.MAX_RADIX)); copyLocal(fileSystem, fileStatus, file); URLClassLoader loader = new URLClassLoader(getUrls(file).toArray(new URL[] {})); Enumeration<URL> resources = loader.getResources(META_INF_SERVICES_ORG_APACHE_BLUR_COMMAND_COMMANDS); loadCommandClasses(resources, loader, hashOfContents); }
From source file:org.apache.openejb.config.DeploymentLoader.java
public static void addBeansXmls(final WebModule webModule) { final List<URL> urls = webModule.getScannableUrls(); // parent returns nothing when calling getresources because we don't want here to be fooled by maven classloader final URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), new EmptyResourcesClassLoader()); final List<URL> xmls = new LinkedList<>(); try {/* w w w. j a v a 2 s . c om*/ final URL e = (URL) webModule.getAltDDs().get("beans.xml"); if (e != null) { // first! xmls.add(e); } xmls.addAll(Collections.list(loader.getResources("META-INF/beans.xml"))); } catch (final IOException e) { return; } final CompositeBeans complete = new CompositeBeans(); for (final URL url : xmls) { if (url == null) { continue; } mergeBeansXml(complete, url); } if (!complete.getDiscoveryByUrl().isEmpty()) { complete.removeDuplicates(); webModule.getAltDDs().put("beans.xml", complete); } }
From source file:org.apache.openejb.config.DeploymentLoader.java
private void addBeansXmls(final AppModule appModule) { final List<URL> urls = appModule.getAdditionalLibraries(); final URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()])); final ArrayList<URL> xmls; try {// w w w.ja va 2s. co m xmls = Collections.list(loader.getResources("META-INF/beans.xml")); } catch (final IOException e) { return; } final CompositeBeans complete = new CompositeBeans(); for (final URL url : xmls) { if (url == null) { continue; } mergeBeansXml(complete, url); } if (complete.getDiscoveryByUrl().isEmpty()) { return; } complete.removeDuplicates(); IAnnotationFinder finder; try { finder = FinderFactory.createFinder(appModule); } catch (final Exception e) { finder = new FinderFactory.ModuleLimitedFinder(new FinderFactory.OpenEJBAnnotationFinder( new WebappAggregatedArchive(appModule.getClassLoader(), appModule.getAltDDs(), xmls))); } appModule.setEarLibFinder(finder); final EjbModule ejbModule = new EjbModule(appModule.getClassLoader(), EAR_SCOPED_CDI_BEANS + appModule.getModuleId(), new EjbJar(), new OpenejbJar()); ejbModule.setBeans(complete); ejbModule.setFinder(finder); ejbModule.setEjbJar(new EmptyEjbJar()); appModule.getEjbModules().add(ejbModule); }
From source file:org.efaps.update.version.Application.java
/** * Method to get all applications from the class path. * * @param _application searched application in the class path * @param _classpath class path (list of the complete class path) * @return List of applications//w w w . j ava 2 s.c o m * @throws InstallationException if the install.xml file in the class path * could not be accessed */ public static Map<String, Application> getApplicationsFromClassPath(final String _application, final List<String> _classpath) throws InstallationException { final Map<String, Application> appls = new HashMap<String, Application>(); try { final ClassLoader parent = Application.class.getClassLoader(); final List<URL> urls = new ArrayList<>(); for (final String pathElement : _classpath) { urls.add(new File(pathElement).toURI().toURL()); } final URLClassLoader cl = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]), parent); // get install application (read from all install xml files) final Enumeration<URL> urlEnum = cl.getResources("META-INF/efaps/install.xml"); while (urlEnum.hasMoreElements()) { // TODO: why class path? final URL url = urlEnum.nextElement(); final Application appl = Application.getApplication(url, new URL(url, "../../../"), _classpath); appls.put(appl.getApplication(), appl); } } catch (final IOException e) { throw new InstallationException("Could not access the install.xml file " + "(in path META-INF/efaps/ path of each eFaps install jar).", e); } return appls; }
From source file:org.sakaiproject.kernel.component.core.ComponentLoaderServiceImpl.java
public void load(String componentLocations, boolean fromClassloader) throws IOException, ComponentSpecificationException, KernelConfigurationException { // convert the location set into a list of URLs final Map<String, URL> locations = new HashMap<String, URL>(); LOG.info("Components are located in: " + componentLocations); String[] compLocs = StringUtils.split(componentLocations, ';'); if (compLocs != null) { for (String location : compLocs) { location = location.trim();// w w w .j a va 2 s. com if (location.startsWith("maven-repo")) { Artifact dep = DependencyImpl.fromString(location); URL u = artifactResolverService.resolve(null, dep); LOG.info("Added component: " + u); locations.put(u.toString(), u); } else if (location.endsWith(".jar")) { if (location.indexOf("://") < 0) { File f = new File(location); if (!f.exists()) { LOG.warn("Jar file " + f.getAbsolutePath() + " does not exist, will be ignored "); } else { URL url = null; try { url = f.toURI().toURL(); LOG.info("Added component: " + url); locations.put(url.toString(), url); } catch (MalformedURLException e) { LOG.warn("Component load failed, could not map file path to URL"); LOG.warn("Cause was: " + e.getMessage()); } } } else { LOG.info("Added component: " + location); URL u = new URL(location); locations.put(u.toString(), u); } } else if (location.startsWith("classpath")) { // resolve in the current classpath and add directly fromClassloader = true; } else if (location.endsWith(COMPONENT_SPEC_XML)) { location = location.substring(0, location.length() - COMPONENT_SPEC_XML.length()); File f = new File(location); URL url = f.toURI().toURL(); LOG.info("Added component: " + url); locations.put(url.toString(), url); } else { LOG.info("Locating Components in " + location); for (File f : FileUtil.findAll(location, ".jar")) { URL url = f.toURI().toURL(); LOG.info("-> added component: " + url); locations.put(url.toString(), url); } } } } LOG.info("Bundle contains " + locations.size() + " components"); // bind to the parent classloader ? ClassLoader pcl = null; if (fromClassloader) { pcl = this.getClass().getClassLoader(); } final ClassLoader parent = pcl; // find all the instances LOG.info("==============> Determining class search locations:"); for (URL location : locations.values()) { LOG.info("-> searching in " + location.toString()); } LOG.info("==============> End determining class search locations"); URLClassLoader uclassloader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(locations.values().toArray(new URL[0]), parent); } }); for (URL u : uclassloader.getURLs()) { LOG.info("URLClassLoader configured with: " + u); } for (Enumeration<URL> components = uclassloader.getResources(COMPONENT_SPEC_XML); components .hasMoreElements();) { LOG.info("URLClassLoader found: " + components.nextElement()); } Map<String, ComponentSpecification> specs = new HashMap<String, ComponentSpecification>(); for (Enumeration<URL> components = uclassloader.getResources(COMPONENT_SPEC_XML); components .hasMoreElements();) { URL url = components.nextElement(); try { String componentSpecXml = url.toURI().toString(); String source = componentSpecXml; if (source.endsWith(COMPONENT_SPEC_XML)) { source = source.substring(0, source.length() - COMPONENT_SPEC_XML.length() - 1); } if (source.endsWith("!")) { source = source.substring(0, source.length() - 1); } if (source.startsWith("jar:")) { source = source.substring(4); } if (source.endsWith("/")) { source = source.substring(0, source.length() - 1); } LOG.info("Adding Component: " + componentSpecXml + " from " + source); specs.put(source, new URLComponentSpecificationImpl(source, componentSpecXml)); } catch (URISyntaxException e) { LOG.warn("Failed to resolve URL " + e.getMessage()); } } LOG.info("==============> Specifying Component Set"); for (ComponentSpecification spec : specs.values()) { LOG.info("-> Specification: " + spec.getName()); } LOG.info("==============> End specifying Component Set"); if (specs.size() > 0) { uclassloader = null; componentManager.startComponents(new ArrayList<ComponentSpecification>(specs.values())); } else if (locations.size() > 0) { StringBuilder sb = new StringBuilder(); sb.append("No Components found in classpath:"); for (URL u : uclassloader.getURLs()) { sb.append("\n ").append(u.toString()); } sb.append("\n so no components were loaded.\nThis is almost certainly bad!\n"); LOG.error(sb.toString()); } else { LOG.error("Load operation should have specified some Components / locations but did not."); } uclassloader = null; }