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:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

@Test
public void testDiamondOptimizedHierarchyCompilation() {

    OntoModel results = factory.buildModel("diamond",
            ResourceFactory.newClassPathResource("ontologies/diamondProp2.manchester.owl"),
            DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED));

    assertTrue(results.isHierarchyConsistent());

    compiler = new OntoModelCompiler(results, folder.getRoot());

    // ****** Stream the java interfaces
    boolean javaOut = compiler.streamJavaInterfaces(true);

    assertTrue(javaOut);/*from   ww  w .j av  a2 s .c  o m*/

    // ****** Stream the XSDs, the JaxB customizations abd the persistence configuration
    boolean xsdOut = compiler.streamXSDsWithBindings(true);

    assertTrue(xsdOut);
    File f = new File(compiler.getMetaInfDir() + File.separator + results.getDefaultPackage() + ".xsd");
    try {
        Document dox = parseXML(f, true);

        NodeList types = dox.getElementsByTagName("xsd:complexType");
        assertEquals(10, types.getLength());

        NodeList elements = dox.getElementsByTagName("xsd:element");
        assertEquals(12 + 14, elements.getLength());
    } catch (Exception e) {
        fail(e.getMessage());
    }

    showDirContent(folder);

    File b = new File(compiler.getMetaInfDir() + File.separator + results.getDefaultPackage() + ".xjb");
    try {
        Document dox = parseXML(b, false);

        NodeList types = dox.getElementsByTagName("bindings");
        assertEquals(28, types.getLength());
    } catch (Exception e) {
        fail(e.getMessage());
    }

    showDirContent(folder);

    // ****** Generate sources
    boolean mojo = compiler.mojo(
            Arrays.asList("-extension", "-Xjaxbindex", "-Xannotate", "-Xinheritance", "-XtoString",
                    "-Xcopyable", "-Xmergeable", "-Xvalue-constructor", "-Xfluent-api", "-Xkey-equality",
                    "-Xsem-accessors", "-Xdefault-constructor", "-Xmetadata", "-Xinject-code"),
            OntoModelCompiler.MOJO_VARIANTS.JPA2);

    assertTrue(mojo);

    File klass = new File(compiler.getXjcDir().getPath() + File.separator
            + results.getDefaultPackage().replace(".", File.separator) + File.separator + "BottomImpl.java");
    printSourceFile(klass, System.out);

    showDirContent(folder);

    // ****** Do compile sources
    List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler.doCompile();

    boolean success = true;
    for (Diagnostic diag : diagnostics) {
        System.out.println("ERROR : " + diag);
        if (diag.getKind() == Diagnostic.Kind.ERROR) {
            success = false;
        }
    }
    assertTrue(success);

    showDirContent(folder);

    try {
        parseXML(new File(compiler.getBinDir() + "/META-INF/" + "persistence.xml"), true);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        ClassLoader urlKL = new URLClassLoader(new URL[] { compiler.getBinDir().toURI().toURL() },
                Thread.currentThread().getContextClassLoader());

        testPersistenceWithInstance(urlKL, "org.jboss.drools.semantics.diamond2.Bottom", results.getName());

    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        fail(e.getMessage());
    }

}

From source file:com.greenpepper.maven.runner.CommandLineRunner.java

private void runClassicRunner(List<String> args) throws Exception {
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    initMavenEmbedder(originalClassLoader);

    resolveProject();/* ww  w. ja  v a  2 s .  c o  m*/

    ProjectFileResolver.MavenGAV mavenGAV = resolvers.getMavenGAV();
    if (StringUtils.isNotEmpty(mavenGAV.getClassifier())) {
        Artifact artifactWithClassifier = embedder.createArtifactWithClassifier(project.getGroupId(),
                project.getArtifactId(), project.getVersion(), mavenGAV.getPackaging(),
                mavenGAV.getClassifier());
        resolve(artifactWithClassifier, artifacts);
    } else {
        resolveScopedArtifacts();

        resolveMavenPluginArtifact();

        resolveProjectArtifact();
    }

    URL[] classpaths = buildRuntimeClasspaths();

    URLClassLoader urlClassLoader = new URLClassLoader(classpaths, originalClassLoader);

    Thread.currentThread().setContextClassLoader(urlClassLoader);

    ReflectionUtils.setDebugEnabled(urlClassLoader, isDebug);
    ReflectionUtils.setSystemOutputs(urlClassLoader, logger.getOut(), System.err);

    Class<?> mainClass = urlClassLoader.loadClass("com.greenpepper.runner.Main");

    logger.debug("Invoking: com.greenpepper.runner.Main " + StringUtils.join(args, ' '));
    ReflectionUtils.invokeMain(mainClass, args);

    Thread.currentThread().setContextClassLoader(originalClassLoader);

}

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

