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

public URLClassLoader(URL[] urls) 

Source Link

Document

Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader .

Usage

From source file:net.pms.external.ExternalFactory.java

/**
 * This method loads the jar files found in the plugin dir
 * or if installed from the web.// w ww  . j  av a  2 s .com
 */
public static void loadJAR(URL[] jarURL, boolean download, URL newURL) {
    /* Create a classloader to take care of loading the plugin classes from
     * their URL.
     *
     * A not on the suppressed warning: The classloader need to remain open as long
     * as the loaded classes are in use - in our case forever.
     * @see http://stackoverflow.com/questions/13944868/leaving-classloader-open-after-first-use
     */
    @SuppressWarnings("resource")
    URLClassLoader classLoader = new URLClassLoader(jarURL);
    Enumeration<URL> resources;

    try {
        // Each plugin .jar file has to contain a resource named "plugin"
        // which should contain the name of the main plugin class.
        resources = classLoader.getResources("plugin");
    } catch (IOException e) {
        LOGGER.error("Can't load plugin resources: {}", e.getMessage());
        LOGGER.trace("", e);
        try {
            classLoader.close();
        } catch (IOException e2) {
            // Just swallow
        }
        return;
    }

    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();

        try {
            // Determine the plugin main class name from the contents of
            // the plugin file.
            char[] name;
            try (InputStreamReader in = new InputStreamReader(url.openStream())) {
                name = new char[512];
                in.read(name);
            }
            String pluginMainClassName = new String(name).trim();

            LOGGER.info("Found plugin: " + pluginMainClassName);

            if (download) {
                // Only purge code when downloading!
                purgeCode(pluginMainClassName, newURL);
            }

            // Try to load the class based on the main class name
            Class<?> clazz = classLoader.loadClass(pluginMainClassName);
            registerListenerClass(clazz);

            if (download) {
                downloadedListenerClasses.add(clazz);
            }
        } catch (Exception | NoClassDefFoundError e) {
            LOGGER.error("Error loading plugin", e);
        }
    }
}

From source file:SearchlistClassLoader.java

/**
 *  create a SearchlistClassLoader.
 */
public SearchlistClassLoader(URL url[]) {
    content = new Loader(new URLClassLoader(url), false);
}

From source file:com.lexicalscope.javabeanhelpers.generator.plugin.JavaBeanHelpersGeneratorMojo.java

private ClassLoader getClassLoader() throws MalformedURLException, DependencyResolutionRequiredException {
    synchronized (JavaBeanHelpersGeneratorMojo.class) {
        if (classLoader == null) {
            final List<URL> urls = new ArrayList<URL>();
            for (final Object object : project.getCompileClasspathElements()) {
                if (!object.equals(project.getBuild().getOutputDirectory())) {
                    final String path = (String) object;
                    urls.add(new File(path).toURI().toURL());
                }//from  www . j a  va 2 s. c o  m
            }
            classLoader = new URLClassLoader(urls.toArray(new URL[] {}));
        }
        return classLoader;
    }
}

From source file:com.eviware.soapui.plugins.PluginManager.java

private Plugin doInstallPlugin(File pluginFile, Collection<JarClassLoader> classLoaders) throws IOException {
    // add jar to resource classloader so embedded images can be found with UISupport.loadImageIcon(..)
    UISupport.addResourceClassLoader(new URLClassLoader(new URL[] { pluginFile.toURI().toURL() }));

    InstalledPluginRecord context = pluginLoader.loadPlugin(pluginFile, classLoaders);
    installedPlugins.put(pluginFile, context);
    for (PluginListener listener : listeners) {
        listener.pluginLoaded(context.plugin);
    }/*w  w  w. j a  va  2  s . co  m*/

    return context.plugin;
}

From source file:org.openecard.addon.FileRegistry.java

@Override
public ClassLoader downloadAddon(AddonSpecification addonSpec) {
    String aId = addonSpec.getId();
    // TODO use other own classloader impl with security features
    URL[] url = new URL[1];
    try {/*from  w  w w.ja  v a 2  s .  c om*/
        url[0] = files.get(aId).toURI().toURL();
    } catch (MalformedURLException e) {
        // TODO will this ever happen?
        logger.error(e.getMessage(), e);
    }
    URLClassLoader ucl = new URLClassLoader(url);
    return ucl;
}

From source file:SearchlistClassLoader.java

/**
 *  create a SearchlistClassLoader.//from  ww w  . ja v  a2 s  .  c  o  m
 */
public SearchlistClassLoader(URL url[], ClassLoader parent) {
    super(parent);
    content = new Loader(new URLClassLoader(url), false);
}

From source file:com.github.juanmf.java2plant.Parser.java

