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:de.micromata.genome.util.runtime.DynamicClassPath.java

public static void addContextClassPathes(URL[] urls) {
    URLClassLoader urlClassLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(urlClassLoader);
}

From source file:com.mirth.connect.server.util.javascript.MirthContextFactory.java

public MirthContextFactory(URL[] urls, Set<String> resourceIds) {
    this.id = UUID.randomUUID().toString();
    this.urls = urls;
    this.resourceIds = resourceIds;

    ClassLoader classLoader = null;
    if (ArrayUtils.isNotEmpty(urls)) {
        classLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
    } else {/*from  www.  j a va 2  s.  com*/
        classLoader = Thread.currentThread().getContextClassLoader();
    }

    initApplicationClassLoader(classLoader);

    sealedSharedScope = JavaScriptScopeUtil.createSealedSharedScope(this);
    serializer = new ObjectXMLSerializer(classLoader);
    try {
        serializer.init(ControllerFactory.getFactory().createConfigurationController().getServerVersion());
    } catch (Exception e) {
    }
}

From source file:net.orfjackal.dimdwarf.server.ApplicationLoader.java

public ApplicationLoader(File applicationDir, ClassLoader parent) throws ConfigurationException {
    List<File> classpath = new ArrayList<>();
    classpath.add(new File(applicationDir, CLASSES_DIR));
    classpath.addAll(Arrays.asList(listJarsInDirectory(new File(applicationDir, LIBRARIES_DIR))));
    classLoader = new URLClassLoader(asUrls(classpath), parent);

    applicationName = getRequiredProperty(APP_NAME, CONFIG_FILE);
    applicationModule = getRequiredProperty(APP_MODULE, CONFIG_FILE);
}

From source file:com.navercorp.pinpoint.profiler.instrument.classloading.Java9DefineClassTest.java

@Test
public void defineClass() throws ClassNotFoundException, IOException {
    URL location = CodeSourceUtils.getCodeLocation(Logger.class);
    logger.debug("location:{}", location);

    URL[] empty = {};//from   ww  w.  j  a  va  2 s .c  om
    URLClassLoader classLoader = new URLClassLoader(empty, null);
    try {
        classLoader.loadClass(Logger.class.getName());
        Assert.fail();
    } catch (ClassNotFoundException ignore) {
    }

    String className = JavaAssistUtils.javaClassNameToJvmResourceName(Logger.class.getName());
    InputStream classStream = Logger.class.getClassLoader().getResourceAsStream(className);
    byte[] bytes = IOUtils.readFully(classStream, classStream.available());

    DefineClass defineClass = new Java9DefineClass();
    Class<?> defineClassSlf4jLogger = defineClass.defineClass(classLoader, Logger.class.getName(), bytes);
    Class<?> slf4jLogger = classLoader.loadClass(Logger.class.getName());

    Assert.assertSame(defineClassSlf4jLogger, slf4jLogger);
    Assert.assertSame(slf4jLogger.getClassLoader(), classLoader);

    Assert.assertNotSame(slf4jLogger.getClassLoader(), Logger.class.getClassLoader());

}

From source file:org.apache.hive.spark.client.SparkClientUtilities.java

/**
 * Add new elements to the classpath.//from   ww  w  .j a va  2  s  .  c  o m
 *
 * @param newPaths Map of classpath elements and corresponding timestamp
 * @return locally accessible files corresponding to the newPaths
 */
public static List<String> addToClassPath(Map<String, Long> newPaths, Configuration conf, File localTmpDir)
        throws Exception {
    URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    List<URL> curPath = Lists.newArrayList(loader.getURLs());
    List<String> localNewPaths = new ArrayList<>();

    boolean newPathAdded = false;
    for (Map.Entry<String, Long> entry : newPaths.entrySet()) {
        URL newUrl = urlFromPathString(entry.getKey(), entry.getValue(), conf, localTmpDir);
        localNewPaths.add(newUrl.toString());
        if (newUrl != null && !curPath.contains(newUrl)) {
            curPath.add(newUrl);
            LOG.info("Added jar[" + newUrl + "] to classpath.");
            newPathAdded = true;
        }
    }

    if (newPathAdded) {
        URLClassLoader newLoader = new URLClassLoader(curPath.toArray(new URL[curPath.size()]), loader);
        Thread.currentThread().setContextClassLoader(newLoader);
    }
    return localNewPaths;
}

From source file:com.phoenixnap.oss.ramlapisync.plugin.ClassLoaderUtils.java

public static void addLocationsToClassLoader(MavenProject mavenProject) throws MojoExecutionException {

    List<URL> urls = Lists.newArrayList();
    try {//from  www .j a  va 2  s.com
        urls.add(new File(mavenProject.getBuild().getOutputDirectory()).toURI().toURL());

        // Getting all artifacts locations
        Set<Artifact> artifacts = mavenProject.getArtifacts();

        for (Artifact artifact : artifacts) {
            urls.add(artifact.getFile().toURI().toURL());
        }

    } catch (MalformedURLException e) {
        // DO NOTHING
    }

    /*
     * this was failing when executing goal on a maven project if (originalClassLoader != null) { throw new
     * MojoExecutionException( "Context setting of the current thread ClassLoader is allowed only once."); }
     */

    // Store ClassLoader before applying modifications.
    originalClassLoader = Thread.currentThread().getContextClassLoader();

    Thread.currentThread()
            .setContextClassLoader(new URLClassLoader(urls.toArray(new URL[urls.size()]), originalClassLoader));

}

