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.jenkinsci.maven.plugins.hpi.AbstractHpiMojo.java

/**
 * Is the dynamic loading supported?/*from w w w .jav  a2  s  . c  o m*/
 *
 * False, if the answer is known to be "No". Otherwise null, if there are some extensions
 * we don't know we can dynamic load. Otherwise, if everything is known to be dynamic loadable, return true.
 */
protected Boolean isSupportDynamicLoading() throws IOException {
    URLClassLoader cl = new URLClassLoader(
            new URL[] { new File(project.getBuild().getOutputDirectory()).toURI().toURL() },
            getClass().getClassLoader());

    EnumSet<YesNoMaybe> e = EnumSet.noneOf(YesNoMaybe.class);
    for (IndexItem<Extension, Object> i : Index.load(Extension.class, Object.class, cl)) {
        e.add(i.annotation().dynamicLoadable());
    }

    if (e.contains(YesNoMaybe.NO))
        return false;
    if (e.contains(YesNoMaybe.MAYBE))
        return null;
    return true;
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Runs this application directly in the current VM.
 *//*from w w  w  .  jav a2 s.c om*/
public void invokeDirect(JApplet applet) throws IOException {
    ClassPath classPath = ClassPaths.buildClassPath(this);
    URL[] jarUrls = classPath.asUrls();

    // create custom class loader
    URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
        @Override
        protected PermissionCollection getPermissions(CodeSource code) {
            Permissions perms = new Permissions();
            perms.add(new AllPermission());
            return perms;
        }
    };
    Thread.currentThread().setContextClassLoader(loader);

    log.info("Configured URL class loader:");
    for (URL url : jarUrls)
        log.info("  " + url);

    // configure any system properties that we can
    for (String jvmarg : _jvmargs) {
        if (jvmarg.startsWith("-D")) {
            jvmarg = processArg(jvmarg.substring(2));
            int eqidx = jvmarg.indexOf("=");
            if (eqidx == -1) {
                log.warning("Bogus system property: '" + jvmarg + "'?");
            } else {
                System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx + 1));
            }
        }
    }

    // pass along any pass-through arguments
    Map<String, String> passProps = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
            key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
            passProps.put(key, (String) entry.getValue());
        }
    }
    // we can't set these in the above loop lest we get a ConcurrentModificationException
    for (Map.Entry<String, String> entry : passProps.entrySet()) {
        System.setProperty(entry.getKey(), entry.getValue());
    }

    // make a note that we're running in "applet" mode
    System.setProperty("applet", "true");

    // prepare our app arguments
    String[] args = new String[_appargs.size()];
    for (int ii = 0; ii < args.length; ii++)
        args[ii] = processArg(_appargs.get(ii));

    try {
        log.info("Loading " + _class);
        Class<?> appclass = loader.loadClass(_class);
        Method main;
        try {
            // first see if the class has a special applet-aware main
            main = appclass.getMethod("main", JApplet.class, SA_PROTO.getClass());
            log.info("Invoking main(JApplet, {" + StringUtil.join(args, ", ") + "})");
            main.invoke(null, new Object[] { applet, args });
        } catch (NoSuchMethodException nsme) {
            main = appclass.getMethod("main", SA_PROTO.getClass());
            log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
            main.invoke(null, new Object[] { args });
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:azkaban.webapp.AzkabanWebServer.java

private static void loadViewerPlugins(Context root, String pluginPath, VelocityEngine ve) {
    File viewerPluginPath = new File(pluginPath);
    if (!viewerPluginPath.exists()) {
        return;/* www .jav  a2  s. c  o  m*/
    }

    ClassLoader parentLoader = AzkabanWebServer.class.getClassLoader();
    File[] pluginDirs = viewerPluginPath.listFiles();
    ArrayList<String> jarPaths = new ArrayList<String>();
    for (File pluginDir : pluginDirs) {
        if (!pluginDir.exists()) {
            logger.error("Error viewer plugin path " + pluginDir.getPath() + " doesn't exist.");
            continue;
        }

        if (!pluginDir.isDirectory()) {
            logger.error("The plugin path " + pluginDir + " is not a directory.");
            continue;
        }

        // Load the conf directory
        File propertiesDir = new File(pluginDir, "conf");
        Props pluginProps = null;
        if (propertiesDir.exists() && propertiesDir.isDirectory()) {
            File propertiesFile = new File(propertiesDir, "plugin.properties");
            File propertiesOverrideFile = new File(propertiesDir, "override.properties");

            if (propertiesFile.exists()) {
                if (propertiesOverrideFile.exists()) {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile, propertiesOverrideFile);
                } else {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile);
                }
            } else {
                logger.error("Plugin conf file " + propertiesFile + " not found.");
                continue;
            }
        } else {
            logger.error("Plugin conf path " + propertiesDir + " not found.");
            continue;
        }

        String pluginName = pluginProps.getString("viewer.name");
        String pluginWebPath = pluginProps.getString("viewer.path");
        String pluginJobTypes = pluginProps.getString("viewer.jobtypes", null);
        int pluginOrder = pluginProps.getInt("viewer.order", 0);
        boolean pluginHidden = pluginProps.getBoolean("viewer.hidden", false);
        List<String> extLibClasspath = pluginProps.getStringList("viewer.external.classpaths",
                (List<String>) null);

        String pluginClass = pluginProps.getString("viewer.servlet.class");
        if (pluginClass == null) {
            logger.error("Viewer class is not set.");
        } else {
            logger.error("Plugin class " + pluginClass);
        }

        URLClassLoader urlClassLoader = null;
        File libDir = new File(pluginDir, "lib");
        if (libDir.exists() && libDir.isDirectory()) {
            File[] files = libDir.listFiles();

            ArrayList<URL> urls = new ArrayList<URL>();
            for (int i = 0; i < files.length; ++i) {
                try {
                    URL url = files[i].toURI().toURL();
                    urls.add(url);
                } catch (MalformedURLException e) {
                    logger.error(e);
                }
            }

            // Load any external libraries.
            if (extLibClasspath != null) {
                for (String extLib : extLibClasspath) {
                    File extLibFile = new File(pluginDir, extLib);
                    if (extLibFile.exists()) {
                        if (extLibFile.isDirectory()) {
                            // extLibFile is a directory; load all the files in the
                            // directory.
                            File[] extLibFiles = extLibFile.listFiles();
                            for (int i = 0; i < extLibFiles.length; ++i) {
                                try {
                                    URL url = extLibFiles[i].toURI().toURL();
                                    urls.add(url);
                                } catch (MalformedURLException e) {
                                    logger.error(e);
                                }
                            }
                        } else { // extLibFile is a file
                            try {
                                URL url = extLibFile.toURI().toURL();
                                urls.add(url);
                            } catch (MalformedURLException e) {
                                logger.error(e);
                            }
                        }
                    } else {
                        logger.error("External library path " + extLibFile.getAbsolutePath() + " not found.");
                        continue;
                    }
                }
            }

            urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader);
        } else {
            logger.error("Library path " + libDir.getAbsolutePath() + " not found.");
            continue;
        }

        Class<?> viewerClass = null;
        try {
            viewerClass = urlClassLoader.loadClass(pluginClass);
        } catch (ClassNotFoundException e) {
            logger.error("Class " + pluginClass + " not found.");
            continue;
        }

        String source = FileIOUtils.getSourcePathFromClass(viewerClass);
        logger.info("Source jar " + source);
        jarPaths.add("jar:file:" + source);

        Constructor<?> constructor = null;
        try {
            constructor = viewerClass.getConstructor(Props.class);
        } catch (NoSuchMethodException e) {
            logger.error("Constructor not found in " + pluginClass);
            continue;
        }

        Object obj = null;
        try {
            obj = constructor.newInstance(pluginProps);
        } catch (Exception e) {
            logger.error(e);
            logger.error(e.getCause());
        }

        if (!(obj instanceof AbstractAzkabanServlet)) {
            logger.error("The object is not an AbstractAzkabanServlet");
            continue;
        }

        AbstractAzkabanServlet avServlet = (AbstractAzkabanServlet) obj;
        root.addServlet(new ServletHolder(avServlet), "/" + pluginWebPath + "/*");
        PluginRegistry.getRegistry().register(
                new ViewerPlugin(pluginName, pluginWebPath, pluginOrder, pluginHidden, pluginJobTypes));
    }

    // Velocity needs the jar resource paths to be set.
    String jarResourcePath = StringUtils.join(jarPaths, ", ");
    logger.info("Setting jar resource path " + jarResourcePath);
    ve.addProperty("jar.resource.loader.path", jarResourcePath);
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private ClassLoader getClassLoader() {
    if (project != null) {
        try {/* w w w  .  j a  va  2 s .  c  o m*/
            List classpathElements = project.getCompileClasspathElements();
            classpathElements.add(project.getBuild().getOutputDirectory());
            classpathElements.add(project.getBuild().getTestOutputDirectory());
            URL[] urls = new URL[classpathElements.size()];
            for (int i = 0; i < classpathElements.size(); i++) {
                urls[i] = new File((String) classpathElements.get(i)).toURI().toURL();
            }
            return new URLClassLoader(urls, getClass().getClassLoader());
        } catch (Exception e) {
            getLog().error("Couldn't get the classloader.");
        }
    }
    return getClass().getClassLoader();
}

