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:de.juwimm.cms.content.modules.ModuleFactoryStandardImpl.java

public Module loadPlugins(String classname, List<String> additionalJarFiles) {
    Module module = null;/* w  ww.  j a v  a  2 s. c om*/
    Communication comm = ((Communication) getBean(Beans.COMMUNICATION));
    SiteValue site = comm.getCurrentSite();
    String urlPath = site.getDcfUrl();
    final String userHome = System.getProperty("user.home");
    final String fileSeparator = System.getProperty("file.separator");

    StringBuffer pluginCachePath = new StringBuffer(userHome);
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(".tizzitCache");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append("plugins");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(Constants.SERVER_HOST);
    pluginCachePath.append(fileSeparator);

    final String pluginPath = pluginCachePath.toString();

    final int addSize = additionalJarFiles.size();

    /* enthaelt alle Jar files die sich nicht auf dem lokalen Rechner befinden */
    ArrayList<String> httpLoad = new ArrayList<String>();

    for (int i = 0; i < addSize; i++) {
        String filePath = pluginPath + additionalJarFiles.get(i);
        File tempFile = new File(filePath);
        if (!tempFile.exists()) {
            httpLoad.add(additionalJarFiles.get(i));
        }
    }

    if (httpLoad.size() > 0) {
        File dir = new File(pluginPath);
        if (!dir.exists()) {
            if (log.isDebugEnabled())
                log.debug("Going to create plugin directory...");
            boolean ret = dir.mkdirs();
            if (!ret) {
                log.warn("Could not create plugin directory");
            }
        }

        /* laedt die Jarfiles auf den lokalen Rechner herunter */
        HttpClient httpclient = new HttpClient();
        for (int i = 0; i < httpLoad.size(); i++) {
            String url = urlPath + httpLoad.get(i);
            if (log.isDebugEnabled())
                log.debug("Plugin URL " + url);
            HttpMethod method = new GetMethod(url);
            try {
                int status = httpclient.executeMethod(method);
                if (status == HttpStatus.SC_OK) {
                    File file = new File(pluginPath + httpLoad.get(i));
                    byte[] data = method.getResponseBody();
                    if (log.isDebugEnabled())
                        log.debug("Received " + data.length + " bytes of data");
                    FileOutputStream output = new FileOutputStream(file);
                    output.write(data);
                    output.close();
                } else {
                    log.warn("No OK received");
                }
            } catch (HttpException htex) {
                log.warn("HTTP exception " + htex.getMessage());
            } catch (IOException ioe) {
                log.warn("IO exception " + ioe.getMessage());
            }
            method.releaseConnection();
        }
    }

    try {
        if (log.isDebugEnabled())
            log.debug("Creating URL");

        URL[] url = new URL[addSize];
        for (int i = 0; i < addSize; i++) {
            String jarModule = additionalJarFiles.get(i);
            String jarPath = "file:///" + pluginPath + jarModule;
            if (log.isDebugEnabled())
                log.debug("Jar path " + jarPath);
            url[i] = new URL(jarPath);
        }
        URLClassLoader cl = this.getURLClassLoader(url);
        //URLClassLoader cl = new URLClassLoader(url, this.getClass().getClassLoader());
        if (log.isDebugEnabled())
            log.debug("Created URL classloader");
        Class c = cl.loadClass(classname);
        if (log.isDebugEnabled())
            log.debug("Created class");
        module = (Module) c.newInstance();
        if (log.isDebugEnabled())
            log.debug("Got the module");
    } catch (Exception loadex) {
        log.warn(loadex.getClass().toString());
        log.error("Cannot load from URL " + loadex.getMessage(), loadex);
    }
    return module;
}

From source file:com.greenpepper.maven.runner.CommandLineRunner.java

private void runClassicRunner(List<String> args) throws Exception {
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    initMavenEmbedder(originalClassLoader);

    resolveProject();/*from  www  . ja v  a2  s.c  o  m*/

    ProjectFileResolver.MavenGAV mavenGAV = resolvers.getMavenGAV();
    if (StringUtils.isNotEmpty(mavenGAV.getClassifier())) {
        Artifact artifactWithClassifier = embedder.createArtifactWithClassifier(project.getGroupId(),
                project.getArtifactId(), project.getVersion(), mavenGAV.getPackaging(),
                mavenGAV.getClassifier());
        resolve(artifactWithClassifier, artifacts);
    } else {
        resolveScopedArtifacts();

        resolveMavenPluginArtifact();

        resolveProjectArtifact();
    }

    URL[] classpaths = buildRuntimeClasspaths();

    URLClassLoader urlClassLoader = new URLClassLoader(classpaths, originalClassLoader);

    Thread.currentThread().setContextClassLoader(urlClassLoader);

    ReflectionUtils.setDebugEnabled(urlClassLoader, isDebug);
    ReflectionUtils.setSystemOutputs(urlClassLoader, logger.getOut(), System.err);

    Class<?> mainClass = urlClassLoader.loadClass("com.greenpepper.runner.Main");

    logger.debug("Invoking: com.greenpepper.runner.Main " + StringUtils.join(args, ' '));
    ReflectionUtils.invokeMain(mainClass, args);

    Thread.currentThread().setContextClassLoader(originalClassLoader);

}