public static void loadPluginJar(File file) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null) {
        cl = PluginUtil.class.getClassLoader();
    }//from w  ww. j  av a 2 s . com

    URLClassLoader classLoader = new URLClassLoader(new URL[] { file.toURI().toURL() }, cl);

    Thread.currentThread().setContextClassLoader(classLoader);
}

From source file:com.marklogic.contentpump.ContentPump.java

/**
 * Set class loader for current thread and for Confifguration based on 
 * Hadoop home./*from w w w .  j  a  v a  2  s .co  m*/
 * 
 * @param hdConfDir Hadoop home directory
 * @param conf Hadoop configuration
 * @throws MalformedURLException
 */
private static void setClassLoader(File hdConfDir, Configuration conf) throws Exception {
    ClassLoader parent = conf.getClassLoader();
    URL url = hdConfDir.toURI().toURL();
    URL[] urls = new URL[1];
    urls[0] = url;
    ClassLoader classLoader = new URLClassLoader(urls, parent);
    Thread.currentThread().setContextClassLoader(classLoader);
    conf.setClassLoader(classLoader);
}

From source file:com.asakusafw.compiler.bootstrap.BatchCompilerDriver.java

static boolean compile(File outputDirectory, Class<? extends BatchDescription> batchDescription,
        String packageName, Location hadoopWorkLocation, File compilerWorkDirectory,
        List<File> linkingResources, List<URL> pluginLibraries) {
    assert outputDirectory != null;
    assert batchDescription != null;
    assert packageName != null;
    assert hadoopWorkLocation != null;
    assert compilerWorkDirectory != null;
    assert linkingResources != null;
    try {/*w  w  w. ja v  a  2s  .c o  m*/
        BatchDriver analyzed = BatchDriver.analyze(batchDescription);
        if (analyzed.hasError()) {
            for (String diagnostic : analyzed.getDiagnostics()) {
                LOG.error(diagnostic);
            }
            return false;
        }

        String batchId = analyzed.getBatchClass().getConfig().name();
        ClassLoader serviceLoader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> {
            URLClassLoader loader = new URLClassLoader(pluginLibraries.toArray(new URL[pluginLibraries.size()]),
                    BatchCompilerDriver.class.getClassLoader());
            return loader;
        });
        DirectBatchCompiler.compile(analyzed.getDescription(), packageName, hadoopWorkLocation,
                new File(outputDirectory, batchId), new File(compilerWorkDirectory, batchId), linkingResources,
                serviceLoader, FlowCompilerOptions.load(System.getProperties()));
        return true;
    } catch (Exception e) {
        LOG.error(MessageFormat.format(Messages.getString("BatchCompilerDriver.errorFailedToCompile"), //$NON-NLS-1$
                batchDescription.getName()), e);
        return false;
    }
}

From source file:org.ligoj.app.resource.plugin.LigojPluginListenerTest.java

@Test
public void getPluginClassLoader() {
    final LigojPluginsClassLoader pluginsClassLoader = Mockito.mock(LigojPluginsClassLoader.class);
    try (ThreadClassLoaderScope scope = new ThreadClassLoaderScope(
            new URLClassLoader(new URL[0], pluginsClassLoader))) {
        Assertions.assertNotNull(resource.getPluginClassLoader());
    }//w  w w .  j  a  v  a 2 s .c o  m
}

From source file:org.perfcake.util.ObjectFactory.java

/**
 * Gets a dedicated class loader for loading plugins.
 *
 * @return Plugin class loader./* w w  w .j  a  v  a 2 s .c o m*/
 */
protected static ClassLoader getPluginClassLoader() {
    if (pluginClassLoader == null) {
        final ClassLoader currentClassLoader = ObjectFactory.class.getClassLoader();
        final String pluginsDirProp = Utils.getProperty(PerfCakeConst.PLUGINS_DIR_PROPERTY);
        if (pluginsDirProp == null) {
            return currentClassLoader;
        }

        final File pluginsDir = new File(pluginsDirProp);
        final File[] plugins = pluginsDir.listFiles(new FileExtensionFilter(".jar"));

        if ((plugins == null) || (plugins.length == 0)) {
            return currentClassLoader;
        }

        final URL[] pluginURLs = new URL[plugins.length];
        for (int i = 0; i < plugins.length; i++) {
            try {
                pluginURLs[i] = plugins[i].toURI().toURL();
            } catch (final MalformedURLException e) {
                log.warn(String.format("Cannot resolve path to plugin '%s', skipping this file", plugins[i]));
            }
        }

        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                pluginClassLoader = new URLClassLoader(pluginURLs, currentClassLoader);
                return null;
            }
        });
    }

    return pluginClassLoader;
}

