Example usage for java.net URLClassLoader URLClassLoader

List of usage examples for java.net URLClassLoader URLClassLoader

Introduction

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

Prototype

URLClassLoader(URL[] urls, AccessControlContext acc) 

Source Link

Usage

From source file:org.gradle.initialization.BuildSourceBuilder.java

public URLClassLoader buildAndCreateClassLoader(StartParameter startParameter) {
    Set<File> classpath = createBuildSourceClasspath(startParameter);
    Iterator<File> classpathIterator = classpath.iterator();
    URL[] urls = new URL[classpath.size()];
    for (int i = 0; i < urls.length; i++) {
        try {/*from  w w  w  .  j  a  v  a2s . c  om*/
            urls[i] = classpathIterator.next().toURI().toURL();
        } catch (MalformedURLException e) {
            throw new UncheckedIOException(e);
        }
    }
    return new URLClassLoader(urls, classLoaderFactory.getRootClassLoader());
}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

/**
 * Scans the code base for public methods in the correct packages. The result is stored in the code base.
 *
 * @param codeBase The code base to scan.
 * @return The number of classes containing at least one included method.
 *///from w  w w.ja  v a 2s . co  m
public int scanSignatures(CodeBase codeBase) {
    long startedAt = System.currentTimeMillis();
    log.debug("Scanning code base {}", codeBase);
    int result = 0;

    URLClassLoader appClassLoader = new URLClassLoader(codeBase.getUrls(), System.class.getClassLoader());
    Set<String> packages = new TreeSet<>(codeBase.getConfig().getNormalizedPackages());
    Set<String> excludePackages = new TreeSet<>(codeBase.getConfig().getNormalizedExcludePackages());

    Set<String> recognizedTypes = getRecognizedTypes(packages, appClassLoader);

    for (String type : recognizedTypes) {
        try {
            Class<?> clazz = Class.forName(type, false, appClassLoader);
            findTrackedConstructors(codeBase, clazz);
            findTrackedMethods(codeBase, packages, excludePackages, clazz);
            result += 1;
        } catch (ClassNotFoundException | NoClassDefFoundError e) {
            log.warn("Cannot analyze " + type + ": " + e);
        }
    }

    if (codeBase.isEmpty()) {
        log.warn("{} does not contain any classes with package packages {}.'", codeBase,
                codeBase.getConfig().getNormalizedPackages());
    }

    codeBase.writeSignaturesToDisk();

    log.info("Scanned {} with package prefix {} in {} ms, found {} methods in {} classes.", codeBase,
            codeBase.getConfig().getNormalizedPackages(), System.currentTimeMillis() - startedAt,
            codeBase.size(), result);

    return result;
}

From source file:org.jruyi.launcher.Main.java

public void init(String[] args) throws Exception {
    ClassLoader classLoader = Main.class.getClassLoader();
    if (!(classLoader instanceof URLClassLoader))
        classLoader = new URLClassLoader(new URL[0], classLoader);

    final Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    boolean accessible = addUrl.isAccessible();
    if (!accessible)
        addUrl.setAccessible(true);//w  w  w .  ja v  a  2 s .co  m

    final ArrayList<String> pkgList = new ArrayList<>();
    final File[] jars = getLibJars();
    for (final File jar : jars) {
        final String exportPackages;
        try (JarFile jf = new JarFile(jar)) {
            exportPackages = jf.getManifest().getMainAttributes().getValue("Export-Package");
        }
        if (exportPackages != null)
            pkgList.add(exportPackages);
        addUrl.invoke(classLoader, jar.getCanonicalFile().toURI().toURL());
    }

    if (!accessible)
        addUrl.setAccessible(false);

    final int n = pkgList.size();
    if (n < 1)
        return;

    final StringBuilder builder = new StringBuilder(pkgList.get(0));
    for (int i = 1; i < n; ++i)
        builder.append(',').append(pkgList.get(i));

    final HashMap<String, String> props = new HashMap<>(3);
    props.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, builder.toString());

    final Class<?> clazz = classLoader.loadClass("org.jruyi.system.main.Ruyi");
    final Object ruyi = clazz.getMethod("getInstance").invoke(null);
    clazz.getMethod("setProperties", Map.class).invoke(ruyi, props);
    final String instConfUrl = (String) clazz.getMethod(RUYI_PROPERTY, String.class).invoke(ruyi,
            JRUYI_INST_CONF_URL);

    System.setProperty(ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY, Log4jCallback.class.getName());
    final String confFile = System.getProperty(LOG4J_CONF);
    if (confFile == null || confFile.trim().isEmpty())
        System.setProperty(LOG4J_CONF, instConfUrl + "log4j2.xml");

    m_ruyi = ruyi;
}

From source file:org.apache.spark.streaming.aliyun.mns.adapter.MNSAgentUtil.java

@SuppressWarnings("unchecked")
private static URLClassLoader getUrlClassLoader(Configuration conf, boolean runLocal) {
    if (urlClassLoader == null) {
        synchronized (MNSAgentUtil.class) {
            if (urlClassLoader == null) {
                try {
                    String[] internalDep = getMNSClasses(conf, runLocal);
                    ArrayList<URL> urls = new ArrayList<URL>();
                    if (internalDep != null) {
                        for (String dep : internalDep) {
                            urls.add(new URL("file://" + dep));
                        }/* www . ja  v  a2s.  c om*/
                    }
                    String[] cp;
                    if (SystemUtils.IS_OS_WINDOWS) {
                        cp = System.getProperty("java.class.path").split(";");
                        for (String entity : cp) {
                            urls.add(new URL("file:" + entity));
                        }
                    } else {
                        cp = System.getProperty("java.class.path").split(":");
                        for (String entity : cp) {
                            urls.add(new URL("file://" + entity));
                        }
                    }
                    urlClassLoader = new URLClassLoader(urls.toArray(new URL[0]), null);
                } catch (Exception e) {
                    throw new RuntimeException("Can not initialize MNS " + "URLClassLoader, " + e.getMessage());
                }
            }
        }
    }
    return urlClassLoader;
}

