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:com.asakusafw.directio.hive.tools.cli.GenerateCreateTable.java

/**
 * Creates a class loader for loading plug-ins.
 * @param parent parent class loader, or {@code null} to use the system class loader
 * @param files plug-in class paths (*.jar file or class path directory)
 * @return the created class loader/* ww  w .  j a  v a2s  .  c o m*/
 * @throws IllegalArgumentException if some parameters were {@code null}
 */
private static URLClassLoader buildPluginLoader(ClassLoader parent, List<File> files) {
    if (files == null) {
        throw new IllegalArgumentException("files must not be null"); //$NON-NLS-1$
    }
    List<URL> locations = new ArrayList<>();
    for (File file : files) {
        try {
            if (file.exists() == false) {
                throw new FileNotFoundException(
                        MessageFormat.format(Messages.getString("GenerateCreateTable.errorMissingPluginFile"), //$NON-NLS-1$
                                file.getAbsolutePath()));
            }
            URL url = file.toURI().toURL();
            locations.add(url);
        } catch (IOException e) {
            LOG.warn(MessageFormat.format(Messages.getString("GenerateCreateTable.warnInvalidPluginFile"), //$NON-NLS-1$
                    file.getAbsolutePath()), e);
        }
    }
    return AccessController.doPrivileged((PrivilegedAction<URLClassLoader>) () -> new URLClassLoader(
            locations.toArray(new URL[locations.size()]), parent));
}

From source file:com.alibaba.rocketmq.filtersrv.filter.DynaCode.java

private void loadClass(Set<String> classFullNames) throws ClassNotFoundException, MalformedURLException {
    synchronized (loadClass) {
        ClassLoader classLoader = new URLClassLoader(new URL[] { new File(outPutClassPath).toURI().toURL() },
                parentClassLoader);//from ww  w  . j av  a2 s.com
        for (String key : classFullNames) {
            Class<?> classz = classLoader.loadClass(key);
            if (null != classz) {
                loadClass.put(key, classz);
                logger.info("Dyna Load Java Class File OK:----> className: " + key);
            } else {
                logger.error("Dyna Load Java Class File Fail:----> className: " + key);
            }
        }
    }
}

From source file:com.github.sakserv.minicluster.yarn.InJvmContainerExecutor.java

/**
 * Will launch containers within the same JVM as this Container Executor. It
 * will do so by: - extracting Container's class name and program arguments
 * from the launch script (e.g., launch_container.sh) - Creating an isolated
 * ClassLoader for each container - Calling doLaunchContainer(..) method to
 * launch Container/*from  w  w  w .j  av  a2s  .  c  om*/
 */
private int doLaunch(Container container, Path containerWorkDir) throws Exception {
    Map<String, String> environment = container.getLaunchContext().getEnvironment();
    EnvironmentUtils.putAll(environment);

    Set<URL> additionalClassPathUrls = this.filterAndBuildUserClasspath(container);

    ExecJavaCliParser javaCliParser = this.createExecCommandParser(containerWorkDir.toString());

    UserGroupInformation.setLoginUser(null);
    try {
        // create Isolated Class Loader for each container and set it as context
        // class loader
        URLClassLoader containerCl = new URLClassLoader(
                additionalClassPathUrls.toArray(additionalClassPathUrls.toArray(new URL[] {})), null);
        Thread.currentThread().setContextClassLoader(containerCl);
        String containerLauncher = javaCliParser.getMain();

        Class<?> containerClass = Class.forName(containerLauncher, true, containerCl);
        Method mainMethod = containerClass.getMethod("main", new Class[] { String[].class });
        mainMethod.setAccessible(true);
        String[] arguments = javaCliParser.getMainArguments();

        this.doLaunchContainer(containerClass, mainMethod, arguments);

    } catch (Exception e) {
        logger.error("Failed to launch container " + container, e);
        container.handle(new ContainerDiagnosticsUpdateEvent(container.getContainerId(), e.getMessage()));
        return -1;
    } finally {
        logger.info("Removing symlinks");
        this.cleanUp();
    }
    return 0;
}

