Example usage for java.net URLClassLoader getURLs

List of usage examples for java.net URLClassLoader getURLs

Introduction

In this page you can find the example usage for java.net URLClassLoader getURLs.

Prototype

public URL[] getURLs() 

Source Link

Document

Returns the search path of URLs for loading classes and resources.

Usage

From source file:ResourceBundleSupport.java

/**
 * Instantiate a {@link URLClassLoader} for resource lookups where the
 * codeBase URL is removed.  This method is typically called from an
 * applet's init() method.  If this method is never called, the
 * <code>getBundle()</code> methods map to the standard
 * {@link ResourceBundle} lookup methods.
 *
 * @param codeBase  the codeBase URL./*from w  w w. j a  v a  2  s . c  o m*/
 * @param urlClassLoader  the class loader.
 */
public static void removeCodeBase(URL codeBase, URLClassLoader urlClassLoader) {
    List urlsNoBase = new ArrayList();

    URL[] urls = urlClassLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (!urls[i].sameFile(codeBase)) {
            urlsNoBase.add(urls[i]);
        }
    }
    // substitute the filtered URL list
    URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]);
    noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}

From source file:com.netflix.dyno.contrib.ElasticConnectionPoolConfigurationPublisher.java

/**
 * Get library version by iterating through the classloader jar list and obtain the name from the jar filename.
 * This will not open the library jar files.
 * <p>//from  w  w w.ja v  a2 s  . com
 * This function assumes the conventional jar naming format and relies on the dash character to separate the
 * name of the jar from the version. For example, foo-bar-baz-1.0.12-CANDIDATE.
 *
 * @param libraryNames unique list of library names, i.e. "dyno-core"
 * @param classLoadedWithURLClassLoader For this to work, must have a URL based classloader
 *        This has been tested to be the case in Tomcat (WebAppClassLoader) and basic J2SE classloader
 * @return the version of the library (everything between library name, dash, and .jar)
 */
Map<String, String> getLibraryVersion(Class<?> classLoadedWithURLClassLoader, Set<String> libraryNames) {
    ClassLoader cl = classLoadedWithURLClassLoader.getClassLoader();
    Map<String, String> libraryVersionMapping = new HashMap<String, String>();

    if (cl instanceof URLClassLoader) {
        @SuppressWarnings("resource")
        URLClassLoader uCl = (URLClassLoader) cl;
        URL urls[] = uCl.getURLs();

        for (URL url : urls) {
            String fullNameWithVersion = url.toString().substring(url.toString().lastIndexOf('/'));
            if (fullNameWithVersion.length() > 4) { // all entries we attempt to parse must end in ".jar"
                String nameWithVersion = fullNameWithVersion.substring(1, fullNameWithVersion.length() - 4);
                int idx = findVersionStartIndex(nameWithVersion);
                if (idx > 0) {
                    String name = nameWithVersion.substring(0, idx - 1);
                    if (libraryNames.contains(name)) {
                        libraryVersionMapping.put(name, nameWithVersion.substring(idx));
                    }
                }
            }
        }
    }

    return libraryVersionMapping;
}

From source file:se.crisp.codekvast.support.web.config.WebjarVersionFilter.java

private void scanWebjars() {
    ClassLoader cl = WebjarVersionFilter.class.getClassLoader();

    if (!(cl instanceof URLClassLoader)) {
        throw new UnsupportedOperationException(
                "Don't know how to scan classpath from " + cl.getClass().getName());
    }//from w  w w  .  ja  va  2 s. c om

    log.debug("Scanning classpath for webjars...");

    URLClassLoader ucl = (URLClassLoader) cl;
    Pattern pattern = Pattern.compile(".*webjars/(.*?)/(.*?)/.*");

    // For each URL in classpath
    for (URL url : ucl.getURLs()) {
        try {
            analyzeJar(url, pattern);
        } catch (IOException e) {
            log.warn("Cannot analyze " + url, e);
        }
    }
    log.debug("Found {} webjars", versions.size());
}

From source file:com.clican.pluto.orm.dynamic.impl.ClassLoaderUtilImpl.java

