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:org.kuali.ole.sys.context.Log4jConfigurer.java

protected static void debugClasspath() {
    URLClassLoader ucl = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    URL[] urls = ucl.getURLs();
    List<String> files = new ArrayList<String>();
    for (URL url : urls) {
        files.add(url.getFile());/*  www .  j  av  a  2 s . c  om*/
    }
    Collections.sort(files);
    logger.debug("Located " + files.size() + " classpath entries");
    for (String file : files) {
        logger.debug("Classpath entry: " + file);
    }
}

From source file:org.metricagent.agent.MetricAgent.java

@Override
public byte[] transform(ClassLoader classLoader, String className, Class<?> aClass,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

    className = className.replace("/", ".");
    if (aClass != null)
        log.info("Class redefined {0}", className);

    //log.info("Loading class {0}", className);

    boolean doInstrument = false;
    for (Metric metric : configuration.getMetrics().getMeterOrTimer()) {
        if (className.matches(metric.getPackage())) {
            doInstrument = true;/*from  w ww .j  a va  2s.c om*/
            break;
        }
    }

    if (doInstrument) {
        log.info("Weaving class {0}", className);
    } else {
        //log.info("Not weaving class {0}", className);
        return classfileBuffer;
    }

    ClassPool classPool = new ClassPool();
    classPool.appendSystemPath();

    try {
        if (classLoader instanceof URLClassLoader) {
            log.info("Attempting to load URL class loader.");
            URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
            for (URL url : urlClassLoader.getURLs()) {
                log.info("Adding class path {0}", url.getPath());
                classPool.appendClassPath(url.getPath());
            }
        }
    } catch (Exception e) {
        log.info("Unable to load class path. Exception : {0}", ExceptionUtils.getStackTrace(e));
    }

    CtClass ctClass = null;
    try {
        ctClass = classPool.get(className);
        if (ctClass.isFrozen()) {
            log.info("Skip class {0}: is frozen", className);
            return null;
        }

        if (ctClass.isPrimitive() || ctClass.isArray() || ctClass.isAnnotation() || ctClass.isEnum()
                || ctClass.isInterface()) {
            log.info("Skip class {0}: not a class", className);
            return null;
        }

        boolean isClassModified = false;

        for (Metric metric : configuration.getMetrics().getMeterOrTimer()) {
            if (!className.matches(metric.getPackage()))
                continue;
            for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
                //String signature= Modifier.toString(ctMethod.getModifiers())+" "+ctMethod.getLongName();
                String signature = ctMethod.getLongName();
                if (!signature.matches(metric.getMethodRegex())) {
                    log.info("Not weaving method {0}", signature);
                    continue;
                }
                try {
                    if (metric instanceof Meter) {
                        MetricManager.getInstance().instrumentForMeter(metric.getName(),
                                ((Meter) metric).getPlacement().equals("before"), ctClass, ctMethod);
                    } else if (metric instanceof Timer) {
                        MetricManager.getInstance().instrumentForTimer(metric.getName(), ctClass, ctMethod);
                    }
                    isClassModified = true;
                } catch (Exception e) {
                    log.info("Skipping instrumentation of methods for class {0} exception {1}",
                            ctClass.getName(), ExceptionUtils.getStackTrace(e));
                }
            }
        }

        if (isClassModified) {
            log.info("Completed weaving class {0}", className);
            return ctClass.toBytecode();
        }
    } catch (Exception e) {
        log.info("Exception occurred while weaving class {0} with Exception : {1} ", className,
                ExceptionUtils.getStackTrace(e));
    }

    return classfileBuffer;
}

From source file:org.mili.core.resource.ResourceUtilImpl.java

private URL getUrlFromUrlClassLoader(ClassLoader cl) {
    if (cl instanceof URLClassLoader) {
        URLClassLoader urlCL = (URLClassLoader) cl;
        return urlCL.getURLs()[0];
    }/*from   w  w  w.  j  av  a2 s . co  m*/
    return null;
}

From source file:org.mrgeo.utils.ClassLoaderUtil.java