From source file:com.cloudbees.sdk.ArtifactInstallFactory.java

/**
 * Creates a classloader from all the artifacts resolved thus far.
 *//*from  w  ww. j a  v a2s  .c  o m*/
private ClassLoader createClassLoader(List<URL> urls, ClassLoader parent) {
    // if (urls.isEmpty()) return parent;  // nothing to load // this makes it hard to differentiate newly loaded stuff from what's already visible
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
}

From source file:org.apache.hama.util.GenericOptionsParser.java

/**
 * Modify configuration according user-specified generic options
 * // w  w  w. j av  a 2s.  c o  m
 * @param conf Configuration to be modified
 * @param line User-specified generic options
 */
private void processGeneralOptions(HamaConfiguration conf, CommandLine line) throws IOException {

    if (line.hasOption("conf")) {
        String[] values = line.getOptionValues("conf");
        for (String value : values) {
            conf.addResource(new Path(value));
        }
    }
    if (line.hasOption("libjars")) {
        conf.set("tmpjars", validateFiles(line.getOptionValue("libjars"), conf));
        // setting libjars in client classpath
        URL[] libjars = getLibJars(conf);
        if (libjars != null && libjars.length > 0) {
            conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));
            Thread.currentThread().setContextClassLoader(
                    new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader()));
        }
    }
    if (line.hasOption("files")) {
        conf.set("tmpfiles", validateFiles(line.getOptionValue("files"), conf));
    }
    if (line.hasOption("archives")) {
        conf.set("tmparchives", validateFiles(line.getOptionValue("archives"), conf));
    }
    if (line.hasOption('D')) {
        String[] property = line.getOptionValues('D');
        for (String prop : property) {
            String[] keyval = prop.split("=", 2);
            if (keyval.length == 2) {
                conf.set(keyval[0], keyval[1]);
            }
        }
    }

    conf.setBoolean("hama.used.genericoptionsparser", true);

    // tokensFile
    if (line.hasOption("tokenCacheFile")) {
        String fileName = line.getOptionValue("tokenCacheFile");
        // check if the local file exists
        try {
            FileSystem localFs = FileSystem.getLocal(conf);
            Path p = new Path(fileName);
            if (!localFs.exists(p)) {
                throw new FileNotFoundException("File " + fileName + " does not exist.");
            }

            LOG.debug("setting conf tokensFile: " + fileName);
            conf.set("hama.job.credentials.json", localFs.makeQualified(p).toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.moss.nomad.core.packager.Packager.java

private MigrationResources createMigrationResources(MigrationDef def) throws Exception {

    ResolvedMigrationInfo info = resolver.resolve(def);

    /*//ww w .  j  av a2 s  .c  om
     * Determine the classpath for this migration package.
     */

    List<ResolvedDependencyInfo> dependencyArtifacts = new ArrayList<ResolvedDependencyInfo>();
    dependencyArtifacts.add(new ResolvedDependencyInfo(def.groupId(), def.artifactId(), def.version(),
            def.type(), def.classifier(), info.migrationArtifact()));
    dependencyArtifacts.addAll(info.dependencyArtifacts());

    List<String> handlerClassPath = new ArrayList<String>();
    for (ResolvedDependencyInfo dep : dependencyArtifacts) {

        StringBuilder sb = new StringBuilder();
        sb.append(dep.groupId());
        sb.append("/").append(dep.artifactId());
        sb.append("/").append(dep.version());
        sb.append("/").append(dep.artifactId());

        if (dep.classifier() != null) {
            sb.append("-").append(dep.classifier());
        }

        sb.append("-").append(dep.version());
        sb.append(".").append(dep.type());

        String pathName = sb.toString();

        handlerClassPath.add(pathName);

        if (!dependencies.containsKey(pathName)) {
            dependencies.put(pathName, dep);
        }
    }

    /*
     * Determine which class is the migration handler. There can only be
     * one, any other case will cause an exception to be thrown.
     */

    URL[] cp;
    {
        List<URL> urls = new ArrayList<URL>();

        urls.add(info.migrationArtifact().toURL());

        for (ResolvedDependencyInfo d : dependencyArtifacts) {
            urls.add(d.file().toURL());
        }

        cp = urls.toArray(new URL[0]);
    }

    ClassLoader cl = new URLClassLoader(cp, null);

    List<String> handlerClassNames = new ArrayList<String>();
    for (String jarPath : listJarPaths(info.migrationArtifact())) {

        if (!jarPath.endsWith(".class")) {
            continue;
        }

        String className = jarPath.replaceAll("\\/", ".").substring(0, jarPath.length() - 6);
        Class clazz = cl.loadClass(className);

        for (Class iface : clazz.getInterfaces()) {
            if (iface.getName().equals(MigrationHandler.class.getName())) {
                handlerClassNames.add(className);
                break;
            }
        }
    }

    String handlerClassName;
    if (handlerClassNames.isEmpty()) {

        StringBuilder sb = new StringBuilder();
        sb.append("Could not find an implementation of ");
        sb.append(MigrationHandler.class.getName());
        sb.append(" in migration def jar ");
        sb.append(def.toString());
        sb.append(": there must be exactly one.\n");

        throw new RuntimeException(sb.toString());
    } else if (handlerClassNames.size() > 1) {

        StringBuilder sb = new StringBuilder();
        sb.append("Found more than one implementation of ");
        sb.append(MigrationHandler.class.getName());
        sb.append(" in migration def jar ");
        sb.append(def.toString());
        sb.append(": there must be exactly one.\n");

        for (String n : handlerClassNames) {
            sb.append("    --> ").append(n).append("\n");
        }

        throw new RuntimeException(sb.toString());
    } else {
        handlerClassName = handlerClassNames.get(0);
    }

    return new MigrationResources(handlerClassName, handlerClassPath);
}

From source file:org.apache.sysml.runtime.codegen.CodegenUtils.java

private static Class<?> loadFromClassFile(String name, byte[] classBytes) {
    if (classBytes != null) {
        //load from byte representation of class file
        try (ByteClassLoader byteLoader = new ByteClassLoader(new URL[] {}, CodegenUtils.class.getClassLoader(),
                classBytes)) {/*from ww w  .jav  a2  s .  co  m*/
            return byteLoader.findClass(name);
        } catch (Exception e) {
            throw new DMLRuntimeException(e);
        }
    } else {
        //load compiled class file
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        try (URLClassLoader classLoader = new URLClassLoader(
                new URL[] { new File(_workingDir).toURI().toURL(), runDir },
                CodegenUtils.class.getClassLoader())) {
            return classLoader.loadClass(name);
        } catch (Exception e) {
            throw new DMLRuntimeException(e);
        }
    }
}

From source file:org.overlord.gadgets.server.devsvr.GadgetDevServer.java

/**
 * @see org.overlord.commons.dev.server.DevServer#addModulesToJetty(org.overlord.commons.dev.server.DevServerEnvironment, org.eclipse.jetty.server.handler.ContextHandlerCollection)
 *//*from  ww w. ja  v  a 2s.c o m*/
@Override
protected void addModulesToJetty(DevServerEnvironment environment, ContextHandlerCollection handlers)
        throws Exception {
    URL[] clURLs = new URL[] {
            new File(environment.getModuleDir("gadget-server"), "WEB-INF/classes").toURI().toURL() };
    // Set up the classloader.
    ClassLoader cl = new URLClassLoader(clURLs, GadgetDevServer.class.getClassLoader());
    Thread.currentThread().setContextClassLoader(cl);

    /* *********
     * gadgets
     * ********* */
    ServletContextHandler gadgets = new ServletContextHandler(ServletContextHandler.SESSIONS);
    gadgets.setContextPath("/gadgets");
    gadgets.setResourceBase(environment.getModuleDir("gadgets").getCanonicalPath());
    // File resources
    ServletHolder resources = new ServletHolder(new DefaultServlet());
    resources.setInitParameter("dirAllowed", "true");
    resources.setInitParameter("pathInfoOnly", "false");
    gadgets.addServlet(resources, "/");

    /* *********
     * gadget-web
     * ********* */
    System.setProperty("shindig.host", "");
    System.setProperty("shindig.port", "");
    System.setProperty("aKey", "/shindig/gadgets/proxy?container=default&url=");
    ServletContextHandler gadgetWeb = new ServletContextHandler(ServletContextHandler.SESSIONS);
    gadgetWeb.setInitParameter("guice-modules", GUICE_MODULES);
    gadgetWeb.setInitParameter("resteasy.servlet.mapping.prefix", "/rs");
    gadgetWeb.setContextPath("/gadget-web");
    gadgetWeb.setWelcomeFiles(new String[] { "Application.html" });
    //        gadgetServer.setResourceBase(environment.getModuleDir("gadget-server").getCanonicalPath());
    gadgetWeb.addEventListener(new GuiceServletContextListener());
    gadgetWeb.addEventListener(new ShindigResteasyBootstrapServletContextListener());
    // JSONP filter
    gadgetWeb.addFilter(JSONPFilter.class, "/rs/*", EnumSet.of(DispatcherType.REQUEST));
    // HostFilter
    gadgetWeb.addFilter(HostFilter.class, "/gadgets/ifr", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(HostFilter.class, "/gadgets/js/*", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(HostFilter.class, "/gadgets/proxy/*", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(HostFilter.class, "/gadgets/concat", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(HostFilter.class, "/gadgets/makeRequest", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(HostFilter.class, "/rpc/*", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(HostFilter.class, "/rest/*", EnumSet.of(DispatcherType.REQUEST));
    // ShiroFilter
    FilterHolder shiroFilter = new FilterHolder(IniShiroFilter.class);
    shiroFilter.setInitParameter("config", SHIRO_CONFIG);
    gadgetWeb.addFilter(shiroFilter, "/oauth/authorize", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(shiroFilter, "/oauth2/authorize", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(shiroFilter, "*.jsp", EnumSet.of(DispatcherType.REQUEST));
    // AuthFilter
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/gadgets/ifr", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/gadgets/js/*", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/gadgets/proxy/*",
            EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/gadgets/concat",
            EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/gadgets/makeRequest",
            EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/rpc/*", EnumSet.of(DispatcherType.REQUEST));
    gadgetWeb.addFilter(AuthenticationServletFilter.class, "/rest/*", EnumSet.of(DispatcherType.REQUEST));
    // EtagFilter
    gadgetWeb.addFilter(ETagFilter.class, "*", EnumSet.of(DispatcherType.REQUEST));
    // Servlets
    gadgetWeb.addServlet(GadgetRenderingServlet.class, "/gadgets/ifr");
    gadgetWeb.addServlet(HtmlAccelServlet.class, "/gadgets/accel");
    gadgetWeb.addServlet(ProxyServlet.class, "/gadgets/proxy/*");
    gadgetWeb.addServlet(MakeRequestServlet.class, "/gadgets/makeRequest");
    gadgetWeb.addServlet(ConcatProxyServlet.class, "/gadgets/concat");
    gadgetWeb.addServlet(OAuthCallbackServlet.class, "/gadgets/oauthcallback");
    gadgetWeb.addServlet(OAuth2CallbackServlet.class, "/gadgets/oauth2callback");
    gadgetWeb.addServlet(RpcServlet.class, "/gadgets/metadata");
    gadgetWeb.addServlet(JsServlet.class, "/gadgets/js/*");
    ServletHolder servletHolder = new ServletHolder(DataServiceServlet.class);
    servletHolder.setInitParameter("handlers", "org.apache.shindig.handlers");
    gadgetWeb.addServlet(servletHolder, "/rest/*");
    gadgetWeb.addServlet(servletHolder, "/gadgets/api/rest/*");
    gadgetWeb.addServlet(servletHolder, "/social/rest/*");
    servletHolder = new ServletHolder(JsonRpcServlet.class);
    servletHolder.setInitParameter("handlers", "org.apache.shindig.handlers");
    gadgetWeb.addServlet(servletHolder, "/rpc/*");
    gadgetWeb.addServlet(servletHolder, "/gadgets/api/rpc/*");
    gadgetWeb.addServlet(servletHolder, "/social/rpc/*");
    gadgetWeb.addServlet(SampleOAuthServlet.class, "/oauth/*");
    gadgetWeb.addServlet(OAuth2Servlet.class, "/oauth2/*");
    gadgetWeb.addServlet(RpcSwfServlet.class, "/xpc*");
    gadgetWeb.addServlet(HttpServletDispatcher.class, "/rs/*");
    // Service Overview REST service proxy servlet
    ServletHolder soProxyServlet = gadgetWeb.addServlet(RestProxyServlet.class, "/service/dependency/overview");
    soProxyServlet.setInitParameter("proxy-name", "service-overview");
    soProxyServlet.setInitParameter("proxy-url",
            "SCHEME://HOST:PORT/overlord-rtgov/service/dependency/overview");
    // Overlord Header JS servlet
    ServletHolder overlordHeaderJS = new ServletHolder(OverlordHeaderDataJS.class);
    overlordHeaderJS.setInitParameter("app-id", "gadget-server");
    gadgetWeb.addServlet(overlordHeaderJS, "/js/overlord-header-data.js");
    // File resources
    resources = new ServletHolder(new MultiDefaultServlet());
    resources.setInitParameter("resourceBase", "/");
    resources.setInitParameter("resourceBases",
            environment.getModuleDir("gadget-web").getCanonicalPath() + "|"
                    + environment.getModuleDir("gadget-server").getCanonicalPath() + "|"
                    + environment.getModuleDir("overlord-commons-uiheader").getCanonicalPath());
    resources.setInitParameter("dirAllowed", "true");
    resources.setInitParameter("pathInfoOnly", "false");
    gadgetWeb.addServlet(resources, "/");
    gadgetWeb.setSecurityHandler(createSecurityHandler());

    /* *********
     * rtgov mock
     * ********* */
    ServletContextHandler rtgov = new ServletContextHandler(ServletContextHandler.SESSIONS);
    rtgov.setContextPath("/overlord-rtgov");
    rtgov.setResourceBase(environment.getModuleDir("gadgets").getCanonicalPath());
    rtgov.addServlet(OverlordRTGovMockServlet.class, "/");
    rtgov.setSecurityHandler(createRtGovSecurityHandler());

    // Add the web contexts to jetty
    handlers.addHandler(gadgets);
    handlers.addHandler(gadgetWeb);
    handlers.addHandler(rtgov);
}

From source file:com.googlecode.flyway.commandline.Main.java

/**
 * Adds a jar or a directory with this name to the classpath.
 *
 * @param name The name of the jar or directory to add.
 * @throws IOException when the jar or directory could not be found.
 *///from w  ww .j  a v a  2s  .c o m
/* private -> for testing */
static void addJarOrDirectoryToClasspath(String name) throws Exception {
    LOG.debug("Adding location to classpath: " + name);

    // Add the jar or dir to the classpath
    // Chain the current thread classloader
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File(name).toURI().toURL() },
            Thread.currentThread().getContextClassLoader());

    // Replace the thread classloader - assumes
    // you have permissions to do so
    Thread.currentThread().setContextClassLoader(urlClassLoader);
}