Example usage for java.net URLClassLoader loadClass

List of usage examples for java.net URLClassLoader loadClass

Introduction

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

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:org.eclipse.wb.android.internal.support.AndroidBridge.java

/**
 * Checks for legacy API and rewrites legacy bridge to be able to collect View instances.
 *//*ww w  .  j  a  v a  2  s  . c o  m*/
private LayoutLibrary checkLegacy(AndroidTargetData data, LayoutLibrary layoutLibrary) throws Exception {
    if (ReflectionUtils.getFieldObject(layoutLibrary, "mBridge") != null) {
        // do nothing, modern api
        return layoutLibrary;
    }
    // create new bridge using rewriting class loader
    Object legacyBridge = ReflectionUtils.getFieldObject(layoutLibrary, "mLegacyBridge");
    URLClassLoader legacyClassLoader = (URLClassLoader) legacyBridge.getClass().getClassLoader();
    URLClassLoader newClassLoader = new LegacyBridgeClassLoader(legacyClassLoader.getURLs(),
            AndroidBridge.class.getClassLoader());
    // create new
    Class<?> legacyClass = newClassLoader.loadClass(LayoutLibrary.CLASS_BRIDGE);
    ILayoutBridge newLegacyBridge = (ILayoutBridge) legacyClass.newInstance();
    // re-init
    IAndroidTarget target = (IAndroidTarget) ReflectionUtils.getFieldObject(data, "mTarget");
    String fontPath = target.getPath(IAndroidTarget.FONTS);
    newLegacyBridge.init(fontPath, data.getEnumValueMap());
    // store
    ReflectionUtils.setField(layoutLibrary, "mLegacyBridge", newLegacyBridge);
    ReflectionUtils.setField(layoutLibrary, "mClassLoader", newClassLoader);
    // setup collector
    ReflectionUtils.setField(newLegacyBridge, "collector", new IViewsCollector() {
        public void collect(Object view, Object key) {
            if (view != null) {
                m_legacyViewsCollection.put(key, view);
            }
        }
    });
    return layoutLibrary;
}

From source file:org.apache.synapse.core.axis2.ExtensionDeployer.java

private <T> List<T> getProviders(Class<T> providerClass, URLClassLoader loader)
        throws DeploymentException, IOException {

    List<T> providers = new LinkedList<T>();
    String providerClassName = providerClass.getName();
    providerClassName = providerClassName.substring(providerClassName.indexOf('.') + 1);
    URL servicesURL = loader.findResource("META-INF/services/" + providerClass.getName());
    if (servicesURL != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(servicesURL.openStream()));
        try {/* www .j  ava 2s .  co m*/
            String className;
            while ((className = in.readLine()) != null) {
                log.info("Loading the " + providerClassName + " implementation: " + className);
                try {
                    Class<? extends T> clazz = loader.loadClass(className).asSubclass(providerClass);
                    providers.add(clazz.newInstance());
                } catch (ClassNotFoundException e) {
                    handleException("Unable to find the specified class on the path or " + "in the jar file",
                            e);
                } catch (IllegalAccessException e) {
                    handleException("Unable to load the class from the jar", e);
                } catch (InstantiationException e) {
                    handleException("Unable to instantiate the class specified", e);
                }
            }
        } finally {
            in.close();
        }
    }
    return providers;
}

From source file:org.apache.synapse.deployers.ExtensionDeployer.java

private <T> List<T> getProviders(Class<T> providerClass, URLClassLoader loader) throws IOException {

    List<T> providers = new LinkedList<T>();
    String providerClassName = providerClass.getName();
    providerClassName = providerClassName.substring(providerClassName.indexOf('.') + 1);
    URL servicesURL = loader.findResource("META-INF/services/" + providerClass.getName());
    if (servicesURL != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(servicesURL.openStream()));
        try {//from w w w .jav a 2s .  c  o m
            String className;
            while ((className = in.readLine()) != null && (!className.trim().equals(""))) {
                log.info("Loading the " + providerClassName + " implementation: " + className);
                try {
                    Class<? extends T> clazz = loader.loadClass(className).asSubclass(providerClass);
                    providers.add(clazz.newInstance());
                } catch (ClassNotFoundException e) {
                    handleException("Unable to find the specified class on the path or " + "in the jar file",
                            e);
                } catch (IllegalAccessException e) {
                    handleException("Unable to load the class from the jar", e);
                } catch (InstantiationException e) {
                    handleException("Unable to instantiate the class specified", e);
                }
            }
        } finally {
            in.close();
        }
    }
    return providers;
}