private static Collection<URL> getUrls(List<ClassLoader> classLoadersList) {
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());
    Collection<URL> urls = ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]));
    CLASS_LOADER = new URLClassLoader(urls.toArray(new URL[0]));
    return urls;//w  ww.  ja  v  a 2s. c o  m
}

From source file:net.sourceforge.mavenhippo.gen.BeanGeneratorTest.java

@Test
public void compilationTest()
        throws ContentTypeException, TemplateException, IOException, ClassNotFoundException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, baseDocument.getAbsolutePath()));
    Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, newsDocument.getAbsolutePath()));
    Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, testCompound.getAbsolutePath()));
    URLClassLoader classLoader = new URLClassLoader(new URL[] { tempFolder.toURI().toURL() });

    Assert.assertNotNull(Class.forName("generated.beans.TestCompound", true, classLoader));
    Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, myCompound.getAbsolutePath()));

    Assert.assertEquals(0,/*  ww w  .  jav  a  2 s  . com*/
            compiler.run(System.in, System.out, System.err, carouselBannerPickerMixin.getAbsolutePath()));
}

From source file:com.streamsets.datacollector.cluster.TestClusterProviderImpl.java

@Before
public void setup() throws Exception {
    tempDir = File.createTempFile(getClass().getSimpleName(), "");
    sparkManagerShell = new File(tempDir, "_cluster-manager");
    Assert.assertTrue(tempDir.delete());
    Assert.assertTrue(tempDir.mkdir());//from www.  j  a va2  s  .c  om
    providerTemp = new File(tempDir, "provider-temp");
    Assert.assertTrue(providerTemp.mkdir());
    Assert.assertTrue(sparkManagerShell.createNewFile());
    sparkManagerShell.setExecutable(true);
    MockSystemProcess.reset();
    etcDir = new File(tempDir, "etc-src");
    Assert.assertTrue(etcDir.mkdir());
    File sdcProperties = new File(etcDir, "sdc.properties");
    Assert.assertTrue(sdcProperties.createNewFile());
    File log4jPropertyDummyFile = new File(etcDir, SDC_TEST_PREFIX + RuntimeInfo.LOG4J_PROPERTIES);
    Assert.assertTrue(log4jPropertyDummyFile.createNewFile());
    resourcesDir = new File(tempDir, "resources-src");
    Assert.assertTrue(resourcesDir.mkdir());
    Assert.assertTrue((new File(resourcesDir, "dir")).mkdir());
    File resourcesSubDir = new File(resourcesDir, "dir");
    File resourceFile = new File(resourcesSubDir, "core-site.xml");
    resourceFile.createNewFile();
    Assert.assertTrue((new File(resourcesDir, "file")).createNewFile());
    webDir = new File(tempDir, "static-web-dir-src");
    Assert.assertTrue(webDir.mkdir());
    File someWebFile = new File(webDir, "somefile");
    Assert.assertTrue(someWebFile.createNewFile());
    bootstrapLibDir = new File(tempDir, "bootstrap-lib");
    Assert.assertTrue(bootstrapLibDir.mkdir());
    File bootstrapMainLibDir = new File(bootstrapLibDir, "main");
    Assert.assertTrue(bootstrapMainLibDir.mkdirs());
    File bootstrapSparkLibDir = new File(bootstrapLibDir, "spark");
    Assert.assertTrue(bootstrapSparkLibDir.mkdirs());
    File bootstrapMesosLibDir = new File(bootstrapLibDir, "mesos");
    Assert.assertTrue(bootstrapMesosLibDir.mkdirs());
    Assert.assertTrue(new File(bootstrapMainLibDir, "streamsets-datacollector-bootstrap.jar").createNewFile());
    Assert.assertTrue(
            new File(bootstrapSparkLibDir, "streamsets-datacollector-spark-bootstrap.jar").createNewFile());
    Assert.assertTrue(
            new File(bootstrapMesosLibDir, "streamsets-datacollector-mesos-bootstrap.jar").createNewFile());
    List<Config> configs = new ArrayList<Config>();
    configs.add(new Config("clusterSlaveMemory", 512));
    configs.add(new Config("clusterSlaveJavaOpts", ""));
    configs.add(new Config("clusterKerberos", false));
    configs.add(new Config("kerberosPrincipal", ""));
    configs.add(new Config("kerberosKeytab", ""));
    configs.add(new Config("executionMode", ExecutionMode.CLUSTER_YARN_STREAMING));
    pipelineConf = new PipelineConfiguration(PipelineStoreTask.SCHEMA_VERSION, PipelineConfigBean.VERSION,
            UUID.randomUUID(), null, configs, null, new ArrayList<StageConfiguration>(),
            MockStages.getErrorStageConfig(), MockStages.getStatsAggregatorStageConfig());
    pipelineConf
            .setPipelineInfo(new PipelineInfo("name", "desc", null, null, "aaa", null, null, null, true, null));
    File sparkKafkaJar = new File(tempDir, "spark-streaming-kafka-1.2.jar");
    File avroJar = new File(tempDir, "avro-1.7.7.jar");
    File avroMapReduceJar = new File(tempDir, "avro-mapred-1.7.7.jar");
    Assert.assertTrue(sparkKafkaJar.createNewFile());
    Assert.assertTrue(avroJar.createNewFile());
    Assert.assertTrue(avroMapReduceJar.createNewFile());
    classLoader = new URLClassLoader(
            new URL[] { sparkKafkaJar.toURL(), avroJar.toURL(), avroMapReduceJar.toURL() }) {
        public String getType() {
            return ClusterModeConstants.USER_LIBS;
        }
    };
    stageLibrary = MockStages.createStageLibrary(classLoader);
    env = new HashMap<>();
    sourceInfo = new HashMap<>();
    sourceInfo.put(ClusterModeConstants.NUM_EXECUTORS_KEY, "64");
    URLClassLoader emptyCL = new URLClassLoader(new URL[0]);
    RuntimeInfo runtimeInfo = new RuntimeInfo(SDC_TEST_PREFIX, null, Arrays.asList(emptyCL), tempDir);
    sparkProvider = new ClusterProviderImpl(runtimeInfo, null);
}

