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:org.echocat.locela.api.java.messages.FileAccessorClassLoaderBasedUnitTest.java

@Test
public void testHashCode() throws Exception {
    assertThat(ACCESSOR.hashCode(),//from www .java  2s.c  om
            is(new ClassLoaderBased(FileAccessorClassLoaderBasedUnitTest.class.getClassLoader()).hashCode()));
    assertThat(ACCESSOR.hashCode(), isNot(new ClassLoaderBased(new URLClassLoader(new URL[0])).hashCode()));
}

From source file:de.matzefratze123.heavyspleef.core.flag.FlagRegistry.java

public FlagRegistry(HeavySpleef heavySpleef, File customFlagFolder) {
    this.heavySpleef = heavySpleef;
    this.customFlagFolder = customFlagFolder;
    this.logger = heavySpleef.getLogger();
    this.registeredFlagsMap = new DualKeyHashBiMap<String, Flag, Class<? extends AbstractFlag<?>>>(String.class,
            Flag.class);

    URL url;/*from  www  .ja  va  2s.  c  o m*/

    try {
        url = customFlagFolder.toURI().toURL();
    } catch (MalformedURLException mue) {
        throw new RuntimeException(mue);
    }

    this.classLoader = new URLClassLoader(new URL[] { url });
    this.queuedInitMethods = Lists.newLinkedList();

    loadClasses();
}

From source file:org.apache.pig.test.TestJobControlCompiler.java

@BeforeClass
public static void setupClass() throws Exception {
    // creating a hadoop-site.xml and making it visible to Pig
    // making sure it is at the same location as for other tests to not pick
    // up a conf from a previous test
    File conf_dir = new File("build/classes");
    File hadoopSite = new File(conf_dir, "hadoop-site.xml");
    hadoopSite.deleteOnExit();/* w  ww . j  av a2s.c o m*/
    FileWriter fw = new FileWriter(hadoopSite);
    try {
        fw.write("<?xml version=\"1.0\"?>\n");
        fw.write("<?xml-stylesheet type=\"text/xsl\" href=\"nutch-conf.xsl\"?>\n");
        fw.write("<configuration>\n");
        fw.write("</configuration>\n");
    } finally {
        fw.close();
    }
    // making hadoop-site.xml visible to Pig as it REQUIRES!!! one when
    // running in mapred mode
    Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[] { conf_dir.toURI().toURL() }));
}

From source file:org.jiemamy.entity.io.meta.impl.EntityMetaReaderImpl.java

/**
 * ??//from   ww w  . ja v a2  s .  c o m
 * 
 * @return {@link ClassLoader}
 * @throws IOException ????
 */
private ClassLoader createClassLoader() throws IOException {
    List<URL> urlList = toURLs(entityMetaReaderContext.getClassPathDirs());
    final URLClassLoader urlClassLoader = new URLClassLoader(urlList.toArray(new URL[urlList.size()]));
    return urlClassLoader;
}

From source file:org.javelin.sws.ext.bind.SweJaxbContextFactoryTest.java

@Test
public void nonDefaultClassLoader() throws Exception {
    // parent-last class loader
    // see org.apache.cocoon.servlet.ParanoidClassLoader
    URLClassLoader cl = new URLClassLoader(
            new URL[] { new File("target/test-classes").getCanonicalFile().toURI().toURL() }) {
        @Override/*from   ww w . jav  a  2  s .  co m*/
        protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            Class<?> c = this.findLoadedClass(name);
            if (c == null) {
                try {
                    c = this.findClass(name);
                } catch (ClassNotFoundException e) {
                    if (this.getParent() != null) {
                        c = this.getParent().loadClass(name);
                    } else {
                        throw e;
                    }
                }
            }
            if (resolve)
                this.resolveClass(c);
            return c;
        }
    };

    JAXBContext ctx = SweJaxbContextFactory.createContext("org.javelin.sws.ext.bind.context2", cl);
    @SuppressWarnings("unchecked")
    Map<Class<?>, TypedPattern<?>> patterns = (Map<Class<?>, TypedPattern<?>>) ReflectionTestUtils.getField(ctx,
            "patterns");
    Class<?> mc = null;
    for (Class<?> c : patterns.keySet()) {
        if (c.getName().equals("org.javelin.sws.ext.bind.context2.MyClass2"))
            mc = c;
    }
    assertSame(mc.getClassLoader(), cl);
    Class<?> c1 = ClassUtils.resolveClassName("org.javelin.sws.ext.bind.context2.MyClass2",
            this.getClass().getClassLoader());
    assertFalse(patterns.containsKey(c1));
    Class<?> c2 = ClassUtils.resolveClassName("org.javelin.sws.ext.bind.context2.MyClass2", cl);
    assertTrue(patterns.containsKey(c2));
}

