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.apache.hama.bsp.BSPPeerImpl.java

@SuppressWarnings("unchecked")
public final void initializeIO() throws Exception {

    if (conf.get(Constants.JOB_INPUT_DIR) != null) {
        initInput();// w w w . ja  va2s.  c o m
    }

    String outdir = null;
    if (conf.get(Constants.JOB_OUTPUT_DIR) != null) {
        Path outputDir = new Path(conf.get(Constants.JOB_OUTPUT_DIR, "tmp-" + System.currentTimeMillis()),
                Task.getOutputName(partition));
        outdir = outputDir.makeQualified(fs).toString();
    }
    outWriter = bspJob.getOutputFormat().getRecordWriter(fs, bspJob, outdir);
    final RecordWriter<K2, V2> finalOut = outWriter;

    collector = new OutputCollector<K2, V2>() {
        @Override
        public void collect(K2 key, V2 value) throws IOException {
            finalOut.write(key, value);
        }
    };

    /* Move Files to HDFS */
    try {
        DistributedCacheUtil.moveLocalFiles(this.conf);
    } catch (Exception e) {
        LOG.error(e);
    }

    /* Add additional jars to Classpath */
    // LOG.info("conf.get(tmpjars): " + this.conf.get("tmpjars"));
    URL[] libjars = DistributedCacheUtil.addJarsToJobClasspath(this.conf);

    // ATTENTION bspJob.getConf() != this.conf
    if (libjars != null)
        bspJob.conf.setClassLoader(new URLClassLoader(libjars, bspJob.conf.getClassLoader()));
}

From source file:com.dspot.declex.action.Actions.java

private void createInformationForAction(String actionHolder, boolean isExternal) {

    TypeElement typeElement = env.getProcessingEnvironment().getElementUtils().getTypeElement(actionHolder);
    TypeElement generatedHolder = env.getProcessingEnvironment().getElementUtils()
            .getTypeElement(TypeUtils.getGeneratedClassName(typeElement, env));

    ActionFor actionForAnnotation = null;
    try {//from w w w . j ava 2  s .c o  m
        actionForAnnotation = typeElement.getAnnotation(ActionFor.class);
    } catch (Exception e) {
        LOGGER.error("An error occurred processing the @ActionFor annotation", e);
    }

    if (actionForAnnotation != null) {

        for (String name : actionForAnnotation.value()) {

            ACTION_HOLDER_ELEMENT_FOR_ACTION.put("$" + name, typeElement);

            //Get model info
            final ActionInfo actionInfo = new ActionInfo(actionHolder);
            actionInfo.isGlobal = actionForAnnotation.global();
            actionInfo.isTimeConsuming = actionForAnnotation.timeConsuming();

            if (isExternal) {
                actionInfo.generated = false;
            }

            //This will work only for cached classes
            if (generatedHolder != null) {
                for (Element elem : generatedHolder.getEnclosedElements()) {
                    if (elem instanceof ExecutableElement) {
                        final String elemName = elem.getSimpleName().toString();
                        final List<? extends VariableElement> params = ((ExecutableElement) elem)
                                .getParameters();

                        if (elemName.equals("onViewChanged") && params.size() == 1 && params.get(0).asType()
                                .toString().equals(HasViews.class.getCanonicalName())) {
                            actionInfo.handleViewChanges = true;
                            break;
                        }
                    }
                }
            }

            addAction(name, actionHolder, actionInfo, false);

            String javaDoc = env.getProcessingEnvironment().getElementUtils().getDocComment(typeElement);
            actionInfo.setReferences(javaDoc);

            List<DeclaredType> processors = annotationHelper.extractAnnotationClassArrayParameter(typeElement,
                    ActionFor.class.getCanonicalName(), "processors");

            //Load processors
            if (processors != null) {
                for (DeclaredType processor : processors) {

                    Class<ActionProcessor> processorClass = null;

                    try {

                        ClassLoader loader = classLoaderForProcessor.get(processor.toString());
                        if (loader != null) {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(), true,
                                    loader);
                        } else {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString());
                        }

                    } catch (ClassNotFoundException e) {

                        Element element = env.getProcessingEnvironment().getElementUtils()
                                .getTypeElement(processor.toString());
                        if (element == null) {
                            LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded",
                                    typeElement);
                        } else {

                            try {
                                //Get the file from which the class was loaded
                                java.lang.reflect.Field field = element.getClass().getField("classfile");
                                field.setAccessible(true);
                                JavaFileObject classfile = (JavaFileObject) field.get(element);

                                String jarUrl = classfile.toUri().toURL().toString();
                                jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('!') + 2);

                                //Create or use a previous created class loader for the given file
                                ClassLoader loader;
                                if (classLoaderForProcessor.containsKey(jarUrl)) {
                                    loader = classLoaderForProcessor.get(jarUrl);
                                } else {
                                    loader = new URLClassLoader(new URL[] { new URL(jarUrl) },
                                            Actions.class.getClassLoader());
                                    classLoaderForProcessor.put(processor.toString(), loader);
                                    classLoaderForProcessor.put(jarUrl, loader);
                                }

                                processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(),
                                        true, loader);

                            } catch (Throwable e1) {
                                LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded: "
                                        + e1.getMessage(), typeElement);
                            }

                        }

                    } catch (ClassCastException e) {
                        LOGGER.error("Processor \"" + processor.toString() + "\" is not an Action Processor",
                                typeElement);
                    }

                    if (processorClass != null) {
                        try {
                            actionInfo.processors.add(processorClass.newInstance());
                        } catch (Throwable e) {
                            LOGGER.info("Processor \"" + processor.toString() + "\" couldn't be instantiated",
                                    typeElement);
                        }
                    }

                }
            }

            createInformationForMethods(typeElement, actionInfo);
        }

    }

}