From source file:au.org.ala.delta.util.Utils.java

private static void launchIntkeyViaClassLoader(String inputFile) throws Exception {
    // Gah.... this is a horrible work around for the fact that
    // the swing application framework relies on a static
    // Application instance so we can't have the Editor and
    // Intkey playing together nicely in the same JVM.
    // It doesn't really work properly anyway, the swing application
    // framework generates exceptions during loading and saving
    // state due to failing instanceof checks.
    String classPath = System.getProperty("java.class.path");
    String[] path = classPath.split(File.pathSeparator);
    List<URL> urls = new ArrayList<URL>();
    for (String pathEntry : path) {
        urls.add(new File(pathEntry).toURI().toURL());
    }//from   w  w  w  . j a va 2  s .c o m
    ClassLoader intkeyLoader = new URLClassLoader(urls.toArray(new URL[0]),
            ClassLoader.getSystemClassLoader().getParent());
    Class<?> intkey = intkeyLoader.loadClass("au.org.ala.delta.intkey.Intkey");
    Method main = intkey.getMethod("main", String[].class);
    main.invoke(null, (Object) new String[] { inputFile });
}

From source file:org.apache.openejb.config.DeploymentLoader.java

public static void addBeansXmls(final WebModule webModule) {
    final List<URL> urls = webModule.getScannableUrls();
    // parent returns nothing when calling getresources because we don't want here to be fooled by maven classloader
    final URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
            new EmptyResourcesClassLoader());

    final List<URL> xmls = new LinkedList<>();
    try {/*from w ww  .j  a  v  a2 s.c  o  m*/
        final URL e = (URL) webModule.getAltDDs().get("beans.xml");
        if (e != null) { // first!
            xmls.add(e);
        }
        xmls.addAll(Collections.list(loader.getResources("META-INF/beans.xml")));
    } catch (final IOException e) {
        return;
    }

    final CompositeBeans complete = new CompositeBeans();
    for (final URL url : xmls) {
        if (url == null) {
            continue;
        }
        mergeBeansXml(complete, url);
    }
    if (!complete.getDiscoveryByUrl().isEmpty()) {
        complete.removeDuplicates();
        webModule.getAltDDs().put("beans.xml", complete);
    }
}

