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:com.streamsets.datacollector.cluster.ClusterProviderImpl.java

private static List<URL> findJars(String name, URLClassLoader cl, @Nullable String stageClazzName)
        throws IOException {
    Properties properties = readDataCollectorProperties(cl);
    List<String> blacklist = new ArrayList<>();
    for (Map.Entry entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        if (stageClazzName != null && key.equals(CLUSTER_MODE_JAR_BLACKLIST + stageClazzName)) {
            String value = (String) entry.getValue();
            blacklist.addAll(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value));
        } else if (key.equals(CLUSTER_MODE_JAR_BLACKLIST + ALL_STAGES)) {
            String value = (String) entry.getValue();
            blacklist.addAll(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value));
        }/*from w  w  w  .  ja  v  a2s . com*/
    }
    if (IS_TRACE_ENABLED) {
        LOG.trace("Blacklist for '{}': '{}'", name, blacklist);
    }
    List<URL> urls = new ArrayList<>();
    for (URL url : cl.getURLs()) {
        if (blacklist.isEmpty()) {
            urls.add(url);
        } else {
            if (exclude(blacklist, FilenameUtils.getName(url.getPath()))) {
                LOG.trace("Skipping '{}' for '{}' due to '{}'", url, name, blacklist);
            } else {
                urls.add(url);
            }
        }
    }
    return urls;
}

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

/**
 * This method is the implementation of the war deployer which frequently scans the deploy
 * directory and if there is a change in war redeploys and configures the map
 *///from  www.  ja  v  a2s . c  o  m
