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.lilyproject.runtime.classloading.ClassLoaderBuilder.java

private static ClassLoader create(List<ClasspathEntry> classpathEntries, ClassLoader parentClassLoader,
        ArtifactRepository repository) throws ArtifactNotFoundException, MalformedURLException {
    List<URL> classpath = new ArrayList<URL>();

    for (ClasspathEntry cpEntry : classpathEntries) {
        File resolvedFile = cpEntry.getArtifactRef().resolve(repository);
        classpath.add(resolvedFile.toURL());
    }/*from  w w w . j  a v  a2  s.  c  om*/

    return new URLClassLoader(classpath.toArray(new URL[classpath.size()]), parentClassLoader);
}

From source file:com.legstar.coxb.gen.CoxbBindingGenerator.java

/**
 * The ant method. Generates COXB binding code.
 */// w ww  .ja va  2  s.  com
public void execute() {
    checkInput();

    ClassLoader previousCl = Thread.currentThread().getContextClassLoader();

    try {
        /*
         * If we are provided with a folder containing JAXB classes, we
         * setup a context class loader that will be able to load them.
         * Otherwise, it is assumed JAXB classes are available from the
         * current class loader.
         */
        if (getJaxbBinDir() != null) {
            URL[] urlBinFiles = new URL[] { getJaxbBinDir().toURI().toURL() };
            URLClassLoader coxbCl = new URLClassLoader(urlBinFiles,
                    CoxbBindingGenerator.class.getClassLoader());
            Thread.currentThread().setContextClassLoader(coxbCl);
        }
        Object jaxbObjectFactory = BindingUtil.newJaxbObjectFactory(getJaxbPackageName());

        for (String jaxbRootClassName : getJaxbRootClassNames()) {

            /* Create an instance of the JAXB root object */
            Object jaxbRootObject = getRootObject(jaxbObjectFactory, jaxbRootClassName);

            /* Create a visitor */
            CoxbGenReflectVisitor visitor = new CoxbGenReflectVisitor(_coxbGenModel, _outputFolder);
            /* Bind the root object to a COXB type */
            CComplexReflectBinding ce = new CComplexReflectBinding(jaxbObjectFactory, jaxbRootObject);
            /* Visit COXB type and all subtypes recursively */
            ce.accept(visitor);

            /* For root objects, generate transformer classes */
            visitor.getWriter().writeHostToJavaTransformer(ce);
            visitor.getWriter().writeJavaToHostTransformer(ce);
            visitor.getWriter().writeTransformers(ce);
            if (isXmlTransformers()) {
                visitor.getWriter().writeHostToXmlTransformer(ce);
                visitor.getWriter().writeXmlToHostTransformer(ce);
                visitor.getWriter().writeXmlTransformers(ce);
            }
            if (isJsonTransformers()) {
                visitor.getWriter().writeHostToJsonTransformer(ce);
                visitor.getWriter().writeJsonToHostTransformer(ce);
                visitor.getWriter().writeJsonTransformers(ce);
            }
        }

    } catch (HostException e) {
        _log.error(CoxbGenWriter.BINDING_GENERATOR_NAME + " failure ", e);
        throw (new BuildException("HostException " + e.getMessage()));
    } catch (CoxbGenException e) {
        _log.error(CoxbGenWriter.BINDING_GENERATOR_NAME + " failure ", e);
        throw new BuildException(e);
    } catch (MalformedURLException e) {
        _log.error(CoxbGenWriter.BINDING_GENERATOR_NAME + " failure ", e);
        throw new BuildException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(previousCl);
    }

}

From source file:io.cloudslang.dependency.impl.services.DependencyServiceImpl.java

@PostConstruct
private void initMaven() throws ClassNotFoundException, NoSuchMethodException, MalformedURLException {
    ClassLoader parentClassLoader = DependencyServiceImpl.class.getClassLoader();
    while (parentClassLoader.getParent() != null) {
        parentClassLoader = parentClassLoader.getParent();
    }// w  w  w.j a  v  a  2 s  .  c  om

    if (isMavenConfigured()) {
        File libDir = new File(mavenHome, "boot");
        if (libDir.exists()) {
            URL[] mavenJarUrls = getUrls(libDir);

            mavenClassLoader = new URLClassLoader(mavenJarUrls, parentClassLoader);
            MAVEN_EXECUTE_METHOD = Class.forName(MAVEN_LAUNCHER_CLASS_NAME, true, mavenClassLoader)
                    .getMethod(MAVEN_LANUCHER_METHOD_NAME, String[].class);
            initMavenLogs();
        }
    }
}