private void populateJars(Set<String> jars, ClassLoader loader) {
    if (!(loader instanceof URLClassLoader)) {
        if (log.isDebugEnabled()) {
            log.debug("The ClassLoader[" + loader.getClass().getName() + "] is ignored");
        }//from w w  w . j  a  v a 2s  .  c o m
    } else {
        URLClassLoader urlClassLoader = (URLClassLoader) loader;

        for (URL url : urlClassLoader.getURLs()) {
            jars.add(url.getPath());
        }

    }
    if (loader == ClassLoader.getSystemClassLoader()) {
        return;
    } else {
        populateJars(jars, loader.getParent());
    }
}

From source file:com.web.server.XMLDeploymentScanner.java

public XMLDeploymentScanner(String scanDirectory, String userLibDir) {
    super(scanDirectory);
    this.userLibDir = userLibDir;
    File userLibJars = new File(userLibDir);
    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
    getUsersJars(userLibJars, jarList);//  w w  w.j a  v  a  2  s.  c  o  m
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    userLibJarLoader = new WebClassLoader(loader.getURLs());
    for (String jarFilePath : jarList) {
        try {
            userLibJarLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/")));
        } catch (MalformedURLException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }

    DigesterLoader xmlDigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/datasource-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    xmlDigester = xmlDigesterLoader.newDigester();
    try {
        ic = new InitialContext();
        ic.createSubcontext("java:");
    } catch (NamingException e1) {
        // TODO Auto-generated catch block
    }

    File[] xmlFiles = new File(scanDirectory).listFiles();

    if (xmlFiles != null && xmlFiles.length > 0) {
        for (File xmlFile : xmlFiles) {
            if (xmlFile.getName().toLowerCase().endsWith("datasource.xml")) {
                installDataSource(xmlFile);
            }
        }
    }

    // TODO Auto-generated constructor stub
}

From source file:framework.ReloadingServer.java

public ReloadingServer() throws InterruptedException, IOException {
    URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    ReloadingClassLoader pParent = new ReloadingClassLoader(urlClassLoader);
    final ReloadingClassLoader loader = new ReloadingClassLoader(pParent);
    for (URL url : urlClassLoader.getURLs()) {
        String file = url.getFile();
        if (!file.contains("commons-jci")) {
            if (file.endsWith(".jar") || file.endsWith("/web.xml") || file.endsWith(".properties")) {
                pParent.addResourceStore(new JarResourceStore(file));
            } else {
                pParent.addResourceStore(new FileResourceStore(new File(file)));
            }//from   www .  j  a v a  2  s  . c  o m
        }
    }
    Thread.currentThread().setContextClassLoader(loader);

    String classesDir = new File("target/classes").getAbsolutePath();
    int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
    boolean watchSubtree = true;
    try {
        int watchID = JNotify.addWatch(classesDir, mask, watchSubtree, new JNotifyAdapter() {
            @Override
            public void fileModified(int wd, String rootPath, String name) {
                if (name.endsWith(".class")) {
                    modified = true;
                }
            }
        });
    } catch (Exception e) {
        Loggers.SERVER.error(e.getMessage(), e);
    }
    startJetty();
    while (true) {
        try {
            Thread.sleep(400);
        } catch (InterruptedException e) {
            break;
        }
        synchronized (ReloadingServer.class) {
            if (modified) {
                stopJetty();
                ReloadingClassLoader contextClassLoader = (ReloadingClassLoader) Thread.currentThread()
                        .getContextClassLoader();
                contextClassLoader.handleNotification();
                ReloadingClassLoader parent = (ReloadingClassLoader) contextClassLoader.getParent();
                parent.handleNotification();
                Thread.currentThread().setContextClassLoader(new ReloadingClassLoader(parent));
                startJetty();
                modified = false;
            }
        }
    }
}

From source file:com.app.server.XMLDeploymentScanner.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    this.serviceList = serviceList;
    this.serverConfig = serverConfig;
    this.mbeanServer = mbeanServer;
    this.userLibDir = serverConfig.getServiceslibdirectory();
    File userLibJars = new File(userLibDir);
    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
    getUsersJars(userLibJars, jarList);/*from   w  w  w  .jav  a 2  s .  c o m*/
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    userLibJarLoader = new WebClassLoader(loader.getURLs());
    for (String jarFilePath : jarList) {
        try {
            userLibJarLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/")));
        } catch (Exception e) {
            log.error("Error in url " + "file:/" + jarFilePath.replace("\\", "/"), e);
            //e2.printStackTrace();            
        }
    }

    DigesterLoader xmlDigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {

            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/datasource-rules.xml")));
            } catch (Exception e) {
                log.error("Error in loading config rules ./config/datasource-rules.xml", e);
                //e.printStackTrace();
            }

        }
    });
    xmlDigester = xmlDigesterLoader.newDigester();
    try {
        ic = new InitialContext();
        ic.createSubcontext("java:");
    } catch (Exception e) {
        log.error("Error in creating subcontext", e);
    }
    log.info("initialized");
    // TODO Auto-generated constructor stub
}