From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java

/**
 * WARNING: This method relies on having access to the same repository
 * URLs as the server uses.//  ww w.  j  ava2 s.  co m
 *
 * @param request portlet request
 * @param data    info about jars to include
 * @return driver class
 */
private static Class attemptDriverLoad(PortletRequest request, PoolData data) {
    List<URL> list = new ArrayList<URL>();
    try {
        String[] jars = data.getJars();
        if (jars == null) {
            log.error("Driver load failed since no jar files were selected.");
            return null;
        }
        ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories();

        for (String jar : jars) {
            Artifact artifact = Artifact.create(jar);
            for (ListableRepository repo : repos) {
                File url = repo.getLocation(artifact);
                if (url != null) {
                    list.add(url.toURI().toURL());
                }
            }
        }
        URLClassLoader loader = new URLClassLoader(list.toArray(new URL[list.size()]),
                DatabasePoolPortlet.class.getClassLoader());
        try {
            return loader.loadClass(data.driverClass);
        } catch (ClassNotFoundException e) {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java

/**
 * Runs tests in testLocation on the source code given in the parameter.
 *
 * @param submissionBinariesLocation//  w w  w  .  j  a  v  a 2  s.co  m
 *            The path to the compiled binaries of the submission.
 *
 * @return the {@link TestOutput} containing the test results.
 *
 * @throws ClassNotFoundException
 *             Throws if the loaded Classes are not found
 * @throws IOException
 *             Throws if the sourceCodeLocation is malformed or the
 *             {@link URLClassLoader} can't be closed.
 */
@Override
public TestOutput testSubmission(Path submissionBinariesLocation) throws ClassNotFoundException, IOException {

    // if there are no tests create and empty TestOutput with didTest false
    if ((testLocation == null) || testLocation.toString().isEmpty()) {
        return new TestOutput(null, false);
    } else {

        List<Result> results = new LinkedList<>();

        // create the classloader
        URL submissionURL = submissionBinariesLocation.toUri().toURL();
        URL testsURL = testLocation.toUri().toURL();

        // URLClassLoader loader =
        // new URLClassLoader(new URL[] { submissionURL, testsURL });

        URLClassLoader loader = new URLClassLoader(new URL[] { testsURL, submissionURL });

        // iterate submission source code files and load the .class files.
        /*
         * We need to iterate all files in a directory and thus are using
         * the apache commons io utility FileUtils.listFiles. This needs a)
         * the directory, and b) a file filter for which we also use the
         * one supplied by apache commons io.
         */

        Path submissionBin = submissionBinariesLocation.toAbsolutePath();
        List<Path> exploreDirectory = exploreDirectory(submissionBin, ExplorationType.CLASSFILES);
        for (Path path : exploreDirectory) {

            String quallifiedName = getQuallifiedName(submissionBin, path);
            loader.loadClass(quallifiedName);
        }

        // iterate tests, load them and run them
        Path testLoc = testLocation.toAbsolutePath();
        List<Path> exploreDirectory2 = exploreDirectory(testLoc, ExplorationType.SOURCEFILES);
        for (Path path : exploreDirectory2) {

            String unitTestName = getQuallifiedNameFromSource(path);
            try {
                Class<?> testerClass = loader.loadClass(unitTestName);
                Result runClasses = JUnitCore.runClasses(testerClass);
                results.add(runClasses);
            } catch (Throwable e) {
                LOGGER.severe("can't load class: " + unitTestName);
                LOGGER.severe(e.getMessage());
            }
        }

        loader.close();
        // creates new TestOutput from results and returns it
        return new TestOutput(results, true);
    }
}

From source file:org.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*/* w w  w .  j ava  2  s.com*/
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}

From source file:net.sourceforge.sqlexplorer.service.SqlexplorerService.java

private Driver createGenericJDBC(String driverJars, String driverName) throws Exception {
    Driver driver = null;/*from w  w  w  .  jav  a2s . c  o  m*/
    String[] driverJarPath = driverJars.split(SEMICOLON_STRING);
    try {
        int driverCount = 0;
        URL[] driverUrl = new URL[driverJarPath.length];
        for (String dirverpath : driverJarPath) {
            driverUrl[driverCount++] = new File(dirverpath).toURL();
        }
        URLClassLoader cl = URLClassLoader.newInstance(driverUrl,
                Thread.currentThread().getContextClassLoader());
        Class c = cl.loadClass(driverName);
        driver = (Driver) c.newInstance();
    } catch (Exception ex) {
        log.error(ex, ex);
        throw ex;
    }
    return driver;
}

From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java

private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = getCompiler().getStandardFileManager(diagnostics, null, null);

    // This sets up the class path that the compiler will use.
    // I've added the .jar file that contains the DoStuff interface within
    // in it...// w w  w.  j  a  va  2s . c o  m
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(getAllJarsClassPathInMavenLocalRepo());
    optionList.add("-verbose");

    File helloWorldJava = new File(classFilePathName);

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);

    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        // Create a new custom class loader, pointing to the directory that
        // contains the compiled
        // classes, this should point to the top of the package structure!
        //TODO the / separator needs to be revised to platform awared 
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() },
                Thread.currentThread().getContextClassLoader());
        String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/";
        ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent());
        classLoader.loadClass(className);
        classLoader.close();
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(),
                    diagnostic.getSource(), diagnostic.getMessage(new Locale("en")));
        }
    }
}