From source file:de.zib.gndms.infra.system.PluginLoader.java

public URLClassLoader loadPlugins() throws IOException {

    final ArrayList<URL> jars;

    final File pluginDir = new File(pluginPath);

    final String[] list = pluginDir.list(new FilenameFilter() {
        @Override//  www .  j a  v  a 2s . c  o  m
        public boolean accept(final File dir, final String name) {

            return name.matches(".*\\.jar");
        }
    });

    if (list != null) {
        jars = new ArrayList<URL>(list.length);
        for (int i = 0; i < list.length; ++i)
            jars.add(new URL("file://" + pluginPath + File.separator + list[i]));

        return new URLClassLoader(jars.toArray(new URL[jars.size()]), this.getClass().getClassLoader());
    }

    return new URLClassLoader(new URL[] {}, this.getClass().getClassLoader());
}

From source file:com.sleepcamel.ifdtoutils.MvnPluginMojo.java

@SuppressWarnings("deprecation")
public void execute() throws MojoExecutionException {
    try {//from  w w  w .  j  a  v a 2s .c  om

        if (outputDirectory == null || !outputDirectory.exists()) {
            throw new MojoExecutionException("Class directory must exist");
        }

        URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { outputDirectory.toURL() },
                getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(urlClassLoader);

        Collection<File> listFiles = FileUtils.listFiles(outputDirectory, new String[] { "class" }, true);
        for (File file : listFiles) {
            getLog().debug("\nClass found: " + file.getName());
            try {
                Class<?> loadedClass = urlClassLoader.loadClass(fileToClass(outputDirectory, file));
                getLog().debug("Class " + loadedClass.getName() + " loaded");
                if (!loadedClass.isInterface()) {
                    getLog().debug("Not an interface :(");
                    continue;
                }

                ToDTO annotation = loadedClass.getAnnotation(ToDTO.class);

                if (annotation == null) {
                    getLog().debug("No annotation not found :(");
                } else {
                    dtosToGenerate.add(loadedClass);
                    getLog().debug("Annotation found!");
                }
            } catch (ClassNotFoundException e) {
            }
        }

        getLog().info("Found " + dtosToGenerate.size() + " interfaces to generate their DTOs...\n");

        for (Class<?> interfaceClass : dtosToGenerate) {
            String interfaceClassName = interfaceClass.getName();
            try {
                Thread.currentThread().getContextClassLoader()
                        .loadClass(InterfaceDTOInfo.getInfo(interfaceClass).getDTOCanonicalName());
                getLog().info("DTO for interface " + interfaceClassName + " exists, skipping generation\n");
            } catch (ClassNotFoundException e) {
                getLog().info("Generating dto for interface " + interfaceClassName + "...");
                DTOClassGenerator.generateDTOForInterface(interfaceClass, outputDirectory.getAbsolutePath());
                getLog().info("DTO generated for interface " + interfaceClassName + "\n");
            }
        }

    } catch (Exception e1) {
        throw new MojoExecutionException(e1.getMessage());
    }

}

From source file:com.github.persapiens.jsfboot.undertow.JsfUndertowDeploymentInfoCustomizer.java

@Override
public void customize(final DeploymentInfo di) {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override//from   w w w.  j a  va 2  s .  co m
        public Void run() {
            ClassLoader jsfClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
            di.setClassLoader(jsfClassLoader);

            di.setResourceManager(
                    new ClassPathResourceManager(jsfClassLoader, undertowProperties.getClassPathResource()));

            return null;
        }
    });

    LOGGER.info("Setting Undertow classLoader to " + undertowProperties.getClassPathResource() + " directory");
}

From source file:net.sf.taverna.raven.launcher.TestPreLauncher.java

@Test
public void launchHelloWorld() throws Exception {
    System.setProperty("raven.launcher.app.name", "helloworld");
    System.setProperty("raven.launcher.app.main", "net.sf.taverna.raven.helloworld.HelloWorld");
    List<URL> urls = makeClassPath("TestPreLauncher-helloworld/");
    URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(classLoader);
    classLoader.loadClass("org.apache.log4j.Logger");

    File outFile = File.createTempFile(getClass().getCanonicalName(), "test");
    outFile.deleteOnExit();/*from   w  w  w .j a v  a  2  s .  c om*/

    PreLauncher.main(new String[] { outFile.getAbsolutePath() });
    String out = FileUtils.readFileToString(outFile, "utf8");
    assertEquals("Did not match expected output", "This is the test data.\n", out);
}