From source file:hu.ppke.itk.nlpg.purepos.cli.PurePos.java

/**
 * Loads the latest Humor jar file and create an analyzer instance
 * //ww w .j a va 2 s.c om
 * @return analyzer instance
 */
protected static IMorphologicalAnalyzer loadHumor()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException {
    String humorPath = System.getProperty("humor.path");
    if (humorPath == null)
        throw new ClassNotFoundException("Humor jar file is not present");

    File dir = new File(humorPath);

    File[] candidates = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return filename.endsWith(".jar") && filename.startsWith("humor-");
        }
    });

    Arrays.sort(candidates);

    @SuppressWarnings("deprecation")
    URL humorURL = candidates[candidates.length - 1].toURL();

    URLClassLoader myLoader = new URLClassLoader(new URL[] { humorURL }, PurePos.class.getClassLoader());
    Class<?> humorClass = Class.forName("hu.ppke.itk.nlpg.purepos.morphology.HumorAnalyzer", true, myLoader);
    return (IMorphologicalAnalyzer) humorClass.newInstance();
}

From source file:org.mitre.ccv.mapred.InvertKmerProbabilities.java

@Override
public int run(String[] args) throws Exception {
    JobConf conf = new JobConf(getConf());
    boolean cleanLogs = false;

    List<String> other_args = new ArrayList<String>();
    for (int i = 0; i < args.length; ++i) {
        try {//from  w ww . ja  v a 2  s .c  o  m
            if ("-m".equals(args[i])) {
                conf.setNumMapTasks(Integer.parseInt(args[++i]));
            } else if ("-r".equals(args[i])) {
                conf.setNumReduceTasks(Integer.parseInt(args[++i]));
            } else if ("-c".equals(args[i])) {
                cleanLogs = true;
            } else if ("-libjars".equals(args[i])) {
                conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf));

                URL[] libjars = FileUtils.getLibJars(conf);
                if (libjars != null && libjars.length > 0) {
                    // Add libjars to client/tasks classpath
                    conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));
                    // Adds libjars to our classpath
                    Thread.currentThread().setContextClassLoader(
                            new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader()));
                }
            } else {
                other_args.add(args[i]);
            }
        } catch (NumberFormatException except) {
            System.out.println("ERROR: Integer expected instead of " + args[i]);
            return printUsage();
        } catch (ArrayIndexOutOfBoundsException except) {
            System.out.println("ERROR: Required parameter missing from " + args[i - 1]);
            return printUsage();
        }
    }
    // Make sure there are exactly 2 parameters left.
    if (other_args.size() != 2) {
        System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 2.");
        return printUsage();
    }

    return initJob(conf, other_args.get(0), other_args.get(1), cleanLogs);

}

From source file:jp.co.tis.gsp.tools.dba.mojo.GenerateEntity.java

/**
 * ??// w  ww .j a  v a 2  s .c  om
 */
private void executeGenerateEntity() {
    Dialect dialect = DialectFactory.getDialect(url, driver);
    DialectUtil.setDialect(dialect);
    final GenerateEntityCommand command = new GenerateEntityCommand();
    command.setSchemaName(schema);
    command.setOverwrite(true);
    command.setApplyDbCommentToJava(true);
    command.setEntityPackageName(entityPackageName);
    command.setIgnoreTableNamePattern(ignoreTableNamePattern);
    command.setEntityTemplateFileName(entityTemplate);
    command.setGenDialectClassName(genDialectClassName);
    command.setShowTableName(true);
    if (!user.equals(schema)) {
        command.setShowSchemaName(true);
    }
    command.setGenerationType(dialect.getGenerationType());
    command.setFactoryClassName(GspFactoryImpl.class.getName());
    command.setUseAccessor(useAccessor);
    command.setShowColumnName(true);
    command.setJavaFileDestDir(javaFileDestDir);
    command.setTemplateFilePrimaryDir(templateFilePrimaryDir);
    command.setAllocationSize(allocationSize);

    final List<URL> urlList = new ArrayList<URL>();
    try {
        urlList.add(diconDir.toURI().toURL());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(
                "URL(" + diconDir + ") ?????????", e);
    }

    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    final URLClassLoader newLoader = new URLClassLoader(urlList.toArray(new URL[urlList.size()]), oldLoader);
    try {
        Thread.currentThread().setContextClassLoader(newLoader);

        command.setRootPackageName(rootPackage);

        final CommandInvoker invoker = ReflectUtil.newInstance(CommandInvoker.class,
                CommandInvokerImpl.class.getName());
        invoker.invoke(command);
    } finally {
        Thread.currentThread().setContextClassLoader(oldLoader);
    }
}