From source file:com.varaneckas.hawkscope.plugin.PluginManager.java

private void processPlugin(final File pluginDir, final String jar) {
    try {//from   www .ja  v  a  2s .c om
        final File jarFile = new File(pluginDir.getAbsolutePath() + "/" + jar);
        final URLClassLoader classLoader = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
        final Reader r = new InputStreamReader(classLoader.getResourceAsStream("plugin.loader"));
        String pluginClass = "";
        int c = 0;
        while ((c = r.read()) != -1) {
            pluginClass += (char) c;
        }
        r.close();
        log.debug("Processing Plugin: " + pluginClass);
        if (!isPluginEnabled(pluginClass)) {
            log.debug("Plugin disabled, skipping");
            getAllPlugins().add(new DisabledPlugin(pluginClass));
            return;
        }
        Class<?> p = classLoader.loadClass(pluginClass);
        Method creator = null;
        try {
            creator = p.getMethod("getInstance", new Class[] {});
        } catch (final NoSuchMethodException no) {
            log.debug("Plugin does not implement a singleton getter");
        }
        Plugin plugin;
        if (creator == null) {
            plugin = (Plugin) p.newInstance();
        } else {
            plugin = (Plugin) creator.invoke(p, new Object[] {});
        }
        creator = null;
        p = null;
        if (plugin != null) {
            log.debug("Adding plugin: " + plugin);
            getAllPlugins().add(plugin);
        }
    } catch (final Exception e) {
        log.warn("Failed loading plugin: " + jar, e);
    }
}

From source file:dk.netarkivet.externalsoftware.HeritrixTests.java

/**
 * Check, if class exists, and can be loaded. TODO try to instantiate the class as well.
 *
 * @param className a name for a class//from w  ww.  java2 s  . c  om
 * @return true, if class exists, and can be loaded.XS
 */
private boolean validClass(String className) {
    URLClassLoader loader = URLClassLoader.newInstance(classPathAsURLS());
    try {
        loader.loadClass(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}