From source file:com.panet.imeta.core.plugins.PluginLoader.java

private void fromXML(FileObject xml, FileObject parent)
        throws IOException, ClassNotFoundException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(KettleVFS.getInputStream(xml));
    Node plugin = XMLHandler.getSubNode(doc, Plugin.PLUGIN);
    String id = XMLHandler.getTagAttribute(plugin, Plugin.ID);
    String description = XMLHandler.getTagAttribute(plugin, Plugin.DESCRIPTION);
    String iconfile = XMLHandler.getTagAttribute(plugin, Plugin.ICONFILE);
    String tooltip = XMLHandler.getTagAttribute(plugin, Plugin.TOOLTIP);
    String classname = XMLHandler.getTagAttribute(plugin, Plugin.CLASSNAME);
    String category = XMLHandler.getTagAttribute(plugin, Plugin.CATEGORY);
    String errorHelpfile = XMLHandler.getTagAttribute(plugin, Plugin.ERRORHELPFILE);

    // Localized categories
    ////from  w w  w  .j  a  v  a 2 s. com
    Node locCatsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_CATEGORY);
    int nrLocCats = XMLHandler.countNodes(locCatsNode, Plugin.CATEGORY);
    Map<String, String> localizedCategories = new Hashtable<String, String>();
    for (int j = 0; j < nrLocCats; j++) {
        Node locCatNode = XMLHandler.getSubNodeByNr(locCatsNode, Plugin.CATEGORY, j);
        String locale = XMLHandler.getTagAttribute(locCatNode, Plugin.LOCALE);
        String locCat = XMLHandler.getNodeValue(locCatNode);

        if (!Const.isEmpty(locale) && !Const.isEmpty(locCat)) {
            localizedCategories.put(locale.toLowerCase(), locCat);
        }
    }

    // Localized descriptions
    //
    Node locDescsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_DESCRIPTION);
    int nrLocDescs = XMLHandler.countNodes(locDescsNode, Plugin.DESCRIPTION);
    Map<String, String> localizedDescriptions = new Hashtable<String, String>();
    for (int j = 0; j < nrLocDescs; j++) {
        Node locDescNode = XMLHandler.getSubNodeByNr(locDescsNode, Plugin.DESCRIPTION, j);
        String locale = XMLHandler.getTagAttribute(locDescNode, Plugin.LOCALE);
        String locDesc = XMLHandler.getNodeValue(locDescNode);

        if (!Const.isEmpty(locale) && !Const.isEmpty(locDesc)) {
            localizedDescriptions.put(locale.toLowerCase(), locDesc);
        }
    }

    // Localized tooltips
    //
    Node locTipsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_TOOLTIP);
    int nrLocTips = XMLHandler.countNodes(locTipsNode, Plugin.TOOLTIP);
    Map<String, String> localizedTooltips = new Hashtable<String, String>();
    for (int j = 0; j < nrLocTips; j++) {
        Node locTipNode = XMLHandler.getSubNodeByNr(locTipsNode, Plugin.TOOLTIP, j);
        String locale = XMLHandler.getTagAttribute(locTipNode, Plugin.LOCALE);
        String locTip = XMLHandler.getNodeValue(locTipNode);

        if (!Const.isEmpty(locale) && !Const.isEmpty(locTip)) {
            localizedTooltips.put(locale.toLowerCase(), locTip);
        }
    }

    Node libsnode = XMLHandler.getSubNode(plugin, Plugin.LIBRARIES);
    int nrlibs = XMLHandler.countNodes(libsnode, Plugin.LIBRARY);
    String jarfiles[] = new String[nrlibs];
    for (int j = 0; j < nrlibs; j++) {
        Node libnode = XMLHandler.getSubNodeByNr(libsnode, Plugin.LIBRARY, j);
        String jarfile = XMLHandler.getTagAttribute(libnode, Plugin.NAME);
        jarfiles[j] = parent.resolveFile(jarfile).getURL().getFile();
        // System.out.println("jar files=" + jarfiles[j]);
    }

    // convert to URL
    List<URL> classpath = new ArrayList<URL>();
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new FileSystemResourceLoader());
    for (int i = 0; i < jarfiles.length; i++) {
        try {
            Resource[] paths = resolver.getResources(jarfiles[i]);
            for (Resource path : paths) {
                classpath.add(path.getURL());
            }
        } catch (IOException e) {
            e.printStackTrace();
            continue;
        }
    }

    URL urls[] = classpath.toArray(new URL[classpath.size()]);

    URLClassLoader cl = new PDIClassLoader(urls, Thread.currentThread().getContextClassLoader());

    String iconFilename = parent.resolveFile(iconfile).getURL().getFile();

    Class<?> pluginClass = cl.loadClass(classname);

    // here we'll have to use some reflection in order to decide
    // which object we should instantiate!
    if (JobEntryInterface.class.isAssignableFrom(pluginClass)) {
        Set<JobPlugin> jps = (Set<JobPlugin>) this.plugins.get(Job.class);

        JobPlugin plg = new JobPlugin(Plugin.TYPE_PLUGIN, id, description, tooltip, parent.getName().getURI(),
                jarfiles, iconFilename, classname, category);
        plg.setClassLoader(cl);

        // Add localized information too...
        plg.setLocalizedCategories(localizedCategories);
        plg.setLocalizedDescriptions(localizedDescriptions);
        plg.setLocalizedTooltips(localizedTooltips);

        jps.add(plg);
    } else {
        String errorHelpFileFull = errorHelpfile;
        String path = parent.getName().getURI();
        if (!Const.isEmpty(errorHelpfile))
            errorHelpFileFull = (path == null) ? errorHelpfile : path + Const.FILE_SEPARATOR + errorHelpfile;

        StepPlugin sp = new StepPlugin(Plugin.TYPE_PLUGIN, new String[] { id }, description, tooltip, path,
                jarfiles, iconFilename, classname, category, errorHelpFileFull);

        // Add localized information too...
        sp.setLocalizedCategories(localizedCategories);
        sp.setLocalizedDescriptions(localizedDescriptions);
        sp.setLocalizedTooltips(localizedTooltips);

        Set<StepPlugin> sps = (Set<StepPlugin>) this.plugins.get(Step.class);
        sps.add(sp);
    }

}