From source file:org.ow2.mind.unit.Launcher.java

/**
 * Inspired from org.ow2.mind.cli.SrcPathOptionHandler.
 * We extend the original ClassLoader by using it as a parent to a new ClassLoader.
 * Valid test folders are taken from this class urlList attribute.
 * We also extend the ClassLoader to the current jar in order to use local (hidden)
 * resources./*from  w  w w  .  ja  v a  2s  .c om*/
 */
protected void addTestFoldersToPath() {
    // get the --src-path elements
    URLClassLoader srcPathClassLoader = (URLClassLoader) SrcPathOptionHandler
            .getSourceClassLoader(compilerContext);

    // URL array of test path, replace the original source class-loader with our enriched one
    // and use the original source class-loader as parent so as to keep everything intact
    ClassLoader srcAndTestPathClassLoader = new URLClassLoader(urlList.toArray(new URL[0]), srcPathClassLoader);

    // replace the original source classloader with the new one in the context
    compilerContext.remove("classloader");
    compilerContext.put("classloader", srcAndTestPathClassLoader);
}

From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java

private ClassLoader createCompileClassLoader(MavenProject project) throws MavenReportException {
    Thread current = Thread.currentThread();
    ClassLoader cl = current.getContextClassLoader();

    try {//w w w .  java 2 s .  c  o  m
        List classpathElements = project.getCompileClasspathElements();
        if (!classpathElements.isEmpty()) {
            String[] entries = (String[]) classpathElements.toArray(new String[0]);
            URL[] urls = new URL[entries.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(entries[i]).toURL();
            }
            cl = new URLClassLoader(urls, cl);
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MavenReportException("Error calculating scope classpath", e);
    } catch (MalformedURLException e) {
        throw new MavenReportException("Error calculating scope classpath", e);
    }

    return cl;
}

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.//from w w w.ja  v a  2  s .c o  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:org.apache.lens.driver.jdbc.TestColumnarSQLRewriter.java

/**
 * Test replace db name.//from  w  w w.  j a v a2 s.c  o m
 *
 * @throws Exception the exception
 */
@Test
public void testReplaceDBName() throws Exception {
    File jarDir = new File("target/testjars");
    File testJarFile = new File(jarDir, "test.jar");
    File serdeJarFile = new File(jarDir, "serde.jar");

    URL[] serdeUrls = new URL[2];
    serdeUrls[0] = new URL("file:" + testJarFile.getAbsolutePath());
    serdeUrls[1] = new URL("file:" + serdeJarFile.getAbsolutePath());

    URLClassLoader createTableClassLoader = new URLClassLoader(serdeUrls, hconf.getClassLoader());
    ClassLoader loader = new URLClassLoader(serdeUrls, SessionState.getSessionConf().getClassLoader());
    SessionState.getSessionConf().setClassLoader(loader);

    // Create test table
    Database database = new Database();
    database.setName("mydb");

    try {
        Hive.get(hconf).createDatabase(database);
        SessionState.get().setCurrentDatabase("mydb");
        createTable(hconf, "mydb", "mytable", "testDB", "testTable_1");
        createTable(hconf, "mydb", "mytable_2", "testDB", "testTable_2");
        createTable(hconf, "default", "mytable_3", "testDB", "testTable_3");
    } catch (AlreadyExistsException e) {
        //pass
    }
    String query = "SELECT * FROM mydb.mytable t1 JOIN mytable_2 t2 ON t1.t2id = t2.id "
            + " left outer join default.mytable_3 t3 on t2.t3id = t3.id " + "WHERE A = 100";

    ColumnarSQLRewriter rewriter = new ColumnarSQLRewriter();
    rewriter.init(conf);
    rewriter.ast = HQLParser.parseHQL(query, hconf);
    rewriter.query = query;
    rewriter.analyzeInternal(conf, hconf);

    String joinTreeBeforeRewrite = HQLParser.getString(rewriter.fromAST);
    System.out.println(joinTreeBeforeRewrite);

    // Rewrite
    rewriter.replaceWithUnderlyingStorage(hconf);
    String joinTreeAfterRewrite = HQLParser.getString(rewriter.fromAST);
    System.out.println("joinTreeAfterRewrite:" + joinTreeAfterRewrite);

    // Tests
    assertTrue(joinTreeBeforeRewrite.contains("mydb"));
    assertTrue(joinTreeBeforeRewrite.contains("mytable") && joinTreeBeforeRewrite.contains("mytable_2")
            && joinTreeBeforeRewrite.contains("mytable_3"));

    assertFalse(joinTreeAfterRewrite.contains("mydb"));
    assertFalse(joinTreeAfterRewrite.contains("mytable") && joinTreeAfterRewrite.contains("mytable_2")
            && joinTreeAfterRewrite.contains("mytable_3"));

    assertTrue(joinTreeAfterRewrite.contains("testdb"));
    assertTrue(joinTreeAfterRewrite.contains("testtable_1") && joinTreeAfterRewrite.contains("testtable_2")
            && joinTreeAfterRewrite.contains("testtable_3"));

    // Rewrite one more query where table and db name is not set
    createTable(hconf, "mydb", "mytable_4", null, null);
    String query2 = "SELECT * FROM mydb.mytable_4 WHERE a = 100";
    rewriter.ast = HQLParser.parseHQL(query2, hconf);
    rewriter.query = query2;
    rewriter.analyzeInternal(conf, hconf);

    joinTreeBeforeRewrite = HQLParser.getString(rewriter.fromAST);
    System.out.println(joinTreeBeforeRewrite);

    // Rewrite
    rewriter.replaceWithUnderlyingStorage(hconf);
    joinTreeAfterRewrite = HQLParser.getString(rewriter.fromAST);
    System.out.println(joinTreeAfterRewrite);

    // Rewrite should not replace db and table name since its not set
    assertEquals(joinTreeAfterRewrite, joinTreeBeforeRewrite);

    // Test a query with default db
    Hive.get().dropTable("mydb", "mytable");
    database = new Database();
    database.setName("examples");
    Hive.get().createDatabase(database);
    createTable(hconf, "examples", "mytable", "default", null);

    String defaultQuery = "SELECT * FROM examples.mytable t1 WHERE A = 100";
    rewriter.ast = HQLParser.parseHQL(defaultQuery, hconf);
    rewriter.query = defaultQuery;
    rewriter.analyzeInternal(conf, hconf);
    joinTreeBeforeRewrite = HQLParser.getString(rewriter.fromAST);
    rewriter.replaceWithUnderlyingStorage(hconf);
    joinTreeAfterRewrite = HQLParser.getString(rewriter.fromAST);
    assertTrue(joinTreeBeforeRewrite.contains("examples"), joinTreeBeforeRewrite);
    assertFalse(joinTreeAfterRewrite.contains("examples"), joinTreeAfterRewrite);
    System.out.println("default case: " + joinTreeAfterRewrite);

    Hive.get().dropTable("examples", "mytable");
    Hive.get().dropTable("mydb", "mytable_2");
    Hive.get().dropTable("default", "mytable_3");
    Hive.get().dropTable("mydb", "mytable_4");
    Hive.get().dropDatabase("mydb", true, true, true);
    Hive.get().dropDatabase("examples", true, true, true);
    SessionState.get().setCurrentDatabase("default");
}