From source file:com.izforge.izpack.integration.UninstallHelper.java

/**
 * Helper to create an isolated class loader using only those classes in the specified uninstall jar.
 *
 * @param uninstallJar the uninstaller jar
 * @return a new class loader/* w  ww  .ja v  a 2  s .  co m*/
 * @throws MalformedURLException
 */
private static ClassLoader getClassLoader(File uninstallJar) throws MalformedURLException {
    // create an isolated class loader for loading classes and resources
    return new URLClassLoader(new URL[] { uninstallJar.toURI().toURL() }, null);
}

From source file:com.comcast.video.dawg.show.plugins.RemotePluginManager.java

/**
 * Stores a jar and finds all the plugin classes in that jar
 * @param jarFile The jar file on the server
 * @throws IOException//from  w w w.java2 s  .  co m
 */
public void storePlugin(File jarFile) throws IOException {
    URL jarUrl = jarFile.toURI().toURL();
    URLClassLoader urlcl = new URLClassLoader(new URL[] { jarUrl }, this.getClass().getClassLoader());
    Reflections ref = new Reflections(
            new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(urlcl)).addClassLoader(urlcl));
    /** Find all classes in the jar that implement a KeyInputPlugin and add them to our plugin list */
    Set<Class<? extends KeyInputPlugin>> plugins = ref.getSubTypesOf(KeyInputPlugin.class);
    for (Class<? extends KeyInputPlugin> clazz : plugins) {
        try {
            KeyInputPlugin<?> kip = clazz.newInstance();
            PluginConfiguration config = kip.getConfigClass().newInstance();
            PluginAndConfig<KeyInput, ?> pac = new PluginAndConfig(kip, config, jarFile);
            LOGGER.info("Adding plugin class '" + clazz.getName() + "' for remote " + kip.getRemoteType());
            if (this.plugins.containsKey(kip.getRemoteType())) {
                /** Remove the old remote plugin */
                File oldJar = this.plugins.get(kip.getRemoteType()).getJarFile();
                FileUtils.deleteQuietly(oldJar);
            }
            this.plugins.put(kip.getRemoteType(), pac);
            /** Updates the mapping to the UI remote */
            this.remoteManager.addRemoteTypeToRemote(kip.getRemoteUiId(), kip.getRemoteType());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.DynamicHapiLoaderUtils.java

private static URLClassLoader getHackedUrlClassLoader() {
    // HACKED_HAPI_51_JAR = "/hapi_libs/fork/hapi_51_fork.jar";

    URL[] urls = new URL[2];
    urls[0] = DynamicHapiLoaderUtils.class.getResource("/hapi_libs/fork/hacked_patched_hapi-0.5.1.jar");
    urls[1] = DynamicHapiLoaderUtils.class.getResource("/hapi_libs/fork/commons-logging-1.1.1.jar");

    if (logger.isDebugEnabled()) {
        try {/*from   ww w  . jav a 2 s  .  c o  m*/
            logger.debug("jar:hacked hapi, size: " + urls[0].openStream().available());
        } catch (IOException e) {
            logger.error("Unexpected Error", e);
        }
    }

    URLClassLoader classLoader = new URLClassLoader(urls, null);
    return (classLoader);
}

From source file:org.icesquirrel.Squirrel.java

public void init() throws IOException {
    classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = Squirrel.class.getClassLoader();
    }/*from  w w w .  ja  va 2s. c om*/

    switch (mode) {
    case RUN:
    case ON_DEMAND:
    case JIT:
        // In RUN, ON_DEMAND or JIT modes, create a class loader for the
        // current
        // output directory
        LOG.info(String.format("Adding %s to the class path.", output));
        URL[] urls = new URL[] { output.toURI().toURL() };
        classLoader = new URLClassLoader(urls, classLoader);
        break;
    default:
        break;
    }
}

From source file:net.java.javabuild.ExecuteMojo.java

private void initClassLoader() throws MojoExecutionException {
    try {//from  w w  w .j a  v a  2s .c o  m
        List<String> testClasspathElements = project.getTestClasspathElements();
        URL[] urls = new URL[testClasspathElements.size() + 1];
        urls[0] = new File(classesPath).toURI().toURL();
        int i = 1;
        for (Iterator<String> iterator = testClasspathElements.iterator(); iterator.hasNext();) {
            String jar = iterator.next();
            urls[i] = new File(jar).toURI().toURL();
            i++;
        }
        classLoader = new URLClassLoader(urls, this.getClass().getClassLoader());
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to initalize project classpath", e);
    }
}

From source file:com.kjt.service.common.SoafwTesterMojo.java

public void execute() throws MojoExecutionException {

    String flg = System.getProperty("soafw.tester.gen", "false");

    if ("false".equalsIgnoreCase(flg)) {
        this.getLog().info("soafw.tester.gen: " + artifactId);
        return;//from w w  w . j  ava 2s  .  c om
    }

    this.getLog().info("start unit test file gen&check: " + artifactId);

    this.getLog().info("" + this.getPluginContext());

    basedPath = basedir.getAbsolutePath();

    project = (MavenProject) getPluginContext().get("project");

    this.getLog().info("ProjectName: " + project.getName());

    try {
        List<String> classpaths = project.getCompileClasspathElements();
        URL[] runtimeUrls = new URL[classpaths.size() + 1];
        for (int i = 0; i < classpaths.size(); i++) {
            String classpath = (String) classpaths.get(i);
            runtimeUrls[i] = new File(classpath).toURI().toURL();
        }
        // ?classpath
        runtimeUrls[classpaths
                .size()] = new File(basedPath + File.separator + "target" + File.separator + "test-classes")
                        .toURI().toURL();

        this.cl = new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader());
    } catch (Exception e2) {
    }

    String classesDir = basedPath + File.separator + "target" + File.separator + "classes";

    int length = classesDir.length() + 1;

    load(classesDir, new File(classesDir), length);// map
    /**
     * 
     */
    String testClassesDir = basedPath + File.separator + "target" + File.separator + "test-classes";

    length = testClassesDir.length() + 1;

    load(testClassesDir, new File(testClassesDir), length);// map

    int size = defines.size();
    String[] definesArray = new String[size];
    defines.keySet().toArray(definesArray);

    if (size == 0) {
        this.getLog().info("??");
    }

    for (int i = 0; i < size; i++) {
        boolean hasmethod = false;
        if (!testImpl.containsKey(definesArray[i] + "Test")) {
            genTest(basedPath, definesArray[i]);
        } else {// ?
            appendTest(definesArray[i]);
        }
    }

    for (int i = 0; i < size; i++) {
        if (testImpl.containsKey(definesArray[i] + "Test")) {
            defines.remove(definesArray[i]);
        }
    }

    this.getLog().info("&???" + defines);

    this.getLog().info("???||?" + testImpl);

    this.getLog().error("??" + errorImpl);
}

