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:com.huawei.streaming.cql.DriverContext.java

/**
 * classpathjar//from www. ja  v  a  2  s  . co m
 *
 * @param pathsToRemove jar
 * @throws IOException jar
 */
private static void removeFromClassPath(String[] pathsToRemove) throws IOException {
    Thread curThread = Thread.currentThread();
    URLClassLoader loader = (URLClassLoader) curThread.getContextClassLoader();
    Set<URL> newPath = new HashSet<URL>(Arrays.asList(loader.getURLs()));

    if (pathsToRemove != null) {
        for (String onestr : pathsToRemove) {
            if (StringUtils.indexOf(onestr, FILE_PREFIX) == 0) {
                onestr = StringUtils.substring(onestr, CQLConst.I_7);
            }

            URL oneurl = (new File(onestr)).toURI().toURL();
            newPath.remove(oneurl);
        }
    }

    loader = new URLClassLoader(newPath.toArray(new URL[0]));
    curThread.setContextClassLoader(loader);
}

From source file:org.mule.tck.junit4.AbstractMuleTestCase.java

/**
 * Reads the mule-exclusion file for the current test class and
 * @param test//from   w  ww . j  a  v a 2  s.  c o m
 */
protected boolean isTestIncludedInExclusionFile(AbstractMuleTestCase test) {
    boolean result = false;

    final String testName = test.getClass().getName();
    try {
        // We find the physical classpath root URL of the test class and
        // use that to find the correct resource. Works fine everywhere,
        // regardless of classloaders. See MULE-2414
        URL classUrl = ClassUtils.getClassPathRoot(test.getClass());
        URLClassLoader tempClassLoader = new URLClassLoader(new URL[] { classUrl });
        URL fileUrl = tempClassLoader.getResource("mule-test-exclusions.txt");
        if (fileUrl != null) {
            InputStream in = null;
            try {
                in = fileUrl.openStream();

                // this iterates over all lines in the exclusion file
                Iterator<?> lines = IOUtils.lineIterator(in, "UTF-8");

                // ..and this finds non-comments that match the test case name
                result = IteratorUtils.filteredIterator(lines, new Predicate() {
                    @Override
                    public boolean evaluate(Object object) {
                        return StringUtils.equals(testName, StringUtils.trimToEmpty((String) object));
                    }
                }).hasNext();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (IOException ioex) {
        // ignore
    }

    return result;
}

From source file:org.panthercode.arctic.core.reflect.ReflectionUtils.java

/**
 * Creates a list of all classes from a specific jar file.
 *
 * @param path filepath to jar file//from  w  ww.ja  va2 s .  c  o m
 * @return Returns a list with all classes in jar file. If jar file doesn't contain any class, the list will be empty.
 * @throws IOException              Is thrown if an error occurs while reading the .jar file.
 * @throws ClassNotFoundException   Is thrown if the class is not found.
 * @throws IllegalArgumentException Is thrown if path is null.
 */
public static List<Class<?>> extractClassesFromJar(String path)
        throws IOException, ClassNotFoundException, IllegalArgumentException {
    ArgumentUtils.assertNotNull(path, "path");

    List<Class<?>> classList = new ArrayList<>();

    URL[] urlArray = { new URL("jar:file:" + path + "!/") };
    URLClassLoader classLoader = new URLClassLoader(urlArray);

    for (String className : ReflectionUtils.extractClassNamesFromJar(path)) {
        classList.add(classLoader.loadClass(className));
    }

    return classList;
}

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

@Test
public void testLoadClass() throws Exception {
    // Setup testing directory
    testingdir.ensureEmpty();/*from  w  w  w.jav  a  2s  .co  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);
        // Execute test
        Class<?> clazz = IntrospectUtil.loadClass("fr.virtuoz.BotService");
        Assert.assertNotNull("Loaded Class should not be null", clazz);
    } finally {
        Thread.currentThread().setContextClassLoader(originalCL);
    }
}

From source file:org.sahli.asciidoc.confluence.publisher.maven.plugin.AsciidocConfluencePublisherMojo.java

private List<Resource> templateResources() throws IOException {
    Artifact artifact = this.pluginArtifactMap
            .get("org.sahli.asciidoc.confluence.publisher:asciidoc-confluence-publisher-converter");
    URLClassLoader templateClassLoader = new URLClassLoader(new URL[] { artifact.getFile().toURI().toURL() });
    PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(
            new DefaultResourceLoader(templateClassLoader));

    return asList(pathMatchingResourcePatternResolver.getResources(TEMPLATES_CLASSPATH_PATTERN));
}

From source file:org.rhq.plugins.jbossas.JBossASTomcatDiscoveryComponent.java

private String getVersion(File jbossWebDir) throws IOException {
    boolean pre42 = jbossWebDir.getName().startsWith(EMBEDDED_TOMCAT_PRE42_DIR);
    String jarFileName = (pre42) ? "catalina.jar" : "jbossweb.jar";
    File jarFile = new File(jbossWebDir, jarFileName);
    ClassLoader classLoader = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
    InputStream stream = classLoader.getResourceAsStream(SERVER_INFO_PROPERTIES_RESOURCE);
    String version = null;//from w ww.j av  a  2  s  .c o m
    if (stream != null) {
        Properties serverInfo = new Properties();
        serverInfo.load(stream);
        stream.close();
        version = serverInfo.getProperty("server.number");
        if (version == null) {
            String info = serverInfo.getProperty("server.info");
            if (info != null) {
                version = info.substring(info.indexOf('/') + 1);
            }
        }
    }

    if (version == null) {
        version = "?";
        log.error("Failed to determine version of Embedded Tomcat server located at '" + jbossWebDir + "'");
    }

    return version;
}

From source file:fi.jumi.actors.maven.GenerateEventStubsMojo.java

private static Class<?> loadFromClasspath(String className, File[] classpath) throws ClassNotFoundException {
    try {/* w w  w . j a  v  a2 s  .c  om*/
        URL[] urls = FileUtils.toURLs(classpath);
        URLClassLoader loader = new URLClassLoader(urls);
        return loader.loadClass(className);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.dex2jar.tools.DecryptStringCmd.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();//  w w w . j a  v  a2 s.com
        return;
    }

    File jar = new File(remainingArgs[0]);
    if (!jar.exists()) {
        System.err.println(jar + " is not exists");
        return;
    }
    if (methodName == null || methodOwner == null) {
        System.err.println("Please set --decrypt-method-owner and --decrypt-method-name");
        return;
    }

    if (output == null) {
        if (jar.isDirectory()) {
            output = new File(jar.getName() + "-decrypted.jar");
        } else {
            output = new File(FilenameUtils.getBaseName(jar.getName()) + "-decrypted.jar");
        }
    }

    if (output.exists() && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        return;
    }

    System.err.println(jar + " -> " + output);

    List<String> list = new ArrayList<String>();
    if (classpath != null) {
        list.addAll(Arrays.asList(classpath.split(";|:")));
    }
    list.add(jar.getAbsolutePath());
    URL[] urls = new URL[list.size()];
    for (int i = 0; i < list.size(); i++) {
        urls[i] = new File(list.get(i)).toURI().toURL();
    }
    final Method jmethod;
    final String targetMethodDesc;
    try {
        Class<?> argType = "string".equals(type) ? String.class : int.class;
        URLClassLoader cl = new URLClassLoader(urls);
        jmethod = cl.loadClass(methodOwner).getDeclaredMethod(methodName, argType);
        jmethod.setAccessible(true);
        targetMethodDesc = Type.getMethodDescriptor(jmethod);
    } catch (Exception ex) {
        System.err.println("can't load method: String " + methodOwner + "." + methodName + "(" + type + ")");
        ex.printStackTrace();
        return;
    }
    final String methodOwnerInternalType = this.methodOwner.replace('.', '/');
    final OutHandler fo = FileOut.create(output, true);
    try {
        new FileWalker().withStreamHandler(new StreamHandler() {

            @Override
            public void handle(boolean isDir, String name, StreamOpener current, Object nameObject)
                    throws IOException {
                if (isDir || !name.endsWith(".class")) {
                    fo.write(isDir, name, current == null ? null : current.get(), nameObject);
                    return;
                }

                ClassReader cr = new ClassReader(current.get());
                ClassNode cn = new ClassNode();
                cr.accept(cn, ClassReader.EXPAND_FRAMES);

                for (Object m0 : cn.methods) {
                    MethodNode m = (MethodNode) m0;
                    if (m.instructions == null) {
                        continue;
                    }
                    AbstractInsnNode p = m.instructions.getFirst();
                    while (p != null) {
                        if (p.getOpcode() == Opcodes.INVOKESTATIC) {
                            MethodInsnNode mn = (MethodInsnNode) p;
                            if (mn.name.equals(methodName) && mn.desc.equals(targetMethodDesc)
                                    && mn.owner.equals(methodOwnerInternalType)) {
                                AbstractInsnNode q = p.getPrevious();
                                AbstractInsnNode next = p.getNext();
                                if (q.getOpcode() == Opcodes.LDC) {
                                    LdcInsnNode ldc = (LdcInsnNode) q;
                                    tryReplace(m.instructions, p, q, jmethod, ldc.cst);
                                } else if (q.getType() == AbstractInsnNode.INT_INSN) {
                                    IntInsnNode in = (IntInsnNode) q;
                                    tryReplace(m.instructions, p, q, jmethod, in.operand);
                                } else {
                                    switch (q.getOpcode()) {
                                    case Opcodes.ICONST_M1:
                                    case Opcodes.ICONST_0:
                                    case Opcodes.ICONST_1:
                                    case Opcodes.ICONST_2:
                                    case Opcodes.ICONST_3:
                                    case Opcodes.ICONST_4:
                                    case Opcodes.ICONST_5:
                                        int x = ((InsnNode) q).getOpcode() - Opcodes.ICONST_0;
                                        tryReplace(m.instructions, p, q, jmethod, x);
                                        break;
                                    }
                                }
                                p = next;
                                continue;
                            }
                        }
                        p = p.getNext();
                    }
                }

                ClassWriter cw = new ClassWriter(0);
                cn.accept(cw);
                fo.write(false, cr.getClassName() + ".class", cw.toByteArray(), null);
            }
        }).walk(jar);
    } finally {
        IOUtils.closeQuietly(fo);
    }
}

From source file:net.sf.clirr.cli.Clirr.java

private void run(String[] args) {
    Options options = defineOptions();//from  ww  w . j av a 2  s .  co m

    CommandLine cmdline = parseCommandLine(args, options);

    String oldPath = cmdline.getOptionValue('o');
    String newPath = cmdline.getOptionValue('n');
    String oldClassPath = cmdline.getOptionValue("ocp");
    String newClassPath = cmdline.getOptionValue("ncp");
    String style = cmdline.getOptionValue('s', "text");
    String outputFileName = cmdline.getOptionValue('f');
    String[] includePkgs = cmdline.getOptionValues('i');
    boolean showAll = cmdline.hasOption('a');
    boolean showPkg = cmdline.hasOption('p');

    if ((oldPath == null) || (newPath == null)) {
        printUsage(options, System.err);
        System.exit(-1);
    }

    Checker checker = new Checker();
    if (showAll) {
        checker.getScopeSelector().setScope(Scope.PRIVATE);
    } else if (showPkg) {
        checker.getScopeSelector().setScope(Scope.PACKAGE);
    }

    ClassSelector classSelector;
    if ((includePkgs != null) && (includePkgs.length > 0)) {
        classSelector = new ClassSelector(ClassSelector.MODE_IF);
        for (int i = 0; i < includePkgs.length; ++i) {
            classSelector.addPackageTree(includePkgs[i]);
        }
    } else {
        // a selector that selects everything
        classSelector = new ClassSelector(ClassSelector.MODE_UNLESS);
    }

    DiffListener diffListener = null;
    if (style.equals("text")) {
        try {
            diffListener = new PlainDiffListener(outputFileName);
        } catch (IOException ex) {
            System.err.println("Invalid output file name.");
        }
    } else if (style.equals("xml")) {
        try {
            diffListener = new XmlDiffListener(outputFileName);
        } catch (IOException ex) {
            System.err.println("Invalid output file name.");
        }
    } else {
        System.err.println("Invalid style option. Must be one of 'text', 'xml'.");
        printUsage(options, System.err);
        System.exit(-1);
    }

    File[] origClassPathEntries = pathToFileArray(oldPath);
    File[] newClassPathEntries = pathToFileArray(newPath);

    checker.addDiffListener(diffListener);

    try {
        ClassLoader loader1 = new URLClassLoader(convertFilesToURLs(pathToFileArray(oldClassPath)));
        ClassLoader loader2 = new URLClassLoader(convertFilesToURLs(pathToFileArray(newClassPath)));

        DefaultTypeArrayBuilderFactory tabFactory = new DefaultTypeArrayBuilderFactory();

        TypeArrayBuilder tab1 = tabFactory.build();
        TypeArrayBuilder tab2 = tabFactory.build();

        final JavaType[] origClasses = tab1.createClassSet(origClassPathEntries, loader1, classSelector);

        final JavaType[] newClasses = tab2.createClassSet(newClassPathEntries, loader2, classSelector);

        checker.reportDiffs(origClasses, newClasses);

        System.exit(0);
    } catch (CheckerException ex) {
        System.err.println("Unable to complete checks: " + ex.getMessage());
        System.exit(1);
    } catch (MalformedURLException ex) {
        System.err.println("Unable to create classloader for 3rd party classes: " + ex.getMessage());
        System.err.println("old classpath: " + oldClassPath);
        System.err.println("new classpath: " + newClassPath);
        System.exit(1);
    } catch (RuntimeException ex) {
        System.err.println("Unable to complete checks: " + ex.toString());
        Throwable cause = ex.getCause();
        if (cause != null) {
            System.err.println("  caused by : " + cause.toString());
        }
        System.exit(2);
    }
}

From source file:com.streamsets.datacollector.execution.runner.cluster.TestClusterRunner.java

@Before
public void setup() throws Exception {
    executorService = new SafeScheduledExecutorService(2, "ClusterRunnerExecutor");
    emptyCL = new URLClassLoader(new URL[0]);
    tempDir = Files.createTempDir();
    System.setProperty(RuntimeInfo.TRANSIENT_ENVIRONMENT, "true");
    System.setProperty("sdc.testing-mode", "true");
    sparkManagerShell = new File(tempDir, "_cluster-manager");
    Assert.assertTrue(tempDir.delete());
    Assert.assertTrue(tempDir.mkdir());/*from  w  w  w  .j a  v  a 2 s.com*/
    Assert.assertTrue(sparkManagerShell.createNewFile());
    sparkManagerShell.setExecutable(true);
    MockSystemProcess.isAlive = false;
    MockSystemProcess.output.clear();
    MockSystemProcess.error.clear();
    runtimeInfo = new RuntimeInfo("dummy", null, Arrays.asList(emptyCL), tempDir);
    clusterProvider = new MockClusterProvider();
    conf = new Configuration();
    pipelineStateStore = new CachePipelineStateStore(new FilePipelineStateStore(runtimeInfo, conf));
    attributes = new HashMap<>();
    stageLibraryTask = MockStages.createStageLibrary(emptyCL);
    pipelineStoreTask = new FilePipelineStoreTask(runtimeInfo, stageLibraryTask, pipelineStateStore,
            new LockCache<String>());
    pipelineStoreTask.init();
    pipelineStoreTask.create("admin", NAME, "some desc", false);
    //Create an invalid pipeline
    PipelineConfiguration pipelineConfiguration = pipelineStoreTask.create("user2",
            TestUtil.HIGHER_VERSION_PIPELINE, "description2", false);
    PipelineConfiguration mockPipelineConf = MockStages
            .createPipelineConfigurationSourceProcessorTargetHigherVersion();
    mockPipelineConf.getConfiguration().add(new Config("executionMode", ExecutionMode.CLUSTER_BATCH.name()));
    mockPipelineConf.getConfiguration().add(new Config("shouldRetry", "true"));
    mockPipelineConf.getConfiguration().add(new Config("retryAttempts", "3"));
    mockPipelineConf.setUuid(pipelineConfiguration.getUuid());
    pipelineStoreTask.save("user2", TestUtil.HIGHER_VERSION_PIPELINE, "0", "description", mockPipelineConf);

    clusterHelper = new ClusterHelper(new MockSystemProcessFactory(), clusterProvider, tempDir,
            sparkManagerShell, emptyCL, emptyCL, null);
    setExecModeAndRetries(ExecutionMode.CLUSTER_BATCH);
}