From source file:org.ng200.openolympus.services.TestingService.java

private SolutionJudge compileSolution(final Solution solution, final SolutionJudge judge,
        final Properties properties) throws ExecutionException {
    if (this.dataProvider == null) {
        throw new IllegalStateException("Shared data provider is null!");
    }// w w w  .  ja  v  a  2 s  .c  o  m

    final Lock lock = solution.getTask().readLock();
    lock.lock();

    try {
        TestingService.logger.info("Scheduling solution {} for compilation.", solution.getId());

        final JPPFJob job = new JPPFJob();
        job.setDataProvider(this.dataProvider);

        job.setName("Compile solution " + solution.getId());

        job.getSLA().setMaxNodes(1);
        job.getSLA().setPriority((int) (Integer.MAX_VALUE - solution.getId()));
        job.getSLA().setDispatchExpirationSchedule(new JPPFSchedule(20000L));
        job.getSLA().setMaxDispatchExpirations(5);

        TaskContainer taskContainer = taskContainerCache.getTaskContainerForTask(solution.getTask());

        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(taskContainer.getClassLoaderURLs().toArray(new URL[0]),
                        Thread.currentThread().getContextClassLoader()));
        job.add(new JacksonSerializationDelegatingTask<>(new SolutionCompilationTask(judge,
                Lists.from(storageService.getSolutionFile(solution)), properties),
                taskContainer.getClassLoaderURLs()));

        job.setBlocking(false);

        jppfClient.registerClassLoader(taskContainer.getClassLoader(), job.getUuid());
        this.jppfClient.submitJob(job);
        final JsonTaskExecutionResult<SolutionJudge> result = ((JacksonSerializationDelegatingTask<SolutionJudge, SolutionCompilationTask>) job
                .awaitResults().get(0)).getResultOrThrowable();

        if (result.getError() != null) {
            throw result.getError();
        }

        return result.getResult();

    } catch (final Throwable throwable) {
        throw new RuntimeException("Couldn't compile solution: ", throwable);
    } finally {
        lock.unlock();
    }
}

From source file:de.erdesignerng.util.ApplicationPreferences.java

public ClassLoader createDriverClassLoader() {

    final URL[] theUrls = new URL[classpathfiles.size()];
    for (int i = 0; i < classpathfiles.size(); i++) {
        try {/*from   w  w w. j  av a 2  s  . c o m*/
            theUrls[i] = classpathfiles.get(i).toURI().toURL();
        } catch (MalformedURLException e) {
            // This will never happen
        }
    }

    return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(theUrls,
            Thread.currentThread().getContextClassLoader()));
}

From source file:org.apache.cxf.maven_plugin.wadlto.AbstractCodeGeneratorMojo.java