From source file:com.katsu.dwm.reflection.JarUtils.java

/**
 * Return as stream a resource in a jar//from   w  w w  .  j  a va2s.c  om
 * @param jar
 * @param resource 
 */
public static InputStream getResourceAsStream(File jar, String resource) {
    try {
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { jar.toURI().toURL() }, null);
        return urlClassLoader.getResourceAsStream(resource);
    } catch (Exception e) {
        logger.error(e);
    }
    return null;
}

From source file:org.ebayopensource.turmeric.tools.codegen.AbstractServiceGeneratorTestCase.java

protected void setURLsInClassLoader(URL[] urls) {
    URLClassLoader loader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(loader);
}

From source file:org.cloudfoundry.tools.io.compiler.ResourceJavaFileManager.java

@Override
public ClassLoader getClassLoader(Location location) {
    try {/*from w w w  .j  a v a2 s. com*/
        Iterable<Resource> folders = getLocation(location);
        if (folders == null) {
            return null;
        }
        List<URL> urls = ResourceURL.getForResources(folders);
        ClassLoader parent = super.getClassLoader(location);
        return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.overlord.sramp.common.derived.ArtifactDeriverFactory.java

/**
  * Loads any extended derivers.  These can be contributed via the
  * standard Java service loading mechanism.
  *///  w w  w . j  a  v  a 2s. c  o  m
private static void loadExtendedDerivers() {
    // First load via the standard ServiceRegistry mechanism.
    Set<DeriverProvider> providers = ServiceRegistryUtil.getServices(DeriverProvider.class);
    for (DeriverProvider provider : providers) {
        Map<String, ArtifactDeriver> derivers = provider.createArtifactDerivers();
        if (derivers != null && !derivers.isEmpty()) {
            extendedDerivers.putAll(derivers);
        }
    }

    // Allow users to provide a directory path where we will check for JARs that
    // contain DeriverProvider implementations.
    Collection<ClassLoader> loaders = new LinkedList<ClassLoader>();
    String customDeriverDirPath = System.getProperty(SrampConstants.SRAMP_CUSTOM_DERIVER_DIR);
    if (customDeriverDirPath != null && customDeriverDirPath.trim().length() > 0) {
        File directory = new File(customDeriverDirPath);
        if (directory.isDirectory()) {
            List<URL> jarURLs = new ArrayList<URL>();
            Collection<File> jarFiles = FileUtils.listFiles(directory, new String[] { "jar" }, false); //$NON-NLS-1$
            for (File jarFile : jarFiles) {
                try {
                    URL jarUrl = jarFile.toURI().toURL();
                    jarURLs.add(jarUrl);
                } catch (MalformedURLException e) {
                }
            }
            URL[] urls = jarURLs.toArray(new URL[jarURLs.size()]);
            ClassLoader jarCL = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
            loaders.add(jarCL);
        }
    }
    // Now load all of these contributed DeriverProvider implementations
    for (ClassLoader loader : loaders) {
        for (DeriverProvider provider : ServiceLoader.load(DeriverProvider.class, loader)) {
            Map<String, ArtifactDeriver> derivers = provider.createArtifactDerivers();
            if (derivers != null && !derivers.isEmpty()) {
                extendedDerivers.putAll(derivers);
            }
        }
    }
}

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

private void init() {
    ClassLoader oldcl = Thread.currentThread().getContextClassLoader();

    File[] interpreterDirs = new File(conf.getInterpreterDir()).listFiles();
    if (interpreterDirs != null) {
        for (File path : interpreterDirs) {
            logger.info("Reading " + path.getAbsolutePath());
            URL[] urls = null;/*from   w w w. j av a  2 s  . co  m*/
            try {
                urls = recursiveBuildLibList(path);
            } catch (MalformedURLException e1) {
                logger.error("Can't load jars ", e1);
            }
            URLClassLoader ccl = new URLClassLoader(urls, oldcl);

            for (String className : interpreterClassList) {
                try {
                    Class.forName(className, true, ccl);
                    Set<String> keys = Interpreter.registeredInterpreters.keySet();
                    for (String intName : keys) {
                        if (className.equals(Interpreter.registeredInterpreters.get(intName))) {
                            logger.info("Interpreter " + intName + " found. class=" + className);
                            cleanCl.put(intName, ccl);

                            if (className.equals(interpreterClassList[0])) {
                                defaultInterpreterName = intName;
                            }
                        }
                    }
                } catch (ClassNotFoundException e) {
                    // nothing to do
                }
            }
        }
    }
}

From source file:org.apache.spark.streaming.aliyun.mns.adapter.ResourceLoader.java

@SuppressWarnings("unchecked")
public synchronized URLClassLoader getUrlClassLoader(Configuration conf, boolean runLocal) {
    if (urlClassLoader == null) {
        try {//  w ww . j a v a  2s  .c  om
            List<URL> urls = geClassLoaderURLs(conf, runLocal);
            urlClassLoader = new URLClassLoader(urls.toArray(new URL[0]), null);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialize MNS URLClassLoader, " + e.getMessage());
        }
    }
    return urlClassLoader;
}