public void run() {
    File file;
    ConcurrentHashMap filePrevMap = new ConcurrentHashMap();
    ConcurrentHashMap fileCurrMap = new ConcurrentHashMap();
    ;

    FileInfo filePrevLastModified;
    FileInfo fileCurrLastModified;
    String filePath;
    FileInfo fileinfoTmp;
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    warsDeployed = new CopyOnWriteArrayList();
    //System.out.println("URLS="+urls[0]);
    WebClassLoader customClassLoader;
    while (true) {
        file = new File(scanDirectory);
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory())
                continue;
            //Long lastModified=(Long) fileMap.get(files[i].getName());
            if (files[i].getName().endsWith(".war")) {
                filePath = files[i].getAbsolutePath();
                //logger.info("filePath"+filePath);
                filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
                File warDirectory = new File(filePath);
                fileinfoTmp = new FileInfo();
                fileinfoTmp.setFile(files[i]);
                fileinfoTmp.setLastModified(files[i].lastModified());
                if (!warDirectory.exists() || fileCurrMap.get(files[i].getName()) == null
                        && filePrevMap.get(files[i].getName()) == null) {
                    if (warDirectory.exists()) {
                        deleteDir(warDirectory);
                    }
                    customClassLoader = new WebClassLoader(urls);
                    synchronized (urlClassLoaderMap) {
                        logger.info("WARDIRECTORY=" + warDirectory.getAbsolutePath());
                        urlClassLoaderMap.put(warDirectory.getAbsolutePath().replace("\\", "/"),
                                customClassLoader);
                    }
                    extractWar(files[i], customClassLoader);
                    //System.out.println("War Deployed Successfully in path: "+filePath);
                    AddUrlToClassLoader(warDirectory, customClassLoader);
                    numberOfWarDeployed++;
                    logger.info(files[i] + " Deployed");
                    warsDeployed.add(files[i].getName());
                    filePrevMap.put(files[i].getName(), fileinfoTmp);
                }
                fileCurrMap.put(files[i].getName(), fileinfoTmp);
            }
            /*if(lastModified==null||lastModified!=files[i].lastModified()){
               fileMap.put(files[i].getName(),files[i].lastModified());
            }*/
        }
        Set keyset = fileCurrMap.keySet();
        Iterator ite = keyset.iterator();
        String fileName;
        while (ite.hasNext()) {
            fileName = (String) ite.next();
            //logger.info("fileName"+fileName);
            filePrevLastModified = (FileInfo) filePrevMap.get(fileName);
            fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName);
            if (filePrevLastModified != null)
                //logger.info("lastmodified="+filePrevLastModified.getLastModified());
                //System.out.println("prevmodified"+fileCurrLastModified.getLastModified()+""+filePrevLastModified.getLastModified());
                if (fileCurrLastModified != null) {
                    //System.out.println("prevmodified"+fileCurrLastModified.getLastModified());
                }
            if (filePrevLastModified == null
                    || filePrevLastModified.getLastModified() != fileCurrLastModified.getLastModified()) {
                filePath = fileCurrLastModified.getFile().getAbsolutePath();
                //logger.info("filePath"+filePath);
                filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
                File warDirectory = new File(filePath);
                //logger.info("WARDIRECTORY="+warDirectory.getAbsolutePath());
                if (warDirectory.exists()) {
                    WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap
                            .get(warDirectory.getAbsolutePath().replace("\\", "/"));
                    synchronized (executorServiceMap) {
                        try {
                            new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap,
                                    new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                            + "executorservices.xml"),
                                    webClassLoader);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        //System.out.println("executorServiceMap"+executorServiceMap);
                    }
                    synchronized (messagingClassMap) {
                        try {
                            new MessagingClassConstruct().removeMessagingClass(messagedigester,
                                    new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                            + "messagingclass.xml"),
                                    messagingClassMap);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println("executorServiceMap" + executorServiceMap);
                    }
                    ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                    try {
                        webClassLoader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    logger.info("ServletMapping" + servletMapping);
                    logger.info("warDirectory=" + warDirectory.getAbsolutePath().replace("\\", "/"));
                    urlClassLoaderMap.remove(warDirectory.getAbsolutePath().replace("\\", "/"));
                    WebAppConfig webAppConfig = (WebAppConfig) servletMapping
                            .remove(warDirectory.getAbsolutePath().replace("\\", "/"));
                    System.gc();
                    deleteDir(warDirectory);
                    warsDeployed.remove(fileName);
                    removeServletFromSessionObject(webAppConfig,
                            warDirectory.getAbsolutePath().replace("\\", "/"));
                    numberOfWarDeployed--;
                }
                customClassLoader = new WebClassLoader(urls);
                logger.info(customClassLoader);
                urlClassLoaderMap.put(warDirectory.getAbsolutePath().replace("\\", "/"), customClassLoader);
                extractWar(fileCurrLastModified.getFile(), customClassLoader);
                //System.out.println("War Deployed Successfully in path: "+fileCurrLastModified.getFile().getAbsolutePath());
                AddUrlToClassLoader(warDirectory, customClassLoader);
                numberOfWarDeployed++;
                warsDeployed.add(fileName);
                logger.info(filePath + ".war Deployed");
            }
        }
        keyset = filePrevMap.keySet();
        ite = keyset.iterator();
        while (ite.hasNext()) {
            fileName = (String) ite.next();
            filePrevLastModified = (FileInfo) filePrevMap.get(fileName);
            fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName);
            if (fileCurrLastModified == null) {
                filePath = filePrevLastModified.getFile().getAbsolutePath();
                filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
                logger.info("filePath" + filePath);
                File deleteDirectory = new File(filePath);
                logger.info("Delete Directory" + deleteDirectory.getAbsolutePath().replace("\\", "/"));
                WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap
                        .get(deleteDirectory.getAbsolutePath().replace("\\", "/"));
                ;
                synchronized (executorServiceMap) {

                    try {
                        new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap,
                                new File(deleteDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                        + "executorservices.xml"),
                                webClassLoader);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //System.out.println("executorServiceMap"+executorServiceMap);
                }
                synchronized (messagingClassMap) {
                    try {
                        new MessagingClassConstruct().removeMessagingClass(messagedigester,
                                new File(deleteDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                        + "messagingclass.xml"),
                                messagingClassMap);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //System.out.println("executorServiceMap"+executorServiceMap);
                }
                WebAppConfig webAppConfig = (WebAppConfig) servletMapping
                        .remove(deleteDirectory.getAbsolutePath().replace("\\", "/"));
                ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                urlClassLoaderMap.remove(deleteDirectory.getAbsolutePath().replace("\\", "/"));
                logger.info("ServletMapping" + servletMapping);
                logger.info("warDirectory=" + deleteDirectory.getAbsolutePath().replace("\\", "/"));
                try {
                    logger.info(webClassLoader);
                    logger.info("CLASSLOADER IS CLOSED");
                    webClassLoader.close();
                } catch (Throwable e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.gc();
                deleteDir(deleteDirectory);
                numberOfWarDeployed--;
                warsDeployed.remove(fileName);
                try {
                    removeServletFromSessionObject(webAppConfig,
                            deleteDirectory.getAbsolutePath().replace("\\", "/"));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                logger.info(filePath + ".war Undeployed");
            }
        }
        filePrevMap.keySet().removeAll(filePrevMap.keySet());
        filePrevMap.putAll(fileCurrMap);
        fileCurrMap.keySet().removeAll(fileCurrMap.keySet());
        //System.out.println("filePrevMap="+filePrevMap);
        //System.out.println("fileCurrMap="+fileCurrMap);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.aliyun.odps.mapred.LocalJobRunner.java

@SuppressWarnings("deprecation")
private void processResources() throws IOException, OdpsException {
    String[] resources = conf.getResources();

    if (resources == null || resources.length == 0) {
        LOG.debug("No resources to process");
        return;/*from  www. j  ava2s.  c  o  m*/
    }

    Set<String> names = new HashSet<String>(Arrays.asList(resources));
    LOG.info("Start to process resources: " + StringUtils.join(resources, ','));

    URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    ArrayList<URL> cp = new ArrayList<URL>(Arrays.asList(loader.getURLs()));
    String curProjName = wareHouse.getOdps().getDefaultProject();
    File resDir = jobDirecotry.getResourceDir();
    for (String name : names) {

        List<String> res = LocalRunUtils.parseResourceName(name, curProjName);

        String projName = res.get(0);
        String resName = res.get(1);

        if (!wareHouse.existsResource(projName, resName)
                || wareHouse.getDownloadMode() == DownloadMode.ALWAYS) {
            DownloadUtils.downloadResource(odps, projName, resName, wareHouse.getLimitDownloadRecordCount(),
                    wareHouse.getInputColumnSeperator());
        }
        wareHouse.copyResource(projName, resName, resDir, wareHouse.getLimitDownloadRecordCount(),
                wareHouse.getInputColumnSeperator());
        cp.add(new File(resDir, resName).toURI().toURL());
    }
    URLClassLoader newLoader = new URLClassLoader(cp.toArray(new URL[0]), loader);
    Thread.currentThread().setContextClassLoader(newLoader);
    conf.setClassLoader(newLoader);
}

From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java

private List<String> getFilesInCL(URLClassLoader cl, String regex) {
    List<String> files = new ArrayList<>();
    for (URL url : cl.getURLs()) {
        File jar = new File(url.getPath());
        if (jar.getName().matches(regex)) {
            getLog().info(Utils.format("Adding {} to ship.", url.getPath()));
            files.add(jar.getAbsolutePath());
        }/*from   www.  j a v a2  s.  c o  m*/
    }
    return files;
}

From source file:com.mirth.connect.client.ui.reference.ReferenceListFactory.java

private void addUserutilReferences() {
    populateAliases();/* w  w  w  .  ja  v a 2  s.  co m*/

    if (Thread.currentThread().getContextClassLoader() instanceof URLClassLoader) {
        URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
        for (URL url : classLoader.getURLs()) {
            String urlString = url.toString();
            if (StringUtils.endsWithIgnoreCase(urlString, "userutil-sources.jar")) {
                addUserutilReferences(url);
            }
        }
    }
}

From source file:com.streamsets.datacollector.cluster.TestTarFileCreator.java

@Test
public void testCreateLibsTarGz() throws Exception {
    File apiLibDir = new File(tempDir, "api-lib");
    File containerLibDir = new File(tempDir, "container-lib");
    File streamsetsLibsDir = new File(tempDir, "streamsets-libs");
    File userLibsDir = new File(tempDir, "user-libs");
    URLClassLoader apiCl = new URLClassLoader(new URL[] { createJar(apiLibDir).toURL() });
    URLClassLoader containerCL = new URLClassLoader(new URL[] { createJar(containerLibDir).toURL() });
    Map<String, List<URL>> streamsetsLibsCl = new LinkedHashMap<>();
    Map<String, List<URL>> userLibsCL = new LinkedHashMap<>();
    streamsetsLibsCl.put("abc123",
            ImmutableList.copyOf(//  w  w w  .j av a2 s  . com
                    new URLClassLoader(new URL[] { createJar(new File(streamsetsLibsDir, "abc123")).toURL() })
                            .getURLs()));
    streamsetsLibsCl.put("abc456",
            ImmutableList.copyOf(
                    new URLClassLoader(new URL[] { createJar(new File(streamsetsLibsDir, "abc456")).toURL() })
                            .getURLs()));
    userLibsCL.put("yxz456",
            ImmutableList
                    .copyOf(new URLClassLoader(new URL[] { createJar(new File(userLibsDir, "yxz456")).toURL(),
                            createJar(new File(tempDir, "yxz789")).toURL() }).getURLs()));
    File staticWebDir = new File(tempDir, "static-web-dir");
    Assert.assertTrue(staticWebDir.mkdir());
    createJar(new File(staticWebDir, "subdir"));
    File tarFile = new File(tempDir, "libs.tar.gz");
    TarFileCreator.createLibsTarGz(ImmutableList.copyOf(apiCl.getURLs()),
            ImmutableList.copyOf(containerCL.getURLs()), streamsetsLibsCl, userLibsCL, staticWebDir, tarFile);
    TarInputStream tis = new TarInputStream(new GZIPInputStream(new FileInputStream(tarFile)));
    readDir("api-lib/", tis);
    readJar(tis);
    readDir("container-lib/", tis);
    readJar(tis);
    readDir("streamsets-libs/", tis);
    readDir("streamsets-libs/abc123/", tis);
    readDir("streamsets-libs/abc123/lib/", tis);
    readJar(tis);
    readDir("streamsets-libs/abc456/", tis);
    readDir("streamsets-libs/abc456/lib/", tis);
    readJar(tis);
    readDir("user-libs/", tis);
    readDir("user-libs/yxz456/", tis);
    readDir("user-libs/yxz456/lib/", tis);
    readJar(tis);
    readJar(tis);
    readJar(tis);
    readDir("libs-common-lib/", tis);
}

From source file:com.stratio.explorer.interpreter.InterpreterFactory.java

public Interpreter createRepl(String dirName, String className, Properties property) {
    logger.info("Create repl {} from {}", className, dirName);

    ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
    try {/*from w w w .ja  v a 2  s . co  m*/

        URLClassLoader ccl = cleanCl.get(dirName);
        if (ccl == null) {
            // classloader fallback
            ccl = URLClassLoader.newInstance(new URL[] {}, oldcl);
        }

        boolean separateCL = true;
        try { // check if server's classloader has driver already.
            Class cls = this.getClass().forName(className);
            if (cls != null) {
                separateCL = false;
            }
        } catch (Exception e) {
            // nothing to do.
        }

        URLClassLoader cl;

        if (separateCL == true) {
            cl = URLClassLoader.newInstance(new URL[] {}, ccl);
        } else {
            cl = (URLClassLoader) ccl;
        }
        Thread.currentThread().setContextClassLoader(cl);

        Class<Interpreter> replClass = (Class<Interpreter>) cl.loadClass(className);
        Constructor<Interpreter> constructor = replClass.getConstructor(new Class[] { Properties.class });
        Interpreter repl = constructor.newInstance(property);
        if (conf.containsKey("args")) {
            property.put("args", conf.getProperty("args"));
        }
        property.put("share", share);
        property.put("classloaderUrls", ccl.getURLs());
        return new ClassloaderInterpreter(repl, cl, property);
    } catch (SecurityException e) {
        throw new InterpreterException(e);
    } catch (NoSuchMethodException e) {
        throw new InterpreterException(e);
    } catch (IllegalArgumentException e) {
        throw new InterpreterException(e);
    } catch (InstantiationException e) {
        throw new InterpreterException(e);
    } catch (IllegalAccessException e) {
        throw new InterpreterException(e);
    } catch (InvocationTargetException e) {
        throw new InterpreterException(e);
    } catch (ClassNotFoundException e) {
        throw new InterpreterException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(oldcl);
    }
}

From source file:org.ireland.jnetty.webapp.WebApp.java

void displayClassLoader() {
    log.debug("BootstrapClassLoader : ");

    URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
    for (URL url : urls)
        log.debug(url);/*ww  w  . j a v  a2  s  . co m*/
    log.debug("----------------------------");

    // ?
    URLClassLoader extClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader().getParent();

    log.debug(extClassLoader);
    log.debug(" : ");

    urls = extClassLoader.getURLs();
    for (URL url : urls)
        log.debug(url);

    log.debug("----------------------------");

    // ?()
    URLClassLoader appClassLoader = (URLClassLoader) _classLoader.getParent();

    log.debug(appClassLoader);
    log.debug("() : ");

    urls = appClassLoader.getURLs();
    for (URL url : urls)
        log.debug(url);

    log.debug("----------------------------");

    // ?()
    appClassLoader = (URLClassLoader) _classLoader;

    log.debug(appClassLoader);
    log.debug("() : ");

    urls = appClassLoader.getURLs();
    for (URL url : urls)
        log.debug(url);

    log.debug("----------------------------");
}

From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java

private List<URL> findJars(String name, URLClassLoader cl, @Nullable String stageClazzName) throws IOException {
    Properties properties = readDataCollectorProperties(cl);
    List<String> blacklist = new ArrayList<>();
    for (Map.Entry entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        if (stageClazzName != null && key.equals(CLUSTER_MODE_JAR_BLACKLIST + stageClazzName)) {
            String value = (String) entry.getValue();
            blacklist.addAll(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value));
        } else if (key.equals(CLUSTER_MODE_JAR_BLACKLIST + ALL_STAGES)) {
            String value = (String) entry.getValue();
            blacklist.addAll(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value));
        }//from  ww  w  .j av a2  s  . co  m
    }
    if (isIsTraceEnabled()) {
        getLog().trace("Blacklist for '{}': '{}'", name, blacklist);
    }
    List<URL> urls = new ArrayList<>();
    for (URL url : cl.getURLs()) {
        if (blacklist.isEmpty()) {
            urls.add(url);
        } else {
            if (exclude(blacklist, FilenameUtils.getName(url.getPath()))) {
                getLog().trace("Skipping '{}' for '{}' due to '{}'", url, name, blacklist);
            } else {
                urls.add(url);
            }
        }
    }
    return urls;
}