private ClassLoader getResourceLoader() throws MojoExecutionException {
    if (resourceClassLoader == null) {
        try {// ww w. ja va2s  . c  o m
            List<?> runtimeClasspathElements = project.getRuntimeClasspathElements();
            List<?> resources = project.getResources();
            List<?> testResources = project.getTestResources();
            URL[] runtimeUrls = new URL[runtimeClasspathElements.size() + resources.size()
                    + testResources.size()];
            for (int i = 0; i < runtimeClasspathElements.size(); i++) {
                String element = (String) runtimeClasspathElements.get(i);
                runtimeUrls[i] = new File(element).toURI().toURL();
            }
            for (int i = 0, j = runtimeClasspathElements.size(); i < resources.size(); i++, j++) {
                Resource r = (Resource) resources.get(i);
                runtimeUrls[j] = new File(r.getDirectory()).toURI().toURL();
            }
            for (int i = 0, j = runtimeClasspathElements.size() + resources.size(); i < testResources
                    .size(); i++, j++) {
                Resource r = (Resource) testResources.get(i);
                runtimeUrls[j] = new File(r.getDirectory()).toURI().toURL();
            }
            resourceClassLoader = new URLClassLoader(runtimeUrls,
                    Thread.currentThread().getContextClassLoader());
        } catch (Exception e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
    return resourceClassLoader;
}

From source file:org.apache.ranger.biz.ServiceMgr.java

@SuppressWarnings("unchecked")
private Class<RangerBaseService> getClassForServiceType(RangerServiceDef serviceDef) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceMgr.getClassForServiceType(" + serviceDef + ")");
    }/*  w  w w. j a  v a2 s. c o m*/

    Class<RangerBaseService> ret = null;

    if (serviceDef != null) {
        String serviceType = serviceDef.getName();

        ret = serviceTypeClassMap.get(serviceType);

        if (ret == null) {
            synchronized (serviceTypeClassMap) {
                ret = serviceTypeClassMap.get(serviceType);

                if (ret == null) {
                    String clsName = serviceDef.getImplClass();

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class "
                                + clsName + " not found in cache");
                    }

                    URL[] pluginFiles = getPluginFilesForServiceType(serviceType);
                    URLClassLoader clsLoader = new URLClassLoader(pluginFiles,
                            Thread.currentThread().getContextClassLoader());

                    try {
                        Class<?> cls = Class.forName(clsName, true, clsLoader);

                        ret = (Class<RangerBaseService>) cls;

                        serviceTypeClassMap.put(serviceType, ret);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class "
                                    + clsName + " added to cache");
                        }
                    } catch (Exception excp) {
                        LOG.warn("ServiceMgr.getClassForServiceType(" + serviceType
                                + "): failed to find service-class '" + clsName
                                + "'. Resource lookup will not be available", excp);
                        //Let's propagate the error
                        throw new Exception(serviceType + " failed to find service class " + clsName
                                + ". Resource lookup will not be available. Please make sure plugin jar is in the correct place.");
                    }
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class "
                                + ret.getCanonicalName() + " found in cache");
                    }
                }
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class "
                        + ret.getCanonicalName() + " found in cache");
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceMgr.getClassForServiceType(" + serviceDef + "): " + ret);
    }

    return ret;
}

From source file:io.fabric8.ConnectorMojo.java

/**
 * Finds and embeds the Camel component JSon schema file
 *///from   w ww .j a  va2s  .  c om