From source file:de.knurt.fam.plugin.DefaultPluginResolver.java

private void initPlugins() {
    File pluginDirectory = new File(FamConnector.me().getPluginDirectory());
    if (pluginDirectory.exists() && pluginDirectory.isDirectory() && pluginDirectory.canRead()) {
        File[] files = pluginDirectory.listFiles();
        ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
        for (File file : files) {
            if (file.isFile() && file.getName().toLowerCase().endsWith("jar")) {
                JarFile jar = null;
                try {
                    jar = new JarFile(file.getAbsoluteFile().toString());
                    Enumeration<JarEntry> jarEntries = jar.entries();
                    while (jarEntries.hasMoreElements()) {
                        JarEntry entry = jarEntries.nextElement();
                        if (entry.getName().toLowerCase().endsWith("class")) {
                            String className = entry.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                            // @SuppressWarnings("resource") // classLoader must not be closed, getting an "IllegalStateException: zip file closed" otherwise
                            URLClassLoader classLoader = new URLClassLoader(new URL[] { file.toURI().toURL() },
                                    currentThreadClassLoader);
                            Class<?> cl = classLoader.loadClass(className);
                            if (this.isPlugin(cl)) {
                                Plugin plugin = (Plugin) cl.newInstance();
                                this.plugins.add(plugin);
                            }/*www  .ja va2  s .com*/
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091426l);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091424l);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091425l);
                } catch (IOException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091351l);
                } finally {
                    try {
                        jar.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        for (Plugin plugin : this.plugins) {
            boolean found = false;
            if (this.implementz(plugin.getClass(), RegisterSubmission.class)) {
                if (found == true) {
                    throw new PluginConfigurationException("Found more than one RegisterSubmission classes");
                    // TODO #19 supply a solution Ticket
                }
                this.registerSubmission = (RegisterSubmission) plugin;
                found = true;
            }
        }
        for (Plugin plugin : this.plugins) {
            plugin.start();
        }
    }
    // search plugin
    if (this.registerSubmission == null) {
        this.registerSubmission = new DefaultRegisterSubmission();
    }
}