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.hurence.logisland.processor.elasticsearch.AbstractElasticsearchProcessor.java

protected TransportClient getTransportClient(Settings.Builder settingsBuilder, String shieldUrl,
        String username, String password) throws MalformedURLException {

    // Create new transport client using the Builder pattern
    TransportClient.Builder builder = TransportClient.builder();

    // See if the Elasticsearch Shield JAR location was specified, and add the plugin if so. Also create the
    // authorization token if username and password are supplied.
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    if (!StringUtils.isBlank(shieldUrl)) {
        ClassLoader shieldClassLoader = new URLClassLoader(new URL[] { new File(shieldUrl).toURI().toURL() },
                this.getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(shieldClassLoader);

        try {// w ww .j  a  v  a 2s  .com
            Class shieldPluginClass = Class.forName("org.elasticsearch.shield.ShieldPlugin", true,
                    shieldClassLoader);
            builder = builder.addPlugin(shieldPluginClass);

            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {

                // Need a couple of classes from the Shield plugin to build the token
                Class usernamePasswordTokenClass = Class.forName(
                        "org.elasticsearch.shield.authc.support.UsernamePasswordToken", true,
                        shieldClassLoader);

                Class securedStringClass = Class.forName("org.elasticsearch.shield.authc.support.SecuredString",
                        true, shieldClassLoader);

                Constructor<?> securedStringCtor = securedStringClass.getConstructor(char[].class);
                Object securePasswordString = securedStringCtor.newInstance(password.toCharArray());

                Method basicAuthHeaderValue = usernamePasswordTokenClass.getMethod("basicAuthHeaderValue",
                        String.class, securedStringClass);
                authToken = (String) basicAuthHeaderValue.invoke(null, username, securePasswordString);
            }
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException
                | IllegalAccessException | InvocationTargetException shieldLoadException) {
            logger.debug(
                    "Did not detect Elasticsearch Shield plugin, secure connections and/or authorization will not be available");
        }
    } else {
        //logger.debug("No Shield plugin location specified, secure connections and/or authorization will not be available");
    }
    TransportClient transportClient = builder.settings(settingsBuilder.build()).build();
    Thread.currentThread().setContextClassLoader(originalClassLoader);
    return transportClient;
}

From source file:com.hurence.logisland.plugin.PluginManager.java

private static void installPlugin(String artifact, String logislandHome) {
    Optional<ModuleInfo> moduleInfo = findPluginMeta().entrySet().stream()
            .filter(e -> artifact.equals(e.getKey().getArtifact())).map(Map.Entry::getKey).findFirst();
    if (moduleInfo.isPresent()) {
        System.err//from   w w w. ja  v  a2s .  com
                .println("A component already matches the artifact " + artifact + ". Please remove it first.");
        System.exit(-1);
    }

    try {

        IvySettings settings = new IvySettings();
        settings.load(new File(logislandHome, "conf/ivy.xml"));

        Ivy ivy = Ivy.newInstance(settings);
        ivy.bind();

        System.out.println("\nDownloading dependencies. Please hold on...\n");

        String parts[] = Arrays.stream(artifact.split(":")).map(String::trim).toArray(a -> new String[a]);
        if (parts.length != 3) {
            throw new IllegalArgumentException(
                    "Unrecognized artifact format. It should be groupId:artifactId:version");
        }
        ModuleRevisionId revisionId = new ModuleRevisionId(new ModuleId(parts[0], parts[1]), parts[2]);
        Set<ArtifactDownloadReport> toBePackaged = downloadArtifacts(ivy, revisionId,
                new String[] { "default", "compile", "runtime" });

        ArtifactDownloadReport artifactJar = toBePackaged.stream()
                .filter(a -> a.getArtifact().getModuleRevisionId().equals(revisionId)).findFirst()
                .orElseThrow(() -> new IllegalStateException("Unable to find artifact " + artifact
                        + ". Please check the name is correct and the repositories on ivy.xml are correctly configured"));

        Manifest manifest = new JarFile(artifactJar.getLocalFile()).getManifest();
        File libDir = new File(logislandHome, "lib");

        if (manifest.getMainAttributes().containsKey(ManifestAttributes.MODULE_ARTIFACT)) {
            org.apache.commons.io.FileUtils.copyFileToDirectory(artifactJar.getLocalFile(), libDir);
            //we have a logisland plugin. Just copy it
            System.out.println(String.format("Found logisland plugin %s version %s\n" + "It will provide:",
                    manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_NAME),
                    manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION)));
            Arrays.stream(manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_EXPORTS).split(","))
                    .map(String::trim).forEach(s -> System.out.println("\t" + s));

        } else {
            System.out.println("Repackaging artifact and its dependencies");
            Set<ArtifactDownloadReport> environment = downloadArtifacts(ivy, revisionId,
                    new String[] { "provided" });
            Set<ArtifactDownloadReport> excluded = toBePackaged.stream()
                    .filter(adr -> excludeGroupIds.stream()
                            .anyMatch(s -> s.matches(adr.getArtifact().getModuleRevisionId().getOrganisation()))
                            || excludedArtifactsId.stream().anyMatch(
                                    s -> s.matches(adr.getArtifact().getModuleRevisionId().getName())))
                    .collect(Collectors.toSet());

            toBePackaged.removeAll(excluded);
            environment.addAll(excluded);

            Repackager rep = new Repackager(artifactJar.getLocalFile(), new LogislandPluginLayoutFactory());
            rep.setMainClass("");
            File destFile = new File(libDir, "logisland-component-" + artifactJar.getLocalFile().getName());
            rep.repackage(destFile, callback -> toBePackaged.stream().filter(adr -> adr.getLocalFile() != null)
                    .filter(adr -> !adr.getArtifact().getModuleRevisionId().equals(revisionId))
                    .map(adr -> new Library(adr.getLocalFile(), LibraryScope.COMPILE)).forEach(library -> {
                        try {
                            callback.library(library);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }));
            Thread.currentThread().setContextClassLoader(new URLClassLoader(
                    environment.stream().filter(adr -> adr.getLocalFile() != null).map(adr -> {
                        try {
                            return adr.getLocalFile().toURI().toURL();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }).toArray(a -> new URL[a]), Thread.currentThread().getContextClassLoader()));
            //now clean up package and write the manifest
            String newArtifact = "com.hurence.logisland.repackaged:" + parts[1] + ":" + parts[2];
            LogislandRepackager.execute(destFile.getAbsolutePath(), "BOOT-INF/lib-provided", parts[2],
                    newArtifact, "Logisland Component for " + artifact, "Logisland Component for " + artifact,
                    new String[] { "org.apache.kafka.*" }, new String[0],
                    "org.apache.kafka.connect.connector.Connector");
        }
        System.out.println("Install done!");
    } catch (Exception e) {
        System.err.println("Unable to install artifact " + artifact);
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:com.googlecode.psiprobe.AbstractTomcatContainer.java

/**
 * Lists and optionally compiles all JSPs for the given context. Compilation details are added to the summary.
 *
 * @param context//from ww  w.  j ava 2 s.  co m
 * @param summary
 * @param compile
 * @throws Exception
 */
public void listContextJsps(Context context, Summary summary, boolean compile) throws Exception {
    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());
                }

                //
                // mark all items as missing
                //
                for (Iterator it = summary.getItems().keySet().iterator(); it.hasNext();) {
                    Item item = (Item) summary.getItems().get(it.next());
                    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
                //
                compileItem("/", opt, context, jrctx, summary,
                        new URLClassLoader(new URL[] {}, context.getLoader().getClassLoader()), 0, compile);
            } finally {
                jrctx.destroy();
            }
        }

        //
        // delete "missing" items by keeping "not missing" ones
        //
        Map hashMap = new HashMap();
        for (Iterator it = summary.getItems().keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            Item item = (Item) summary.getItems().get(key);
            if (!item.isMissing()) {
                hashMap.put(key, item);
            }
        }

        summary.setItems(hashMap);
    } else {
        logger.error("Context " + context.getName() + " does not have \"jsp\" servlet");
    }
}