From source file:net.sourceforge.pmd.cache.AbstractAnalysisCache.java

@Override
public void checkValidity(final RuleSets ruleSets, final ClassLoader auxclassPathClassLoader) {
    boolean cacheIsValid = cacheExists();

    if (cacheIsValid && ruleSets.getChecksum() != rulesetChecksum) {
        LOG.info("Analysis cache invalidated, rulesets changed.");
        cacheIsValid = false;/*from   w ww. ja v  a2s . co m*/
    }

    final long currentAuxClassPathChecksum;
    if (auxclassPathClassLoader instanceof URLClassLoader) {
        final URLClassLoader urlClassLoader = (URLClassLoader) auxclassPathClassLoader;
        currentAuxClassPathChecksum = computeClassPathHash(urlClassLoader.getURLs());

        if (cacheIsValid && currentAuxClassPathChecksum != auxClassPathChecksum) {
            // Do we even care?
            for (final Rule r : ruleSets.getAllRules()) {
                if (r.isDfa() || r.isTypeResolution()) {
                    LOG.info("Analysis cache invalidated, auxclasspath changed.");
                    cacheIsValid = false;
                    break;
                }
            }
        }
    } else {
        currentAuxClassPathChecksum = 0;
    }

    final long currentExecutionClassPathChecksum = computeClassPathHash(getClassPathEntries());
    if (cacheIsValid && currentExecutionClassPathChecksum != executionClassPathChecksum) {
        LOG.info("Analysis cache invalidated, execution classpath changed.");
        cacheIsValid = false;
    }

    if (!cacheIsValid) {
        // Clear the cache
        fileResultsCache.clear();
    }

    // Update the local checksums
    rulesetChecksum = ruleSets.getChecksum();
    auxClassPathChecksum = currentAuxClassPathChecksum;
    executionClassPathChecksum = currentExecutionClassPathChecksum;
    ruleMapper.initialize(ruleSets);
}