From source file:org.wso2.carbon.micro.integrator.server.Main.java

private static void startEquinox() {
    /**/*from   w ww.ja v a  2 s .  c o  m*/
     * Launches Equinox OSGi framework by  invoking EclipseStarter.startup() method using reflection.
     * Creates a ChildFirstClassLoader out of the OSGi framework jar and set the classloader as the framework
     * classloader.
     */
    URLClassLoader frameworkClassLoader = null;
    platformDirectory = Utils.getCarbonComponentRepo();
    if (platformDirectory == null) {
        throw new IllegalStateException("Could not start the Framework - (not deployed)");
    }

    if (frameworkClassLoader != null) {
        return;
    }

    final Map<String, String> initialPropsMap = buildInitialPropertyMap();
    String[] args2 = Utils.getArgs();

    ClassLoader original = Thread.currentThread().getContextClassLoader();
    try {
        System.setProperty("osgi.framework.useSystemProperties", "false");

        frameworkClassLoader = java.security.AccessController
                .doPrivileged(new java.security.PrivilegedAction<URLClassLoader>() {
                    public URLClassLoader run() {
                        URLClassLoader cl = null;
                        try {
                            cl = new ChildFirstURLClassLoader(
                                    new URL[] { new URL(initialPropsMap.get(OSGI_FRAMEWORK)) }, null);
                        } catch (MalformedURLException e) {
                            log.error(e.getMessage(), e);
                        }
                        return cl;
                    }
                });

        //            frameworkClassLoader =

        //Loads EclipseStarter class.
        Class clazz = frameworkClassLoader.loadClass(STARTER);

        //Set the propertyMap by invoking setInitialProperties method.
        Method setInitialProperties = clazz.getMethod("setInitialProperties", Map.class);
        setInitialProperties.invoke(null, initialPropsMap);

        //Invokes the startup method with some arguments.
        Method runMethod = clazz.getMethod("startup", String[].class, Runnable.class);
        runMethod.invoke(null, args2, null);

    } catch (InvocationTargetException ite) {
        Throwable t = ite.getTargetException();
        if (t == null) {
            t = ite;
        }
        throw new RuntimeException(t.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    } finally {
        Thread.currentThread().setContextClassLoader(original);
    }
}

From source file:interactivespaces.workbench.project.test.IsolatedJavaTestRunner.java

/**
 * Run all JUnit tests.//from w  ww  .j  a  va  2s . c  o  m
 *
 * @param classLoader
 *          the classloader for loading test classes
 * @param testClassNames
 *          the names of the detected JUnit classes
 * @param log
 *          logger for the test run
 *
 * @return {@code true} if all tests succeeded
 */
private boolean runJunitTests(URLClassLoader classLoader, List<String> testClassNames, final Log log) {
    JUnitCore junit = new JUnitCore();

    junit.addListener(new RunListener() {
        @Override
        public void testFailure(Failure failure) throws Exception {
            reportFailure(failure, log);
        }

        @Override
        public void testAssumptionFailure(Failure failure) {
            reportFailure(failure, log);
        }
    });

    log.info("Starting JUnit tests");

    boolean allSucceeded = true;
    for (String testClassName : testClassNames) {
        try {
            Class<?> testClass = classLoader.loadClass(testClassName);
            Result result = junit.run(testClass);

            log.info(String.format("Ran %2d tests in %4dms: %d failed, %d ignored. (%s)", result.getRunCount(),
                    result.getRunTime(), result.getFailureCount(), result.getIgnoreCount(), testClassName));

            allSucceeded &= result.wasSuccessful();
        } catch (Exception e) {
            log.error(String.format("Error while running test class %s", testClassName), e);
        }
    }

    log.info("JUnit tests complete");

    return allSucceeded;
}

From source file:gdt.jgui.entity.procedure.JProcedurePanel.java

private String[] run() {
    try {/*from  ww  w . ja v  a  2s  . c o m*/
        File procedureJava = new File(entihome$ + "/" + entityKey$ + "/" + entityKey$ + ".java");
        if (!procedureJava.exists())
            createSource(entityKey$);
        else {
            FileInputStream fis = new FileInputStream(procedureJava);
            InputStreamReader ins = new InputStreamReader(fis, "UTF-8");
            BufferedReader rds = new BufferedReader(ins);
            String ss;
            StringBuffer sbs = new StringBuffer();
            while ((ss = rds.readLine()) != null) {
                sbs.append(ss + "\n");
            }
            rds.close();
            sourcePanel.setText(sbs.toString());
        }
        File procedureHome = new File(entihome$ + "/" + entityKey$);
        URL url = procedureHome.toURI().toURL();
        URL[] urls = new URL[] { url };
        ClassLoader parentLoader = JMainConsole.class.getClassLoader();
        URLClassLoader cl = new URLClassLoader(urls, parentLoader);
        Class<?> cls = cl.loadClass(entityKey$);
        Object obj = cls.newInstance();
        Method method = obj.getClass().getDeclaredMethod("run", JMainConsole.class, String.class,
                Integer.class);
        Integer dividerLocation = new Integer(splitPane.getDividerLocation());
        method.invoke(obj, console, entihome$, dividerLocation);
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
    }
    return null;
}

From source file:com.datatorrent.stram.client.StramAppLauncher.java

/**
 * Scan the application jar file entries for configuration classes.
 * This needs to occur in a class loader with access to the application dependencies.
 *///from  w  ww .j  av  a 2  s  . c o  m
private void findAppConfigClasses(List<String> classFileNames) {
    URLClassLoader cl = URLClassLoader
            .newInstance(launchDependencies.toArray(new URL[launchDependencies.size()]));
    for (final String classFileName : classFileNames) {
        final String className = classFileName.replace('/', '.').substring(0, classFileName.length() - 6);
        try {
            final Class<?> clazz = cl.loadClass(className);
            if (!Modifier.isAbstract(clazz.getModifiers())
                    && StreamingApplication.class.isAssignableFrom(clazz)) {
                final AppFactory appConfig = new AppFactory() {
                    @Override
                    public String getName() {
                        return classFileName;
                    }

                    @Override
                    public String getDisplayName() {
                        ApplicationAnnotation an = clazz.getAnnotation(ApplicationAnnotation.class);
                        if (an != null) {
                            return an.name();
                        } else {
                            return classFileName;
                        }
                    }

                    @Override
                    public LogicalPlan createApp(LogicalPlanConfiguration conf) {
                        // load class from current context class loader
                        Class<? extends StreamingApplication> c = StramUtils.classForName(className,
                                StreamingApplication.class);
                        StreamingApplication app = StramUtils.newInstance(c);
                        LogicalPlan dag = new LogicalPlan();
                        conf.prepareDAG(dag, app, getName());
                        return dag;
                    }

                };
                appResourceList.add(appConfig);
            }
        } catch (Throwable e) { // java.lang.NoClassDefFoundError
            LOG.error("Unable to load class: " + className + " " + e);
        }
    }
}

From source file:org.pentaho.di.core.plugins.BasePluginType.java

protected void registerPluginJars() throws KettlePluginException {
    List<JarFileAnnotationPlugin> jarFilePlugins = findAnnotatedClassFiles(pluginType.getName());
    for (JarFileAnnotationPlugin jarFilePlugin : jarFilePlugins) {

        URLClassLoader urlClassLoader = createUrlClassLoader(jarFilePlugin.getJarFile(),
                getClass().getClassLoader());

        try {/*from   ww  w.  j a v  a 2  s.co  m*/
            Class<?> clazz = urlClassLoader.loadClass(jarFilePlugin.getClassName());
            if (clazz == null) {
                throw new KettlePluginException("Unable to load class: " + jarFilePlugin.getClassName());
            }
            List<String> libraries = new ArrayList<String>();
            java.lang.annotation.Annotation annotation = null;
            try {
                annotation = clazz.getAnnotation(pluginType);

                String jarFilename = URLDecoder.decode(jarFilePlugin.getJarFile().getFile(), "UTF-8");
                libraries.add(jarFilename);
                FileObject fileObject = KettleVFS.getFileObject(jarFilename);
                FileObject parentFolder = fileObject.getParent();
                String parentFolderName = KettleVFS.getFilename(parentFolder);
                String libFolderName = null;
                if (parentFolderName.endsWith(Const.FILE_SEPARATOR + "lib")) {
                    libFolderName = parentFolderName;
                } else {
                    libFolderName = parentFolderName + Const.FILE_SEPARATOR + "lib";
                }

                PluginFolder folder = new PluginFolder(libFolderName, false, false, searchLibDir);
                FileObject[] jarFiles = folder.findJarFiles(true);

                if (jarFiles != null) {
                    for (FileObject jarFile : jarFiles) {

                        String fileName = KettleVFS.getFilename(jarFile);

                        // If the plugin is in the lib folder itself, we'll ignore it here
                        if (fileObject.equals(jarFile)) {
                            continue;
                        }
                        libraries.add(fileName);
                    }
                }
            } catch (Exception e) {
                throw new KettlePluginException(
                        "Unexpected error loading class " + clazz.getName() + " of plugin type: " + pluginType,
                        e);
            }

            handlePluginAnnotation(clazz, annotation, libraries, false, jarFilePlugin.getPluginFolder());
        } catch (Exception e) {
            // Ignore for now, don't know if it's even possible.
            LogChannel.GENERAL
                    .logError("Unexpected error registering jar plugin file: " + jarFilePlugin.getJarFile(), e);
        } finally {
            if (urlClassLoader != null && urlClassLoader instanceof KettleURLClassLoader) {
                ((KettleURLClassLoader) urlClassLoader).closeClassLoader();
            }
        }
    }
}

From source file:com.kotcrab.vis.editor.module.editor.PluginLoaderModule.java

private void loadJarClasses(URLClassLoader classLoader, PluginDescriptor descriptor,
        Enumeration<JarEntry> entries) throws ClassNotFoundException {
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.isDirectory() || entry.getName().endsWith(".class") == false)
            continue;

        String className = entry.getName().substring(0, entry.getName().length() - ".class".length());
        className = className.replace('/', '.');
        Class<?> clazz = classLoader.loadClass(className);

        if (clazz.getAnnotation(VisPlugin.class) != null)
            descriptor.pluginClasses.add(clazz);
    }/* ww w .ja v a2 s.c o m*/
}

From source file:org.apache.zeppelin.interpreter.InterpreterFactory.java

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

    ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
    try {/*from w  w  w .j  a va2  s  .  c om*/

        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) {
            logger.error("exception checking server classloader driver", e);
        }

        URLClassLoader cl;

        if (separateCL == true) {
            cl = URLClassLoader.newInstance(new URL[] {}, ccl);
        } else {
            cl = 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);
        repl.setClassloaderUrls(ccl.getURLs());
        LazyOpenInterpreter intp = new LazyOpenInterpreter(new ClassloaderInterpreter(repl, cl));
        return intp;
    } 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);
    }
}