From source file:ml.shifu.guagua.hadoop.io.GuaguaOptionsParser.java

/**
 * Modify configuration according user-specified generic options
 * // ww  w.j a  va2s. co  m
 * @param conf
 *            Configuration to be modified
 * @param line
 *            User-specified generic options
 */
private void processGeneralOptions(Configuration conf, CommandLine line) throws IOException {
    if (line.hasOption("fs")) {
        FileSystem.setDefaultUri(conf, line.getOptionValue("fs"));
    }

    if (line.hasOption("jt")) {
        conf.set("mapred.job.tracker", line.getOptionValue("jt"));
    }
    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("mapred.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("mapreduce.job.credentials.json", localFs.makeQualified(p).toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.codehaus.enunciate.modules.jaxws.TestJAXWSSupportDeploymentModule.java

/**
 * Create the wrapper class for the given web messgae.
 *
 * @param message The web message.// www  .  j  av  a2s  . c  o m
 * @param templateURL The url for the template to use to create the wrapper class.
 * @param beanFQN The fqn of the bean.
 * @return The wrapper class.
 */
protected Class createWrapperClass(WebMessage message, URL templateURL, String beanFQN) throws Exception {
    setupDefaultModel();

    //generate the java source file.
    Enunciate enunciate = new Enunciate(new String[0]);
    File genDir = enunciate.createTempDir();
    enunciate.setGenerateDir(genDir);
    JAXWSSupportDeploymentModule module = new JAXWSSupportDeploymentModule() {
        @Override
        protected EnunciateFreemarkerModel getModelInternal() {
            return (EnunciateFreemarkerModel) FreemarkerModel.get();
        }
    };
    module.init(enunciate);
    EnunciateFreemarkerModel model = module.getModel();
    model.put("file", new SpecifiedOutputDirectoryFileTransform(genDir));
    model.put("message", message);
    model.put("Introspector",
            BeansWrapper.getDefaultInstance().getStaticModels().get("java.beans.Introspector"));
    module.processTemplate(templateURL, model);

    Collection<String> srcFiles = enunciate.getJavaFiles(genDir);
    assertEquals("The wrapper bean should have been generated.", 1, srcFiles.size());
    srcFiles.addAll(getAllJavaFiles(getSamplesDir()));
    File buildDir = enunciate.createTempDir();
    enunciate.invokeJavac(getInAPTClasspath(), buildDir, srcFiles.toArray(new String[srcFiles.size()]));
    URLClassLoader loader = new URLClassLoader(new URL[] { buildDir.toURL() }, getClass().getClassLoader());
    Class generatedClass = Class.forName(beanFQN, true, loader);
    assertNotNull(generatedClass);

    return generatedClass;
}

From source file:com.aliyun.odps.graph.local.LocalGraphJobRunner.java

private void processResources() throws IOException, OdpsException {

    File resDir = jobDirecotry.getResourceDir();

    String curProjName = SessionState.get().getOdps().getDefaultProject();
    String[] resources = conf.getStrings(GRAPH_CONF.CACHE_RESOURCES);
    int maxResouceNum = 256;

    if (resources == null || resources.length == 0) {
        return;/*from   w w  w  .  j a v a 2s. c o m*/
    }

    Set<String> names = new HashSet<String>(Arrays.asList(resources));
    LOG.info("Start to process resources: " + StringUtils.join(resources, ','));
    if (names.size() > maxResouceNum) {
        throw new IOException(
                ExceptionCode.ODPS_0720331 + " - define too many cache resources, must be <= " + maxResouceNum);
    }
    long resourceSize = 0;
    URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    ArrayList<URL> cp = new ArrayList<URL>(Arrays.asList(loader.getURLs()));
    for (String name : names) {

        List<String> res = LocalRunUtils.parseResourceName(name, curProjName);

        String projName = res.get(0);
        String resName = res.get(1);

        if (!wareHouse.existsResource(projName, resName)
                || wareHouse.getDownloadMode() == DownloadMode.ALWAYS) {
            DownloadUtils.downloadResource(odps, projName, resName, wareHouse.getLimitDownloadRecordCount(),
                    wareHouse.getInputColumnSeperator());
            resourceSize += new File(resDir, resName).length();

        }
        wareHouse.copyResource(projName, resName, resDir, wareHouse.getLimitDownloadRecordCount(),
                wareHouse.getInputColumnSeperator());
        cp.add(new File(resDir, resName).toURI().toURL());
        if (resourceSize > 512 * 1024 * 1024) {
            throw new IOException(ExceptionCode.ODPS_0720071 + " - must be <= 512M");
        }
    }
    URLClassLoader newLoader = new URLClassLoader(cp.toArray(new URL[0]), loader);
    Thread.currentThread().setContextClassLoader(newLoader);
    conf.setClassLoader(newLoader);
}

From source file:org.apache.druid.initialization.Initialization.java

private static URLClassLoader makeClassLoaderForExtension(final File extension,
        final boolean useExtensionClassloaderFirst) {
    final Collection<File> jars = FileUtils.listFiles(extension, new String[] { "jar" }, false);
    final URL[] urls = new URL[jars.size()];

    try {//from w w w . jav a 2 s  .c  o m
        int i = 0;
        for (File jar : jars) {
            final URL url = jar.toURI().toURL();
            log.info("added URL[%s] for extension[%s]", url, extension.getName());
            urls[i++] = url;
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    if (useExtensionClassloaderFirst) {
        return new ExtensionFirstClassLoader(urls, Initialization.class.getClassLoader());
    } else {
        return new URLClassLoader(urls, Initialization.class.getClassLoader());
    }
}

From source file:com.scaleoutsoftware.soss.hserver.hadoop.DistributedCacheManager.java

/**
 * Creates a class loader that includes the designated
 * files and archives.//from   w  ww .  j av a 2 s  .  c o m
 */
public ClassLoader makeClassLoader(final ClassLoader parent) throws MalformedURLException {
    final URL[] urls = new URL[localClasspaths.size()];
    for (int i = 0; i < localClasspaths.size(); ++i) {
        urls[i] = new File(localClasspaths.get(i)).toURI().toURL();
        LOG.info(urls[i]);
    }
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(urls, parent);
        }
    });
}

From source file:org.orbeon.oxf.processor.JavaProcessor.java

private Processor getProcessor(PipelineContext context) {
    try {//from  w  w  w  .  j  av  a2  s.  c  o m
        // Read config input into a String, cache if possible
        ProcessorInput input = getInputByName(INPUT_CONFIG);
        final Config config = readCacheInputAsObject(context, input, new CacheableInputReader<Config>() {
            public Config read(PipelineContext context, ProcessorInput input) {
                Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
                Element configElement = configDocument.getRootElement();
                Config config = new Config();
                config.clazz = configElement.attributeValue("class");

                // Get source path
                String sourcePathAttributeValue = configElement.attributeValue("sourcepath");
                if (sourcePathAttributeValue == null)
                    sourcePathAttributeValue = ".";
                File sourcePath = getFileFromURL(sourcePathAttributeValue,
                        JavaProcessor.this.getLocationData());
                if (!sourcePath.isDirectory())
                    throw new ValidationException(
                            "Invalid sourcepath attribute: cannot find directory for URL: "
                                    + sourcePathAttributeValue,
                            (LocationData) configElement.getData());
                try {
                    config.sourcepath = sourcePath.getCanonicalPath();
                } catch (IOException e) {
                    throw new ValidationException(
                            "Invalid sourcepath attribute: cannot find directory for URL: "
                                    + sourcePathAttributeValue,
                            (LocationData) configElement.getData());
                }

                return config;
            }
        });

        // Check if need to compile
        String sourceFile = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
        String destinationDirectory = SystemUtils.getTemporaryDirectory().getAbsolutePath();
        String destinationFile = destinationDirectory + "/" + config.clazz.replace('.', '/') + ".class";

        // Check if file is up-to-date
        long currentTimeMillis = System.currentTimeMillis();
        Long sourceLastModified;
        Long destinationLastModified;
        synchronized (lastModifiedMap) {
            sourceLastModified = (Long) lastModifiedMap.get(currentTimeMillis, sourceFile);
            if (sourceLastModified == null) {
                sourceLastModified = new Long(new File(sourceFile).lastModified());
                lastModifiedMap.put(currentTimeMillis, sourceFile, sourceLastModified);
            }
            destinationLastModified = (Long) lastModifiedMap.get(currentTimeMillis, destinationFile);
            if (destinationLastModified == null) {
                destinationLastModified = new Long(new File(destinationFile).lastModified());
                lastModifiedMap.put(currentTimeMillis, destinationFile, destinationLastModified);
            }
        }
        boolean fileUpToDate = sourceLastModified.longValue() < destinationLastModified.longValue();

        // Compile
        if (!fileUpToDate) {
            StringBuilderWriter javacOutput = new StringBuilderWriter();

            final ArrayList<String> argLst = new ArrayList<String>();
            final String[] cmdLine;
            {
                argLst.add("-g");
                final String cp = buildClassPath(context);
                if (cp != null) {
                    argLst.add("-classpath");
                    argLst.add(cp);
                }

                if (config.sourcepath != null && config.sourcepath.length() > 0) {
                    argLst.add("-sourcepath");
                    argLst.add(config.sourcepath);
                }
                argLst.add("-d");
                final File tmp = SystemUtils.getTemporaryDirectory();
                final String tmpPth = tmp.getAbsolutePath();
                argLst.add(tmpPth);
                final String fnam = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
                argLst.add(fnam);

                cmdLine = new String[argLst.size()];
                argLst.toArray(cmdLine);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Compiling class '" + config.clazz + "'");
                logger.debug("javac " + argLst.toString());
            }
            Throwable thrown = null;
            int exitCode = 1;
            try {
                // Get compiler class, either user-specified or default to Sun compiler
                String compilerMain = getPropertySet().getString(COMPILER_CLASS_PROPERTY,
                        DEFAULT_COMPILER_MAIN);

                ClassLoader classLoader;
                {
                    URI compilerJarURI = getPropertySet().getURI(COMPILER_JAR_PROPERTY);
                    if (compilerJarURI != null) {
                        // 1: Always honor user-specified compiler JAR if present
                        // Use special class loader pointing to this URL
                        classLoader = new URLClassLoader(new URL[] { compilerJarURI.toURL() },
                                JavaProcessor.class.getClassLoader());
                        if (logger.isDebugEnabled())
                            logger.debug("Java processor using user-specified compiler JAR: "
                                    + compilerJarURI.toString());
                    } else {
                        // 2: Try to use the class loader that loaded this class
                        classLoader = JavaProcessor.class.getClassLoader();
                        try {
                            Class.forName(compilerMain, true, classLoader);
                            logger.debug("Java processor using current class loader");
                        } catch (ClassNotFoundException e) {
                            // Class not found
                            // 3: Try to get to Sun tools.jar
                            String javaHome = System.getProperty("java.home");
                            if (javaHome != null) {
                                File javaHomeFile = new File(javaHome);
                                if (javaHomeFile.getName().equals("jre")) {
                                    File toolsFile = new File(javaHomeFile.getParentFile(),
                                            "lib" + File.separator + "tools.jar");
                                    if (toolsFile.exists()) {
                                        // JAR file exists, will use it to load compiler class
                                        classLoader = new URLClassLoader(
                                                new URL[] { toolsFile.toURI().toURL() },
                                                JavaProcessor.class.getClassLoader());
                                        if (logger.isDebugEnabled())
                                            logger.debug("Java processor using default tools.jar under "
                                                    + toolsFile.toString());
                                    }
                                }
                            }
                        }
                    }
                }

                // Load compiler class using class loader defined above
                Class compilerClass = Class.forName(compilerMain, true, classLoader);

                // Get method and run compiler
                Method compileMethod = compilerClass.getMethod("compile",
                        new Class[] { String[].class, PrintWriter.class });
                Object result = compileMethod.invoke(null, cmdLine, new PrintWriter(javacOutput));
                exitCode = ((Integer) result).intValue();

            } catch (final Throwable t) {
                thrown = t;
            }
            if (exitCode != 0) {
                String javacOutputString = "\n" + javacOutput.toString();
                javacOutputString = StringUtils.replace(javacOutputString, "\n", "\n    ");
                throw new OXFException("Error compiling '" + argLst.toString() + "'" + javacOutputString,
                        thrown);
            }
        }

        // Try to get sourcepath info
        InternalCacheKey sourcepathKey = new InternalCacheKey(JavaProcessor.this, "javaFile",
                config.sourcepath);
        Object sourcepathValidity = new Long(0);
        Sourcepath sourcepath = (Sourcepath) ObjectCache.instance().findValid(sourcepathKey,
                sourcepathValidity);

        // Create classloader
        if (sourcepath == null
                || (sourcepath.callNameToProcessorClass.containsKey(config.clazz) && !fileUpToDate)) {
            if (logger.isDebugEnabled())
                logger.debug("Creating classloader for sourcepath '" + config.sourcepath + "'");
            sourcepath = new Sourcepath();
            sourcepath.classLoader = new URLClassLoader(
                    new URL[] { SystemUtils.getTemporaryDirectory().toURI().toURL(),
                            new File(config.sourcepath).toURI().toURL() },
                    this.getClass().getClassLoader());
            ObjectCache.instance().add(sourcepathKey, sourcepathValidity, sourcepath);
        }

        // Get processor class
        Class<Processor> processorClass = sourcepath.callNameToProcessorClass.get(config.clazz);
        if (processorClass == null) {
            processorClass = (Class<Processor>) sourcepath.classLoader.loadClass(config.clazz);
            sourcepath.callNameToProcessorClass.put(config.clazz, processorClass);
        }

        // Create processor from class
        Thread.currentThread().setContextClassLoader(processorClass.getClassLoader());
        return processorClass.newInstance();

    } catch (final IOException e) {
        throw new OXFException(e);
    } catch (final IllegalAccessException e) {
        throw new OXFException(e);
    } catch (final InstantiationException e) {
        throw new OXFException(e);
    } catch (final ClassNotFoundException e) {
        throw new OXFException(e);
    }
}

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

private void init() throws InterpreterException, IOException, RepositoryException {
    String interpreterJson = zeppelinConfiguration.getInterpreterJson();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    if (Files.exists(interpreterDirPath)) {
        for (Path interpreterDir : Files.newDirectoryStream(interpreterDirPath, new Filter<Path>() {
            @Override/*  w w w .  j  av  a 2  s . c o m*/
            public boolean accept(Path entry) throws IOException {
                return Files.exists(entry) && Files.isDirectory(entry);
            }
        })) {
            String interpreterDirString = interpreterDir.toString();

            /**
             * Register interpreter by the following ordering
             * 1. Register it from path {ZEPPELIN_HOME}/interpreter/{interpreter_name}/
             *    interpreter-setting.json
             * 2. Register it from interpreter-setting.json in classpath
             *    {ZEPPELIN_HOME}/interpreter/{interpreter_name}
             * 3. Register it by Interpreter.register
             */
            if (!registerInterpreterFromPath(interpreterDirString, interpreterJson)) {
                if (!registerInterpreterFromResource(cl, interpreterDirString, interpreterJson)) {
                    /*
                     * TODO(jongyoul)
                     * - Remove these codes below because of legacy code
                     * - Support ThreadInterpreter
                    */
                    URLClassLoader ccl = new URLClassLoader(recursiveBuildLibList(interpreterDir.toFile()), cl);
                    for (String className : interpreterClassList) {
                        try {
                            // Load classes
                            Class.forName(className, true, ccl);
                            Set<String> interpreterKeys = Interpreter.registeredInterpreters.keySet();
                            for (String interpreterKey : interpreterKeys) {
                                if (className.equals(Interpreter.registeredInterpreters.get(interpreterKey)
                                        .getClassName())) {
                                    Interpreter.registeredInterpreters.get(interpreterKey)
                                            .setPath(interpreterDirString);
                                    logger.info("Interpreter " + interpreterKey + " found. class=" + className);
                                    cleanCl.put(interpreterDirString, ccl);
                                }
                            }
                        } catch (Throwable t) {
                            // nothing to do
                        }
                    }
                }
            }
        }
    }

    for (RegisteredInterpreter registeredInterpreter : Interpreter.registeredInterpreters.values()) {
        logger.debug("Registered: {} -> {}. Properties: {}", registeredInterpreter.getInterpreterKey(),
                registeredInterpreter.getClassName(), registeredInterpreter.getProperties());
    }

    // RegisteredInterpreters -> interpreterSettingRef
    InterpreterInfo interpreterInfo;
    for (RegisteredInterpreter r : Interpreter.registeredInterpreters.values()) {
        interpreterInfo = new InterpreterInfo(r.getClassName(), r.getName(), r.isDefaultInterpreter(),
                r.getEditor());
        add(r.getGroup(), interpreterInfo, r.getProperties(), defaultOption, r.getPath(), r.getRunner());
    }

    for (String settingId : interpreterSettingsRef.keySet()) {
        InterpreterSetting setting = interpreterSettingsRef.get(settingId);
        logger.info("InterpreterSettingRef name {}", setting.getName());
    }

    loadFromFile();

    // if no interpreter settings are loaded, create default set
    if (0 == interpreterSettings.size()) {
        Map<String, InterpreterSetting> temp = new HashMap<>();
        InterpreterSetting interpreterSetting;
        for (InterpreterSetting setting : interpreterSettingsRef.values()) {
            interpreterSetting = createFromInterpreterSettingRef(setting);
            temp.put(setting.getName(), interpreterSetting);
        }

        for (String group : interpreterGroupOrderList) {
            if (null != (interpreterSetting = temp.remove(group))) {
                interpreterSettings.put(interpreterSetting.getId(), interpreterSetting);
            }
        }

        for (InterpreterSetting setting : temp.values()) {
            interpreterSettings.put(setting.getId(), setting);
        }

        saveToFile();
    }

    for (String settingId : interpreterSettings.keySet()) {
        InterpreterSetting setting = interpreterSettings.get(settingId);
        logger.info("InterpreterSetting group {} : id={}, name={}", setting.getGroup(), settingId,
                setting.getName());
    }
}