From source file:com.videobox.web.util.dwr.AutoAnnotationDiscoveryContainer.java

private URL findResource(ClassLoader loader, String pkgPath) {
    if (loader == null) {
        return null;
    }/*from   w  w  w . ja  va2  s.c o  m*/
    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:info.magnolia.freemarker.FreemarkerServletContextWrapper.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Set getResourcePaths(String path) {
    if (StringUtils.equals(path, "/WEB-INF/lib")) {
        log.debug("returning resources from classpath");
        // Just when asking libraries, pass the classpath ones.
        final Set<String> resources = new HashSet<String>();
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // if the classloader is an URLClassloader we have a better method for discovering resources
        // whis will also fetch files from jars outside WEB-INF/lib, useful during development
        if (cl instanceof URLClassLoader) {
            final URLClassLoader urlClassLoader = (URLClassLoader) cl;
            final URL[] urls = urlClassLoader.getURLs();
            for (int j = 0; j < urls.length; j++) {
                final File tofile = sanitizeToFile(urls[j]);
                if (tofile.isDirectory()) {
                    for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                        resources.add(file.getAbsolutePath());
                    }// ww  w . j  av  a2  s.com
                } else {
                    resources.add(tofile.getAbsolutePath());
                }
            }

            return resources;
        }
        try {
            // be friendly to WAS developers too...
            // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
            // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
            // check
            //
            // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
            PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
            if (pd != null && pd.getReadMethod() != null) {
                String classpath = (String) pd.getReadMethod().invoke(cl, new Object[] {});
                if (StringUtils.isNotBlank(classpath)) {
                    String[] paths = StringUtils.split(classpath, File.pathSeparator);
                    for (int j = 0; j < paths.length; j++) {
                        final File tofile = new File(paths[j]);
                        // there can be several missing (optional?) paths here...
                        if (tofile.exists()) {
                            if (tofile.isDirectory()) {
                                for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                                    resources.add(file.getAbsolutePath());
                                }
                            } else {
                                resources.add(tofile.getAbsolutePath());
                            }
                        }
                    }
                    return resources;
                }
            }
        } catch (Throwable e) {
            // no, it's not a classloader we can handle in a special way
        }
        // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
        // read the jars in the lib dir
    }
    return parentContext.getResourcePaths(path);
}

From source file:org.ngrinder.agent.service.AgentManagerServiceTest.java

@Test
public void testCompressAgentFolder() throws IOException, URISyntaxException {
    URLClassLoader loader = (URLClassLoader) this.getClass().getClassLoader();
    URL core = this.getClass().getClassLoader().getResource("lib/ngrinder-core-test.jar");
    URL sh = this.getClass().getClassLoader().getResource("lib/ngrinder-sh-test.jar");
    URL[] ls = { core, sh };/* w w  w .  j a  v a2 s  .c  o m*/
    URL[] urls = loader.getURLs();
    URL[] allLib = cast(ArrayUtils.addAll(urls, ls));
    URLClassLoader child = new URLClassLoader(allLib, this.getClass().getClassLoader());
    File agentUpgrade = agentPackageService.createAgentPackage(child, null, null, 10000, null);
    FileUtils.deleteQuietly(agentUpgrade);
}