From source file:com.surenpi.autotest.suite.SuiteRunnerLauncher.java

/**
 * ??/*from w  ww .ja v a 2  s . c  o  m*/
 * @param param
 */
private static void compile(RunnerParam param) {
    URL itemUrl = SuiteRunnerLauncher.class.getResource("/");
    if (itemUrl == null) {
        logger.warn("Can not get base url from root. Try use current dir.");

        try {
            itemUrl = new File(".").toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    logger.debug("Base url : {}", itemUrl);

    String protocol = itemUrl.getProtocol();
    if ("file".equals(protocol)) {
        String file = itemUrl.getFile();
        File[] subFiles = new File(file).listFiles(new PageXmlFilter());

        Generator generator = new DefaultXmlCodeGenerator() {
            @Override
            protected void done() {
                super.done();
            }
        };

        for (File pageFile : subFiles) {
            generator.generate(pageFile.getName(), param.compileDstDir);
        }

        JDTUtils utils = new JDTUtils(param.compileDstDir);
        utils.compileAllFile();

        try {
            logger.info("Compile dest dir: {}.", new File(param.compileDstDir).getAbsolutePath());

            ClassLoader loader = new URLClassLoader(
                    new URL[] { new File(param.compileDstDir).toURI().toURL() }) {
                @Override
                protected Class<?> findClass(String s) throws ClassNotFoundException {
                    return super.findClass(s);
                }
            };

            Thread.currentThread().setContextClassLoader(loader);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.googlecode.dex2jar.test.TestUtils.java

public static File dex(List<File> files, File distFile) throws Exception {
    String dxJar = "src/test/resources/dx.jar";
    File dxFile = new File(dxJar);
    if (!dxFile.exists()) {
        throw new RuntimeException("dx.jar?");
    }/* w  w  w.  j av  a  2s  .com*/
    URLClassLoader cl = new URLClassLoader(new URL[] { dxFile.toURI().toURL() });
    Class<?> c = cl.loadClass("com.android.dx.command.Main");
    Method m = c.getMethod("main", String[].class);

    if (distFile == null) {
        distFile = File.createTempFile("dex", ".dex");
    }
    List<String> args = new ArrayList<String>();
    args.addAll(Arrays.asList("--dex", "--no-strict", "--output=" + distFile.getCanonicalPath()));
    for (File f : files) {
        args.add(f.getCanonicalPath());
    }
    m.invoke(null, new Object[] { args.toArray(new String[0]) });
    return distFile;
}

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

private static String getMainClass(URL jar) {
    URL[] jarURLs1 = { jar };//from w  ww.j  a v  a  2  s.  c om
    URLClassLoader classLoader = new URLClassLoader(jarURLs1);
    try {
        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");

            if (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                char[] name;

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

                return new String(name).trim();
            }
        } catch (IOException e) {
            LOGGER.error("Can't load plugin resources", e);
        }
    } finally {
        try {
            classLoader.close();
        } catch (IOException e) {
            LOGGER.error("Error closing plugin finder: {}", e.getMessage());
            LOGGER.trace("", e);
        }
    }

    return null;
}

From source file:org.apache.pig.data.SchemaTupleBackend.java

/**
 * The only information this class needs is a directory of generated code to resolve
 * classes in./*  ww  w  .  j  a  v  a2s  . c o  m*/
 * @param jConf
 * @param directory of generated code
 */
private SchemaTupleBackend(Configuration jConf, boolean isLocal) {
    if (isLocal) {
        String localCodeDir = jConf.get(PigConstants.LOCAL_CODE_DIR);
        if (localCodeDir == null) {
            LOG.debug("No local code dir set in local mode. Aborting code gen resolution.");
            abort = true;
            return;
        }
        codeDir = new File(jConf.get(PigConstants.LOCAL_CODE_DIR));
    } else {
        codeDir = Files.createTempDir();
        codeDir.deleteOnExit();
    }

    try {
        classLoader = new URLClassLoader(new URL[] { codeDir.toURI().toURL() });
    } catch (MalformedURLException e) {
        throw new RuntimeException("Unable to make URLClassLoader for tempDir: " + codeDir.getAbsolutePath());
    }
    this.jConf = jConf;
    this.isLocal = isLocal;
}

From source file:io.fabric8.maven.core.util.MavenUtil.java

private static URLClassLoader createURLClassLoader(Collection<URL> jars) {
    return new URLClassLoader(jars.toArray(new URL[jars.size()]));
}