private File embedCamelComponentSchema(File file) throws MojoExecutionException {
    try {
        List<String> json = loadFile(file);

        String scheme = extractScheme(json);
        String groupId = extractGroupId(json);
        String artifactId = extractArtifactId(json);
        String version = extractVersion(json); // version not in use

        // find the artifact on the classpath that has the Camel component this connector is using
        // then we want to grab its json schema file to embed in this JAR so we have all files together

        if (scheme != null && groupId != null && artifactId != null) {
            for (Artifact artifact : getProject().getDependencyArtifacts()) {
                if ("jar".equals(artifact.getType())) {
                    if (groupId.equals(artifact.getGroupId()) && artifactId.equals(artifact.getArtifactId())) {
                        // load the component file inside the file
                        URL url = new URL("file:" + artifact.getFile());
                        URLClassLoader child = new URLClassLoader(new URL[] { url },
                                this.getClass().getClassLoader());

                        InputStream is = child
                                .getResourceAsStream("META-INF/services/org/apache/camel/component/" + scheme);
                        if (is != null) {
                            List<String> lines = loadFile(is);
                            String fqn = extractClass(lines);
                            is.close();

                            // only keep package
                            String pck = fqn.substring(0, fqn.lastIndexOf("."));
                            String name = pck.replace(".", "/") + "/" + scheme + ".json";

                            is = child.getResourceAsStream(name);
                            if (is != null) {
                                List<String> schema = loadFile(is);
                                is.close();

                                // write schema to file
                                File out = new File(classesDirectory, "camel-component-schema.json");
                                FileOutputStream fos = new FileOutputStream(out, false);
                                for (String line : schema) {
                                    fos.write(line.getBytes());
                                    fos.write("\n".getBytes());
                                }
                                fos.close();

                                getLog().info("Embedded camel-component-schema.json file for Camel component "
                                        + scheme);

                                return out;
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new MojoExecutionException("Cannot read file camel-connector.json", e);
    }

    return null;
}

From source file:org.apache.nifi.registry.jetty.JettyServer.java

private WebAppContext loadWar(final File warFile, final String contextPath, final URL[] additionalResources)
        throws IOException {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);

    // get the temp directory for this webapp
    final File webWorkingDirectory = properties.getWebWorkingDirectory();
    final File tempDir = new File(webWorkingDirectory, warFile.getName());
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }/*from   w  w w. ja  v a 2s.c om*/
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    // start out assuming the system ClassLoader will be the parent, but if additional resources were specified then
    // inject a new ClassLoader in between the system and webapp ClassLoaders that contains the additional resources
    ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();
    if (additionalResources != null && additionalResources.length > 0) {
        URLClassLoader additionalClassLoader = new URLClassLoader(additionalResources,
                ClassLoader.getSystemClassLoader());
        parentClassLoader = additionalClassLoader;
    }

    webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}

From source file:com.zimbra.cs.zimlet.ZimletUtil.java

/**
 * Loads all the Zimlets, locates the server side ZimletHandler for each Zimlets,
 * loads the class and instantiate the object, then returns the instance.
 *
 * @param name of the Zimlet//  w w  w . j a  v a  2 s .  c  o  m
 * @return ZimletHandler object
 */
public static ZimletHandler getHandler(String name) {
    loadZimlets();
    Class zh = sZimletHandlers.get(name);
    if (zh == null) {
        ZimletFile zf = sZimlets.get(name);
        if (zf == null) {
            return null;
        }
        URLClassLoader cl = null;
        try {
            String clazz = zf.getZimletDescription().getServerExtensionClass();
            if (clazz != null) {
                URL[] urls = { zf.toURL() };
                cl = new URLClassLoader(urls, ZimletUtil.class.getClassLoader());
                zh = cl.loadClass(clazz);
                ZimbraLog.zimlet.info("Loaded class " + zh.getName());
                sZimletHandlers.put(name, zh);
            }
        } catch (Exception e) {
            ZimbraLog.zimlet.warn("Unable to load zimlet handler for %s", name, e);
            return null;
        } finally {
            if (cl != null) {
                try {
                    cl.close();
                } catch (IOException e) {
                    ZimbraLog.zimlet.warn("failed to close URLClassLoader", e);
                }
            }
        }
    }
    try {
        if (zh != null) {
            return (ZimletHandler) zh.newInstance();
        }
    } catch (Exception e) {
        ZimbraLog.zimlet.warn("Unable to instantiate zimlet handler for " + name, e);
    }
    return null;
}

From source file:psiprobe.AbstractTomcatContainer.java

@Override
public void listContextJsps(Context context, Summary summary, boolean compile) {
    ServletConfig servletConfig = (ServletConfig) context.findChild("jsp");
    if (servletConfig != null) {
        synchronized (servletConfig) {
            ServletContext sctx = context.getServletContext();
            Options opt = new EmbeddedServletOptions(servletConfig, sctx);

            JspRuntimeContext jrctx = new JspRuntimeContext(sctx, opt);
            try {
                if (summary.getItems() == null) {
                    summary.setItems(new HashMap<String, Item>());
                }/*from w w w . j  ava  2s  . com*/

                /*
                 * mark all items as missing
                 */
                for (Item item : summary.getItems().values()) {
                    item.setMissing(true);
                }

                /*
                 * we need to pass context classloader here, so the jsps can reference /WEB-INF/classes
                 * and /WEB-INF/lib. JspCompilationContext would only take URLClassLoader, so we fake it
                 */
                URLClassLoader urlcl = new URLClassLoader(new URL[0], context.getLoader().getClassLoader());

                compileItem("/", opt, context, jrctx, summary, urlcl, 0, compile);
            } finally {
                jrctx.destroy();
            }
        }

        //
        // delete "missing" items by keeping "not missing" ones
        //
        Map<String, Item> hashMap = new HashMap<>();
        for (String key : summary.getItems().keySet()) {
            Item item = summary.getItems().get(key);
            if (!item.isMissing()) {
                hashMap.put(key, item);
            }
        }

        summary.setItems(hashMap);
    } else {
        logger.error("Context '{}' does not have 'JSP' servlet", context.getName());
    }
}