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.fao.unredd.portal.Config.java

public ResourceBundle getMessages(Locale locale) throws ConfigurationException {
    ResourceBundle bundle = localeBundles.get(locale);
    if (bundle == null) {
        URLClassLoader urlClassLoader;
        try {/*from w ww .j a  v  a 2  s. co  m*/
            urlClassLoader = new URLClassLoader(new URL[] { getTranslationFolder().toURI().toURL() });
        } catch (MalformedURLException e) {
            logger.error("Something is wrong with the configuration directory", e);
            throw new ConfigurationException(e);
        }
        bundle = ResourceBundle.getBundle("messages", locale, urlClassLoader);
        localeBundles.put(locale, bundle);
    }

    return bundle;
}

From source file:io.albraga.namus.OverlaypdfUI.java

private static void load() throws Exception {
    String[] args = new String[3];
    args[0] = "input.pdf";
    args[1] = "overlay.pdf";
    args[2] = "output.pdf";
    URL[] classLoaderUrls = new URL[] { new URL("file:///pdfbox-tools-2.0.4") };
    URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
    Class<?> overlaypdfClass = urlClassLoader.loadClass("org.apache.pdfbox.tools.OverlayPDF");
    Method method = overlaypdfClass.getMethod("main", new Class[] { args.getClass() });
    method.invoke(null, new Object[] { args });
}

From source file:com.google.gdt.eclipse.designer.util.DefaultModuleDescription.java

public ClassLoader getClassLoader() throws Exception {
    if (m_classLoader == null) {
        URL[] urls = getURLs();/*w  w  w .j a  v a2s . c o  m*/
        m_classLoader = new URLClassLoader(urls);
    }
    return m_classLoader;
}

From source file:org.pentaho.hadoop.mapreduce.test.TransMapReduceJobTestFIXME.java