public static void dumpClasspath(ClassLoader loader, int level) {
    System.out.println(indent(level) + "Classloader " + loader + ":");

    if (loader instanceof URLClassLoader) {
        URLClassLoader ucl = (URLClassLoader) loader;
        //System.out.println("\t" + Arrays.toString(ucl.getURLs()));

        URL[] urls = ucl.getURLs();
        String[] names = new String[urls.length];

        for (int i = 0; i < urls.length; i++) {
            //        String name = urls[i].toString();
            String name = FilenameUtils.getName(urls[i].toString());

            if (name.length() > 0) {
                names[i] = name;// w  ww.  j ava 2s.  c  o  m
            } else {
                names[i] = urls[i].toString();
            }

        }
        Arrays.sort(names);

        for (String name : names) {
            System.out.println(indent(level + 1) + name);
        }
    } else
        System.out.println("\t(cannot display components as not a URLClassLoader)");

    System.out.println("");
    if (loader.getParent() != null) {
        dumpClasspath(loader.getParent(), level + 1);
    }

}

From source file:org.n52.wps.webadmin.ConfigUploadBean.java

public void compile(String fileName) {
    ClassLoader cl = this.getClass().getClassLoader();
    List<URL> classpath = new ArrayList<URL>();
    if (cl instanceof URLClassLoader) {
        URLClassLoader cl2 = (URLClassLoader) cl;
        for (URL jar : cl2.getURLs()) {
            classpath.add(jar);//w w  w .  jav  a  2 s.co  m
        }
    }
    String classPath = System.getProperty("java.class.path");
    for (String path : classPath.split(File.pathSeparator)) {
        try {
            classpath.add(new URL("file:" + path));
        } catch (MalformedURLException e) {
            System.err.println("Wrong url: " + e.getMessage());
            e.printStackTrace();
        }
    }

    StringBuffer sb = new StringBuffer();
    for (URL jar : classpath) {
        if (SystemUtils.IS_OS_WINDOWS == false) {
            sb.append(jar.getPath());
            sb.append(File.pathSeparatorChar);
        } else {
            sb.append(jar.getPath().substring(1));
            sb.append(File.pathSeparatorChar);
        }
    }
    String ops[] = new String[] { "-classpath", sb.toString() };

    List<String> opsIter = new ArrayList<String>();
    try {
        for (String s : ops) {
            // XXX test usage, removed use of deprecated method
            // ((ArrayList) opsIter).add(URLDecoder.decode(s));
            ((ArrayList) opsIter).add(URLDecoder.decode(s, Charset.forName("UTF-8").toString()));
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn(e.getMessage(), e);
    }

    File[] files1 = new File[1];
    files1[0] = new File(fileName);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files1));

    compiler.getTask(null, fileManager, null, opsIter, null, compilationUnits1).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.onehippo.repository.clustering.ClusterTest.java

/**
 * Create a LocalHippoRepository running in its own isolated classloader. Because of this classloader
 * isolation all access to the repository internals must be done using reflection.
 *///from  w w  w.  ja  v a  2s .co  m
