Example usage for java.net URLClassLoader newInstance

List of usage examples for java.net URLClassLoader newInstance

Introduction

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

Prototype

public static URLClassLoader newInstance(final URL[] urls, final ClassLoader parent) 

Source Link

Document

Creates a new instance of URLClassLoader for the specified URLs and parent class loader.

Usage

From source file:org.freeplane.plugin.script.GenericScript.java

private static ClassLoader createClassLoader() {
    if (classLoader == null) {
        final List<String> classpath = ScriptResources.getClasspath();
        final List<URL> urls = new ArrayList<URL>();
        for (String path : classpath) {
            urls.add(pathToUrl(path));//from  w  w w  .  j  a  v  a  2 s . c o  m
        }
        classLoader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]),
                GenericScript.class.getClassLoader());
    }
    return classLoader;
}

From source file:de.thetaphi.forbiddenapis.cli.CliMain.java

public void run() throws ExitException {
    final File classesDirectory = new File(cmd.getOptionValue(dirOpt.getLongOpt())).getAbsoluteFile();

    // parse classpath given as argument; add -d to classpath, too
    final String[] classpath = cmd.getOptionValues(classpathOpt.getLongOpt());
    final URL[] urls;
    try {/* w  w  w  . j a v a 2s  .c om*/
        if (classpath == null) {
            urls = new URL[] { classesDirectory.toURI().toURL() };
        } else {
            urls = new URL[classpath.length + 1];
            int i = 0;
            for (final String cpElement : classpath) {
                urls[i++] = new File(cpElement).toURI().toURL();
            }
            urls[i++] = classesDirectory.toURI().toURL();
            assert i == urls.length;
        }
    } catch (MalformedURLException mfue) {
        throw new ExitException(EXIT_ERR_OTHER, "The given classpath is invalid: " + mfue);
    }
    // System.err.println("Classpath: " + Arrays.toString(urls));

    final URLClassLoader loader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
    try {
        final EnumSet<Checker.Option> options = EnumSet.of(FAIL_ON_VIOLATION);
        if (!cmd.hasOption(allowmissingclassesOpt.getLongOpt()))
            options.add(FAIL_ON_MISSING_CLASSES);
        if (!cmd.hasOption(allowunresolvablesignaturesOpt.getLongOpt()))
            options.add(FAIL_ON_UNRESOLVABLE_SIGNATURES);
        final Checker checker = new Checker(LOG, loader, options);

        if (!checker.isSupportedJDK) {
            throw new ExitException(EXIT_UNSUPPORTED_JDK, String.format(Locale.ENGLISH,
                    "Your Java runtime (%s %s) is not supported by forbiddenapis. Please run the checks with a supported JDK!",
                    System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version")));
        }

        final String[] suppressAnnotations = cmd.getOptionValues(suppressannotationsOpt.getLongOpt());
        if (suppressAnnotations != null)
            for (String a : suppressAnnotations) {
                checker.addSuppressAnnotation(a);
            }

        LOG.info("Scanning for classes to check...");
        if (!classesDirectory.exists()) {
            throw new ExitException(EXIT_ERR_OTHER,
                    "Directory with class files does not exist: " + classesDirectory);
        }
        String[] includes = cmd.getOptionValues(includesOpt.getLongOpt());
        if (includes == null || includes.length == 0) {
            includes = new String[] { "**/*.class" };
        }
        final String[] excludes = cmd.getOptionValues(excludesOpt.getLongOpt());
        final DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir(classesDirectory);
        ds.setCaseSensitive(true);
        ds.setIncludes(includes);
        ds.setExcludes(excludes);
        ds.addDefaultExcludes();
        ds.scan();
        final String[] files = ds.getIncludedFiles();
        if (files.length == 0) {
            throw new ExitException(EXIT_ERR_OTHER,
                    String.format(Locale.ENGLISH,
                            "No classes found in directory %s (includes=%s, excludes=%s).", classesDirectory,
                            Arrays.toString(includes), Arrays.toString(excludes)));
        }

        try {
            final String[] bundledSignatures = cmd.getOptionValues(bundledsignaturesOpt.getLongOpt());
            if (bundledSignatures != null)
                for (String bs : new LinkedHashSet<String>(Arrays.asList(bundledSignatures))) {
                    checker.addBundledSignatures(bs, null);
                }
            if (cmd.hasOption(internalruntimeforbiddenOpt.getLongOpt())) {
                LOG.warn(DEPRECATED_WARN_INTERNALRUNTIME);
                checker.addBundledSignatures(BS_JDK_NONPORTABLE, null);
            }

            final String[] signaturesFiles = cmd.getOptionValues(signaturesfileOpt.getLongOpt());
            if (signaturesFiles != null)
                for (String sf : new LinkedHashSet<String>(Arrays.asList(signaturesFiles))) {
                    final File f = new File(sf).getAbsoluteFile();
                    checker.parseSignaturesFile(f);
                }
        } catch (IOException ioe) {
            throw new ExitException(EXIT_ERR_OTHER,
                    "IO problem while reading files with API signatures: " + ioe);
        } catch (ParseException pe) {
            throw new ExitException(EXIT_ERR_OTHER, "Parsing signatures failed: " + pe.getMessage());
        }

        if (checker.hasNoSignatures()) {
            throw new ExitException(EXIT_ERR_CMDLINE, String.format(Locale.ENGLISH,
                    "No API signatures found; use parameters '--%s', '--%s', and/or '--%s' to define those!",
                    bundledsignaturesOpt.getLongOpt(), signaturesfileOpt.getLongOpt(),
                    internalruntimeforbiddenOpt.getLongOpt()));
        }

        try {
            checker.addClassesToCheck(classesDirectory, files);
        } catch (IOException ioe) {
            throw new ExitException(EXIT_ERR_OTHER, "Failed to load one of the given class files: " + ioe);
        }

        try {
            checker.run();
        } catch (ForbiddenApiException fae) {
            throw new ExitException(EXIT_VIOLATION, fae.getMessage());
        }
    } finally {
        // Java 7 supports closing URLClassLoader, so check for Closeable interface:
        if (loader instanceof Closeable)
            try {
                ((Closeable) loader).close();
            } catch (IOException ioe) {
                // ignore
            }
    }
}

From source file:de.thetaphi.forbiddenapis.CliMain.java

public void run() throws ExitException {
    final File classesDirectory = new File(cmd.getOptionValue(dirOpt.getLongOpt())).getAbsoluteFile();

    // parse classpath given as argument; add -d to classpath, too
    final String[] classpath = cmd.getOptionValues(classpathOpt.getLongOpt());
    final URL[] urls;
    try {/*from   w  ww  .  j av  a 2s  .  c  o m*/
        if (classpath == null) {
            urls = new URL[] { classesDirectory.toURI().toURL() };
        } else {
            urls = new URL[classpath.length + 1];
            int i = 0;
            for (final String cpElement : classpath) {
                urls[i++] = new File(cpElement).toURI().toURL();
            }
            urls[i++] = classesDirectory.toURI().toURL();
            assert i == urls.length;
        }
    } catch (MalformedURLException mfue) {
        throw new ExitException(EXIT_ERR_OTHER, "The given classpath is invalid: " + mfue);
    }
    // System.err.println("Classpath: " + Arrays.toString(urls));

    final URLClassLoader loader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
    try {
        final EnumSet<Checker.Option> options = EnumSet.of(FAIL_ON_VIOLATION);
        if (cmd.hasOption(internalruntimeforbiddenOpt.getLongOpt()))
            options.add(INTERNAL_RUNTIME_FORBIDDEN);
        if (!cmd.hasOption(allowmissingclassesOpt.getLongOpt()))
            options.add(FAIL_ON_MISSING_CLASSES);
        if (!cmd.hasOption(allowunresolvablesignaturesOpt.getLongOpt()))
            options.add(FAIL_ON_UNRESOLVABLE_SIGNATURES);
        final Checker checker = new Checker(loader, options) {
            @Override
            protected void logError(String msg) {
                CliMain.this.logError(msg);
            }

            @Override
            protected void logWarn(String msg) {
                CliMain.this.logWarn(msg);
            }

            @Override
            protected void logInfo(String msg) {
                CliMain.this.logInfo(msg);
            }
        };

        if (!checker.isSupportedJDK) {
            throw new ExitException(EXIT_UNSUPPORTED_JDK, String.format(Locale.ENGLISH,
                    "Your Java runtime (%s %s) is not supported by forbiddenapis. Please run the checks with a supported JDK!",
                    System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version")));
        }

        final String[] suppressAnnotations = cmd.getOptionValues(suppressannotationsOpt.getLongOpt());
        if (suppressAnnotations != null)
            for (String a : suppressAnnotations) {
                checker.addSuppressAnnotation(a);
            }

        logInfo("Scanning for classes to check...");
        if (!classesDirectory.exists()) {
            throw new ExitException(EXIT_ERR_OTHER,
                    "Directory with class files does not exist: " + classesDirectory);
        }
        String[] includes = cmd.getOptionValues(includesOpt.getLongOpt());
        if (includes == null || includes.length == 0) {
            includes = new String[] { "**/*.class" };
        }
        final String[] excludes = cmd.getOptionValues(excludesOpt.getLongOpt());
        final DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir(classesDirectory);
        ds.setCaseSensitive(true);
        ds.setIncludes(includes);
        ds.setExcludes(excludes);
        ds.addDefaultExcludes();
        ds.scan();
        final String[] files = ds.getIncludedFiles();
        if (files.length == 0) {
            throw new ExitException(EXIT_ERR_OTHER,
                    String.format(Locale.ENGLISH,
                            "No classes found in directory %s (includes=%s, excludes=%s).", classesDirectory,
                            Arrays.toString(includes), Arrays.toString(excludes)));
        }

        try {
            final String[] bundledSignatures = cmd.getOptionValues(bundledsignaturesOpt.getLongOpt());
            if (bundledSignatures != null)
                for (String bs : bundledSignatures) {
                    logInfo("Reading bundled API signatures: " + bs);
                    checker.parseBundledSignatures(bs, null);
                }
            final String[] signaturesFiles = cmd.getOptionValues(signaturesfileOpt.getLongOpt());
            if (signaturesFiles != null)
                for (String sf : signaturesFiles) {
                    final File f = new File(sf).getAbsoluteFile();
                    logInfo("Reading API signatures: " + f);
                    checker.parseSignaturesFile(new FileInputStream(f));
                }
        } catch (IOException ioe) {
            throw new ExitException(EXIT_ERR_OTHER,
                    "IO problem while reading files with API signatures: " + ioe);
        } catch (ParseException pe) {
            throw new ExitException(EXIT_ERR_OTHER, "Parsing signatures failed: " + pe.getMessage());
        }

        if (checker.hasNoSignatures()) {
            throw new ExitException(EXIT_ERR_CMDLINE, String.format(Locale.ENGLISH,
                    "No API signatures found; use parameters '--%s', '--%s', and/or '--%s' to define those!",
                    bundledsignaturesOpt.getLongOpt(), signaturesfileOpt.getLongOpt(),
                    internalruntimeforbiddenOpt.getLongOpt()));
        }

        logInfo("Loading classes to check...");
        try {
            for (String f : files) {
                checker.addClassToCheck(new FileInputStream(new File(classesDirectory, f)));
            }
        } catch (IOException ioe) {
            throw new ExitException(EXIT_ERR_OTHER, "Failed to load one of the given class files: " + ioe);
        }

        logInfo("Scanning for API signatures and dependencies...");
        try {
            checker.run();
        } catch (ForbiddenApiException fae) {
            throw new ExitException(EXIT_VIOLATION, fae.getMessage());
        }
    } finally {
        // Java 7 supports closing URLClassLoader, so check for Closeable interface:
        if (loader instanceof Closeable)
            try {
                ((Closeable) loader).close();
            } catch (IOException ioe) {
                // ignore
            }
    }
}

From source file:org.apache.solr.core.SolrResourceLoader.java

private static URLClassLoader replaceClassLoader(final URLClassLoader oldLoader, final File base,
        final FileFilter filter) {
    if (null != base && base.canRead() && base.isDirectory()) {
        File[] files = base.listFiles(filter);

        if (null == files || 0 == files.length)
            return oldLoader;

        URL[] oldElements = oldLoader.getURLs();
        URL[] elements = new URL[oldElements.length + files.length];
        System.arraycopy(oldElements, 0, elements, 0, oldElements.length);

        for (int j = 0; j < files.length; j++) {
            try {
                URL element = files[j].toURI().normalize().toURL();
                log.info("Adding '" + element.toString() + "' to classloader");
                elements[oldElements.length + j] = element;
            } catch (MalformedURLException e) {
                SolrException.log(log, "Can't add element to classloader: " + files[j], e);
            }//from w  ww.  j ava 2s. c om
        }
        ClassLoader oldParent = oldLoader.getParent();
        IOUtils.closeWhileHandlingException(oldLoader); // best effort
        return URLClassLoader.newInstance(elements, oldParent);
    }
    // are we still here?
    return oldLoader;
}

From source file:org.apache.solr.core.SolrResourceLoader.java

/**
 * Convenience method for getting a new ClassLoader using all files found
 * in the specified lib directory./*from w w w  . j a v  a2s .  com*/
 */
static URLClassLoader createClassLoader(final File libDir, ClassLoader parent) {
    if (null == parent) {
        parent = Thread.currentThread().getContextClassLoader();
    }
    return replaceClassLoader(URLClassLoader.newInstance(new URL[0], parent), libDir, null);
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

private ClassLoader getClassloader() throws MojoExecutionException {
    try {//from www. j ava2s.co  m
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

        final List<URL> classPathUrls = getClasspath();

        final URLClassLoader urlClassLoader = URLClassLoader
                .newInstance(classPathUrls.toArray(new URL[classPathUrls.size()]), contextClassLoader);

        trackExecution(
                "Classpath: " + classPathUrls.stream().map(u -> u.toString()).collect(Collectors.joining(",")));

        Thread.currentThread().setContextClassLoader(urlClassLoader);

        return urlClassLoader;
    } catch (final Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.alfresco.solr.client.SOLRAPIClientTest.java

public ClassLoader getResourceClassLoader() {

    File f = new File("woof", "alfrescoResources");
    if (f.canRead() && f.isDirectory()) {

        URL[] urls = new URL[1];

        try {/*from   w ww  .  ja v a2  s  . com*/
            URL url = f.toURI().normalize().toURL();
            urls[0] = url;
        } catch (MalformedURLException e) {
            throw new AlfrescoRuntimeException("Failed to add resources to classpath ", e);
        }

        return URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    } else {
        return this.getClass().getClassLoader();
    }
}

From source file:edu.usc.pgroup.floe.utils.Utils.java

/**
 * Creates and returns a class loader with the given jar file.
 * @param path path to the jar file./*from  ww  w  .  j av a  2  s.c om*/
 * @param parent parent class loader.
 * @return a new child class loader
 */
public static ClassLoader getClassLoader(final String path, final ClassLoader parent) {
    ClassLoader loader = null;
    try {
        File relativeJarLoc = new File(path);

        URL jarLoc = new URL("file://" + relativeJarLoc.getAbsolutePath());

        LOGGER.info("Loading jar: {} into class loader.", jarLoc);
        loader = URLClassLoader.newInstance(new URL[] { jarLoc }, parent);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        LOGGER.error("Invalid Jar URL Exception: {}", e);
    }
    return loader;
}

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/*from   ww  w .  ja  v  a2 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:com.asakusafw.workflow.executor.TaskExecutors.java

private static URLClassLoader loader(TaskExecutionContext context, List<? extends Path> libraries) {
    URL[] urls = libraries.stream().map(Path::toUri).flatMap(uri -> {
        try {/*from   w  w  w.  j av  a2 s.co  m*/
            return Stream.of(uri.toURL());
        } catch (MalformedURLException e) {
            LOG.warn("failed to convert URI: {}", uri, e);
            return Stream.empty();
        }
    }).toArray(URL[]::new);
    return URLClassLoader.newInstance(urls, context.getClassLoader());
}