@Test
public void submitJob() throws Exception {

    String[] args = { "hdfs://" + hostname + ":" + hdfsPort + "/junit/wordcount/input",
            "hdfs://" + hostname + ":" + hdfsPort + "/junit/wordcount/output" };

    JobConf conf = new JobConf();
    conf.setJobName("wordcount");

    KettleEnvironment.init();//from  w  ww .  ja  va2s . c om
    TransExecutionConfiguration transExecConfig = new TransExecutionConfiguration();
    TransMeta transMeta = new TransMeta("./test-res/wordcount-mapper.ktr");
    TransConfiguration transConfig = new TransConfiguration(transMeta, transExecConfig);
    conf.set("transformation-map-xml", transConfig.getXML());

    transMeta = new TransMeta("./test-res/wordcount-reducer.ktr");
    transConfig = new TransConfiguration(transMeta, transExecConfig);
    conf.set("transformation-reduce-xml", transConfig.getXML());

    conf.set("transformation-map-input-stepname", "Injector");
    conf.set("transformation-map-output-stepname", "Output");

    conf.set("transformation-reduce-input-stepname", "Injector");
    conf.set("transformation-reduce-output-stepname", "Output");

    conf.setOutputKeyClass(Text.class);
    conf.setOutputValueClass(IntWritable.class);

    File jar = new File("./dist/pentaho-big-data-plugin-TRUNK-SNAPSHOT.jar");

    URLClassLoader loader = new URLClassLoader(new URL[] { jar.toURI().toURL() });

    conf.setMapperClass(
            (Class<? extends Mapper>) loader.loadClass("org.pentaho.hadoop.mapreduce.GenericTransMap"));
    conf.setCombinerClass(
            (Class<? extends Reducer>) loader.loadClass("org.pentaho.hadoop.mapreduce.GenericTransReduce"));
    conf.setReducerClass(
            (Class<? extends Reducer>) loader.loadClass("org.pentaho.hadoop.mapreduce.GenericTransReduce"));

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat(TextOutputFormat.class);

    FileInputFormat.setInputPaths(conf, new Path(args[0]));
    FileOutputFormat.setOutputPath(conf, new Path(args[1]));

    conf.set("fs.default.name", "hdfs://" + hostname + ":" + hdfsPort);
    conf.set("mapred.job.tracker", hostname + ":" + trackerPort);

    conf.setJar(jar.toURI().toURL().toExternalForm());
    conf.setWorkingDirectory(new Path("/tmp/wordcount"));

    JobClient jobClient = new JobClient(conf);
    ClusterStatus status = jobClient.getClusterStatus();
    assertEquals(State.RUNNING, status.getJobTrackerState());

    RunningJob runningJob = jobClient.submitJob(conf);
    System.out.print("Running " + runningJob.getJobName() + "");
    while (!runningJob.isComplete()) {
        System.out.print(".");
        Thread.sleep(500);
    }
    System.out.println();
    System.out.println("Finished " + runningJob.getJobName() + ".");

    FileObject file = fsManager.resolveFile(buildHDFSURL("/junit/wordcount/output/part-00000"));
    String output = IOUtils.toString(file.getContent().getInputStream());
    assertEquals(
            "Bye\t4\nGood\t2\nGoodbye\t1\nHadoop\t2\nHello\t5\nThis\t1\nWorld\t5\nand\t1\ncounting\t1\nextra\t1\nfor\t1\nis\t1\nsome\t1\ntext\t1\nwords\t1\n",
            output);
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.IntrospectUtilTest.java

@Test
public void testInitializeJType() throws Exception {
    // Setup testing directory
    testingdir.ensureEmpty();//from w  w w  .j ava  2s. c  o  m
    File classes = testingdir.getFile("classes");
    MavenTestingUtils.ensureDirExists(classes);
    File srcDir = TestResourceUtil.getResourceDir("botservice-classes");
    FileUtils.copyDirectory(srcDir, classes);

    // Setup temp classloader with testing dir included
    URL urls[] = { classes.toURI().toURL() };
    URLClassLoader cl = new URLClassLoader(urls);
    ClassLoader originalCL = Thread.currentThread().getContextClassLoader();

    try {
        Thread.currentThread().setContextClassLoader(cl);
        JTypeTable jtt = IntrospectUtil.initializeJType("fr.virtuoz.BotService");
        Assert.assertNotNull("Loaded Class should not be null", jtt);
    } finally {
        Thread.currentThread().setContextClassLoader(originalCL);
    }
}

From source file:com.sillelien.dollar.DocTestingVisitor.java

@Override
public void visit(@NotNull VerbatimNode node) {
    if ("java".equals(node.getType())) {
        try {// w  w w  .j a  v  a2  s.c  o m
            String name = "DocTemp" + System.currentTimeMillis();
            File javaFile = new File("/tmp/" + name + ".java");
            File clazzFile = new File("/tmp/" + name + ".class");
            clazzFile.getParentFile().mkdirs();
            FileUtils.write(javaFile,
                    "import com.sillelien.dollar.api.*;\n"
                            + "import static com.sillelien.dollar.api.DollarStatic.*;\n" + "public class "
                            + name + " implements java.lang.Runnable{\n" + "    public void run() {\n"
                            + "        " + node.getText() + "\n" + "    }\n" + "}");
            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            final StandardJavaFileManager jfm = javac.getStandardFileManager(null, null, null);
            JavaCompiler.CompilationTask task;
            DiagnosticListener<JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() {

                @Override
                public void report(Diagnostic diagnostic) {
                    System.out.println(diagnostic);
                    throw new RuntimeException(diagnostic.getMessage(Locale.getDefault()));
                }
            };

            try (FileOutputStream fileOutputStream = FileUtils.openOutputStream(clazzFile)) {
                task = javac.getTask(new OutputStreamWriter(fileOutputStream), jfm, diagnosticListener, null,
                        null, jfm.getJavaFileObjects(javaFile));
            }
            task.call();

            try {
                // Convert File to a URL
                URL url = clazzFile.getParentFile().toURL();
                URL[] urls = new URL[] { url };
                ClassLoader cl = new URLClassLoader(urls);
                Class cls = cl.loadClass(name);
                ((Runnable) cls.newInstance()).run();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            System.out.println("Parsed: " + node.getText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

From source file:de.xplib.xdbm.ui.dialog.FirstStartSetup.java

/**
 * @param aeIn .../*from   w  w w .ja  v a 2  s . c o  m*/
 * @return Does the test fail or run?
 */
private boolean actionPerformedTest(final ActionEvent aeIn) {

    Locale l = this.config.getLocale();

    try {

        String jar = jfField.getText();
        if (!jar.startsWith("file://")) {
            jar = "file://" + jar;
        }

        URLClassLoader ucl = new URLClassLoader(new URL[] { new URL(jar) });

        Class clazz = ucl.loadClass(jtfClass.getText());
        Database db = (Database) clazz.newInstance();

        DatabaseManager.registerDatabase(db);

        String uri = this.jtfDbURI.getText().trim();
        if (uri != null && !uri.equals("")) {
            try {
                Collection coll = DatabaseManager.getCollection(uri);

                coll.close();
            } catch (XMLDBException e1) {
                throw new Exception(
                        MessageManager.getText("setup.dialog.test.error.uri", "text", new Object[] { uri }, l));
            }
        }

        return true;
    } catch (Exception e) {

        String msg = "<html>"
                + MessageManager.getText("setup.dialog.test.error.label", "text", new Object[0], l) + "<br>"
                + e.getMessage() + "</html>";

        String title = MessageManager.getText("setup.dialog.test.error.title", "text", new Object[0], l);

        JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
        return false;
    }
}

From source file:org.apache.hadoop.mapred.IsolationRunner.java

private ClassLoader makeClassLoader(JobConf conf, File workDir) throws IOException {
    List<String> classPaths = new ArrayList<String>();
    // Add jar clas files (includes lib/* and classes/*)
    String jar = conf.getJar();// w  ww  .  j  av a  2  s.  c  o m
    if (jar != null) {
        TaskRunner.appendJobJarClasspaths(conf.getJar(), classPaths);
    }
    // Add the workdir, too.
    classPaths.add(workDir.toString());
    // Note: TaskRunner.run() does more, including DistributedCache files.

    // Convert to URLs
    URL[] urls = new URL[classPaths.size()];
    for (int i = 0; i < classPaths.size(); ++i) {
        urls[i] = new File(classPaths.get(i)).toURL();
    }
    return new URLClassLoader(urls);
}

From source file:org.codehaus.mojo.gwt.webxml.MergeWebXmlMojo.java

private ClassLoader getAnnotationSearchClassLoader() throws ClasspathBuilderException, MalformedURLException {
    Collection<File> classPathFiles = classpathBuilder.buildClasspathList(getProject(), Artifact.SCOPE_COMPILE,
            Collections.<Artifact>emptySet());

    List<URL> urls = new ArrayList<URL>(classPathFiles.size());

    for (File file : classPathFiles) {
        urls.add(file.toURL());// w  w w  .j  ava2  s. c o  m
    }

    URLClassLoader url = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    return url;

}