private static Object createRepository(final String repoPath, final String repoConfig) throws Exception {
    URLClassLoader contextClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    URLClassLoader classLoader = new RepositoryClassLoader(contextClassLoader.getURLs(), contextClassLoader);
    Thread.currentThread().setContextClassLoader(classLoader);
    try {
        return Class.forName("org.hippoecm.repository.LocalHippoRepository", true, classLoader)
                .getMethod("create", String.class, String.class).invoke(null, repoPath, repoConfig);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:org.openmrs.logic.CompilingClassLoader.java

private List<File> getCompilerClasspath() {
    List<File> files = new ArrayList<File>();
    Collection<ModuleClassLoader> moduleClassLoaders = ModuleFactory.getModuleClassLoaders();

    //check module dependencies
    for (ModuleClassLoader moduleClassLoader : moduleClassLoaders) {
        URL[] urls = moduleClassLoader.getURLs();
        for (URL url : urls)
            files.add(new File(url.getFile()));
    }/*from   w ww.jav  a  2 s . c o  m*/

    // check current class loader and all its parents
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    while (classLoader != null) {
        if (classLoader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
            URL[] urls = urlClassLoader.getURLs();
            for (URL url : urls)
                files.add(new File(url.getFile()));
        }
        classLoader = classLoader.getParent();
    }

    return files;

}

From source file:org.orbeon.oxf.util.SystemUtils.java

/**
 * Walks class loader hierarchy of clazz looking for instances of URLClassLoader.
 * For each found gets file urls and adds, converted, elements to the path.
 * Note that the more junior a class loader is the later in the path it's
 * contribution is. <br/>//from  ww w.j av  a2 s. c o  m
 * Also, tries to deal with fact that urls may or may not be encoded.
 * Converts the urls to java.io.File and checks for existence.  If it
 * exists file name is used as is.  If not name is URLDecoded.  If the
 * decoded form exists that that is used.  If neither exists then the
 * undecoded for is used.
 *
 * @param clazz Class to try and build a classpath from.
 * @return   java.io.File.pathSeparator delimited path.
 */
public static String pathFromLoaders(final Class clazz) throws java.io.UnsupportedEncodingException {
    final TreeSet sysPths = new TreeSet();
    gatherSystemPaths(sysPths);
    final StringBuilder sbuf = new StringBuilder();
    final LinkedList urlLst = new LinkedList();
    for (ClassLoader cl = clazz.getClassLoader(); cl != null; cl = cl.getParent()) {
        if (!(cl instanceof java.net.URLClassLoader)) {
            continue;
        }
        final java.net.URLClassLoader ucl = (java.net.URLClassLoader) cl;
        final java.net.URL[] urls = ucl.getURLs();
        if (urls == null)
            continue;
        for (int i = urls.length - 1; i > -1; i--) {
            final java.net.URL url = urls[i];
            final String prot = url.getProtocol();
            if (!"file".equalsIgnoreCase(prot))
                continue;
            urlLst.addFirst(url);
        }
    }
    for (final Iterator itr = urlLst.iterator(); itr.hasNext();) {
        final java.net.URL url = (java.net.URL) itr.next();
        final String fnam = url.getFile();
        final File fil = new File(fnam);
        if (sysPths.contains(fil))
            continue;
        // 11/14/2004 d : Odd test attempts to deal with fact that
        // a.) The URLs passed to a URLClassLoader don't have to be encoded
        //     in general.
        // b.) The app class loader and the extensions class loader, the
        //     jdk class loaders responsible for loading classes from classpath
        //     and the extensions dir respectively, do encode their urls.
        // c.) java.io.File.toURL doesn't produce encoded urls. ( Perhaps
        //     a sun bug... )
        // As you can see given (a) and (c) odds are pretty good that
        // should anyone use something other than jdk class loaders we
        // will end up unencoded urls.
        if (!fil.exists()) {
            final String unEncNam = URLDecoder.decode(fnam, "utf-8");
            final File unEncFil = new File(unEncNam);
            if (unEncFil.exists())
                sbuf.append(unEncNam);
        } else {
            sbuf.append(fnam);
        }
        sbuf.append(File.pathSeparatorChar);
    }
    final String ret = sbuf.toString();
    return ret;
}

From source file:org.roda.core.util.ClassLoaderUtility.java

/**
 * Add URL to CLASSPATH//from   w  ww  .  ja va 2  s  .  c  o  m
 * 
 * @param url
 *          {@link URL}
 * @throws IOException
 *           IOException
 */
public static void addURL(URL url) throws IOException {

    URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL urls[] = sysLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {

        if (StringUtils.equalsIgnoreCase(urls[i].toString(), url.toString())) {
            LOGGER.debug("URL {} is already in the CLASSPATH", url);
            return;
        }
    }

    try {
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", PARAMETERS);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { url });
    } catch (Throwable t) {
        throw new IOException("Error, could not add URL to system classloader", t);
    }
}

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();//from  w  ww . ja v  a2s.c o m
            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;
}