From source file:org.raml.jaxrs.codegen.core.GeneratorTestCase.java

private void run(final JaxrsVersion jaxrsVersion, final boolean useJsr303Annotations) throws Exception {
    final Set<String> generatedSources = new HashSet<String>();

    final Configuration configuration = new Configuration();
    configuration.setJaxrsVersion(jaxrsVersion);
    configuration.setUseJsr303Annotations(useJsr303Annotations);
    configuration.setOutputDirectory(codegenOutputFolder.getRoot());

    configuration.setBasePackageName(TEST_BASE_PACKAGE);
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/full-config-with-patch.yaml")),
            configuration));//from  w w w. j a v  a2 s.  c o m

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".params");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(
                    getClass().getResourceAsStream("/org/raml/params/param-types-with-repeat.yaml")),
            configuration));

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".integration");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass()
                    .getResourceAsStream("/org/raml/integration/sales-enablement-api-with-collections.yaml")),
            configuration));

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".rules");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/rules/resource-full-ok.yaml")),
            configuration));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(
                    getClass().getResourceAsStream("/org/raml/rules/resource-with-description-ok.yaml")),
            configuration));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/rules/resource-with-uri.yaml")),
            configuration));

    configuration.setBasePackageName(TEST_BASE_PACKAGE + ".schema");
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/schema/valid-xml-global.yaml")),
            configuration));
    generatedSources.addAll(new Generator().run(
            new InputStreamReader(getClass().getResourceAsStream("/org/raml/schema/valid-xml.yaml")),
            configuration));

    // test compile the classes
    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");

    final JavaCompilerSettings settings = compiler.createDefaultSettings();
    settings.setSourceVersion("1.5");
    settings.setTargetVersion("1.5");
    settings.setDebug(true);

    final String[] sources = generatedSources.toArray(EMPTY_STRING_ARRAY);
    System.out.println("Test compiling: " + Arrays.toString(sources));

    final FileResourceReader sourceReader = new FileResourceReader(codegenOutputFolder.getRoot());
    final FileResourceStore classWriter = new FileResourceStore(compilationOutputFolder.getRoot());
    final CompilationResult result = compiler.compile(sources, sourceReader, classWriter,
            Thread.currentThread().getContextClassLoader(), settings);

    assertThat(ToStringBuilder.reflectionToString(result.getErrors(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getErrors(), is(emptyArray()));

    assertThat(ToStringBuilder.reflectionToString(result.getWarnings(), ToStringStyle.SHORT_PREFIX_STYLE),
            result.getWarnings(), is(emptyArray()));

    // test load the classes with Jersey
    final URLClassLoader resourceClassLoader = new URLClassLoader(
            new URL[] { compilationOutputFolder.getRoot().toURI().toURL() });

    final ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(resourceClassLoader);
        final ResourceConfig config = new PackagesResourceConfig(TEST_BASE_PACKAGE);

        assertThat("Found: " + config.getRootResourceClasses(), config.getRootResourceClasses(), hasSize(13));

        // TODO testing: actually send HTTP requests at the resources
    } finally {
        Thread.currentThread().setContextClassLoader(initialClassLoader);
    }
}