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.codehaus.mojo.gwt.AbstractGwtModuleMojo.java

public GwtModule readModule(String name) throws GwtModuleReaderException {
    String modulePath = name.replace('.', '/') + GWT_MODULE_EXTENSION;
    Collection<String> sourceRoots = getProject().getCompileSourceRoots();
    for (String sourceRoot : sourceRoots) {
        File root = new File(sourceRoot);
        File xml = new File(root, modulePath);
        if (xml.exists()) {
            getLog().debug("GWT module " + name + " found in " + root);
            return readModule(name, xml);
        }/* w  w  w. j  a  v  a  2 s .com*/
    }
    Collection<Resource> resources = (Collection<Resource>) getProject().getResources();
    for (Resource resource : resources) {
        File root = new File(resource.getDirectory());
        File xml = new File(root, modulePath);
        if (xml.exists()) {
            getLog().debug("GWT module " + name + " found in " + root);
            return readModule(name, xml);
        }
    }

    try {
        Collection<File> classpath = getClasspath(Artifact.SCOPE_COMPILE);
        URL[] urls = new URL[classpath.size()];
        int i = 0;
        for (File file : classpath) {
            urls[i++] = file.toURI().toURL();
        }
        InputStream stream = new URLClassLoader(urls).getResourceAsStream(modulePath);
        if (stream != null) {
            return readModule(name, stream);
        }
    } catch (MalformedURLException e) {
        // ignored;
    } catch (MojoExecutionException e) {
        throw new GwtModuleReaderException(e.getMessage(), e);
    }

    throw new GwtModuleReaderException("GWT Module " + name + " not found in project sources or resources.");
}

From source file:org.apache.geode.management.internal.configuration.ClusterConfig.java

public void verifyServer(MemberVM<Server> serverVM) {
    // verify files exist in filesystem
    Set<String> expectedJarNames = this.getJarNames().stream().collect(toSet());

    String[] actualJarFiles = serverVM.getWorkingDir().list((dir, filename) -> filename.contains(".jar"));
    Set<String> actualJarNames = Stream.of(actualJarFiles).map(jar -> jar.replaceAll("\\.v\\d+\\.jar", ".jar"))
            .collect(toSet());/*from ww  w.  j av a  2  s .c  o m*/

    // We will end up with extra jars on disk if they are deployed and then undeployed
    assertThat(expectedJarNames).isSubsetOf(actualJarNames);

    // verify config exists in memory
    serverVM.invoke(() -> {
        Cache cache = GemFireCacheImpl.getInstance();

        // TODO: set compare to fail if there are extra regions
        for (String region : this.getRegions()) {
            assertThat(cache.getRegion(region)).isNotNull();
        }

        if (StringUtils.isNotBlank(this.getMaxLogFileSize())) {
            Properties props = cache.getDistributedSystem().getProperties();
            assertThat(props.getProperty(LOG_FILE_SIZE_LIMIT)).isEqualTo(this.getMaxLogFileSize());
        }

        for (String jar : this.getJarNames()) {
            DeployedJar deployedJar = ClassPathLoader.getLatest().getJarDeployer().findDeployedJar(jar);
            assertThat(deployedJar).isNotNull();
            assertThat(Class.forName(nameOfClassContainedInJar(jar), true,
                    new URLClassLoader(new URL[] { deployedJar.getFileURL() }))).isNotNull();
        }

        // If we have extra jars on disk left over from undeploy, make sure they aren't used
        Set<String> undeployedJarNames = new HashSet<>(actualJarNames);
        undeployedJarNames.removeAll(expectedJarNames);
        for (String jar : undeployedJarNames) {
            System.out.println("Verifying undeployed jar: " + jar);
            DeployedJar undeployedJar = ClassPathLoader.getLatest().getJarDeployer().findDeployedJar(jar);
            assertThat(undeployedJar).isNull();
        }
    });
}

From source file:com.mgmtp.perfload.agent.TransformerTest.java

private Class<?> loadClass(final String fqcn)
        throws IOException, IllegalClassFormatException, MalformedURLException, ClassNotFoundException {
    String internalName = fqcn.replace('.', '/');

    byte[] classBytes = Resources.toByteArray(Resources.getResource(internalName + ".class"));
    byte[] transformedClass = transformer.transform(null, internalName, null, null, classBytes);
    File classFile = new File("tmp/" + internalName + ".class");
    writeByteArrayToFile(classFile, transformedClass);

    URLClassLoader loader = new URLClassLoader(new URL[] { new File("tmp").toURI().toURL() }) {
        /**/*from w ww . j  a  v  a2 s  .  c  o  m*/
         * Loads the class with the specified binary name trying to load it from the local
         * classpath first before delegating to the normal class loading mechanism.
         */
        @Override
        protected synchronized Class<?> loadClass(final String name, final boolean resolve)
                throws ClassNotFoundException {
            // Check if the class has already been loaded
            Class<?> loadedClass = findLoadedClass(name);

            if (loadedClass == null) {
                if (name.startsWith("com.mgmtp.perfload.agent.Test")) {
                    try {
                        // First try to find it locally
                        loadedClass = findClass(name);
                    } catch (ClassNotFoundException e) {
                        // Swallow exception --> the class does not exist locally
                    }
                }
                // If the class is not found locally we delegate to the normal class loading mechanism
                if (loadedClass == null) {
                    loadedClass = super.loadClass(name, resolve);
                }
            }

            if (resolve) {
                resolveClass(loadedClass);
            }
            return loadedClass;
        }
    };
    return loader.loadClass(fqcn);
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Initiaize the VariantManager. //from  w w  w  .  j  a  v  a2 s .co m
 *   <p>
 *   An exception is thrown if no File paths are specified. A "." may be used
 *   to specify th ecurrent directory.
 *   <p>
 *   Loaded XML may be validated if the isValidating flag is set to true.
 *
 */
public static synchronized void init(final List<File> searchPaths, boolean isValidating)
        throws javax.xml.parsers.ParserConfigurationException, NoVariantsException {
    long ttime = System.currentTimeMillis();
    long vptime = ttime;
    Log.println("VariantManager.init()");

    if (searchPaths == null || searchPaths.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (vm != null) {
        // perform cleanup
        vm.variantMap.clear();
        vm.variants = new ArrayList<Variant>();
        vm.currentUCL = null;
        vm.currentPackageURL = null;

        vm.symbolPacks = new ArrayList<SymbolPack>();
        vm.symbolMap.clear();
    }

    vm = new VariantManager();

    // find plugins, create plugin loader
    final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS);

    // setup document builder
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        // this may improve performance, and really only apply to Xerces
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE);
        dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096));
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
    } catch (Exception e) {
        Log.println("VM: Could not set XML feature.", e);
    }

    dbf.setValidating(isValidating);
    dbf.setCoalescing(false);
    dbf.setIgnoringComments(true);

    // setup variant parser
    XMLVariantParser variantParser = new XMLVariantParser(dbf);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME);
        if (variantXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(variantXMLURL.openStream());
                variantParser.parse(is, pluginURL);
                final List<Variant> variants = variantParser.getVariants();

                // add variants; variants with same name (but older versions) are
                // replaced with same-name newer versioned variants
                for (final Variant variant : variants) {
                    addVariant(variant, pluginName, pluginURL);
                }
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars
    Enumeration<URL> enum2 = null;
    ClassLoader cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(VARIANT_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL variantURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(variantURL);

                try {
                    is = new BufferedInputStream(variantURL.openStream());

                    variantParser.parse(is, variantURL);
                    final List<Variant> variants = variantParser.getVariants();

                    // add variants; variants with same name (but older versions) are
                    // replaced with same-name newer versioned variants
                    for (final Variant variant : variants) {
                        addVariant(variant, pluginName, variantURL);
                    }
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, variantURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    }

    // check: did we find *any* variants? Throw an exception.
    if (vm.variantMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No variants found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }

    Log.printTimed(vptime, "VariantManager: variant parsing time: ");

    ///////////////// SYMBOLS /////////////////////////

    // now, parse symbol packs
    XMLSymbolParser symbolParser = new XMLSymbolParser(dbf);

    // find plugins, create plugin loader
    final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs2) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME);
        if (symbolXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(symbolXMLURL.openStream());
                symbolParser.parse(is, pluginURL);
                addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL);
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars      
    enum2 = null;
    cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(SYMBOL_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL symbolURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(symbolURL);

                try {
                    is = new BufferedInputStream(symbolURL.openStream());
                    symbolParser.parse(is, symbolURL);
                    addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL);
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, symbolURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    } // if(isInWebStart)      

    // check: did we find *any* symbol packs? Throw an exception.
    if (vm.symbolMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No SymbolPacks found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }
    Log.printTimed(ttime, "VariantManager: total parsing time: ");
}

From source file:org.jboss.dashboard.ui.panel.PanelProvider.java

public String getResource(String key, Locale l) {
    Locale locale = l != null ? l : LocaleManager.currentLocale();
    Map localeMap = (Map) resourcesCache.get(locale);
    if (localeMap == null)
        resourcesCache.put(locale, localeMap = new HashMap());
    String result = (String) localeMap.get(key);
    if (result != null)
        return result;

    String value = null;/*from   w w w  .j  a v  a 2  s .c  om*/
    boolean resourceFound = false;
    for (int iBundle = 0; iBundle < bundles.size() && !resourceFound; iBundle++) {
        File bundleFile = (File) bundles.get(iBundle);
        try {
            URLClassLoader loader = new URLClassLoader(new URL[] { bundleFile.getParentFile().toURL() });
            ResourceBundle bundle = null;
            String fileName = bundleFile.getName().substring(0, bundleFile.getName().indexOf(".properties"));
            try {
                bundle = ResourceBundle.getBundle(fileName, locale, loader);
            } catch (MissingResourceException e) {
                log.error("Error trying to get the panel driver resource bundle: " + fileName, e);
                continue;
            }

            value = bundle.getString(key);
            if (value != null)
                resourceFound = true;

        } catch (MalformedURLException e) {
            log.error("Error trying to get the panel driver resource bundle: " + bundleFile.getAbsolutePath(),
                    e);
        } catch (MissingResourceException e) {
            // Do nothing. Its possible that the key does not exists in a bundle
        }
    }

    if (value == null) {
        value = properties.getProperty("resource." + key);
    }

    value = value != null ? value : key;
    localeMap.put(key, value);
    return value;
}

From source file:com.jf.javafx.Application.java

/**
 * Get resource bundle./* w  ww. j ava  2  s  .  c o m*/
 *
 * @param rs resource path
 * @return the resource
 * @throws MalformedURLException
 */
public ResourceBundle getResourceBundle(String rs) throws MalformedURLException {
    return ResourceBundle.getBundle(rs, Locale.getDefault(),
            new URLClassLoader(new URL[] { (new File(JF_RESOURCES)).toURL() }));
}

From source file:com.eviware.soapui.DefaultSoapUICore.java

protected void initPlugins() {
    File[] pluginFiles = new File("plugins").listFiles();
    if (pluginFiles != null) {
        for (File pluginFile : pluginFiles) {
            if (!pluginFile.getName().toLowerCase().endsWith("-plugin.jar"))
                continue;

            try {
                log.info("Adding plugin from [" + pluginFile.getAbsolutePath() + "]");

                // add jar to our extension classLoader
                getExtensionClassLoader().addFile(pluginFile);
                JarFile jarFile = new JarFile(pluginFile);

                // look for factories
                JarEntry entry = jarFile.getJarEntry("META-INF/factories.xml");
                if (entry != null)
                    getFactoryRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader);

                // look for listeners
                entry = jarFile.getJarEntry("META-INF/listeners.xml");
                if (entry != null)
                    getListenerRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader);

                // look for actions
                entry = jarFile.getJarEntry("META-INF/actions.xml");
                if (entry != null)
                    getActionRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader);

                // add jar to resource classloader so embedded images can be found with UISupport.loadImageIcon(..)
                UISupport.addResourceClassLoader(new URLClassLoader(new URL[] { pluginFile.toURI().toURL() }));
            } catch (Exception e) {
                SoapUI.logError(e);//from  w  ww  .  ja  v  a 2 s .c  o m
            }
        }
    }
}

From source file:nor.core.Nor.java

private void init(final List<URL> jarUrls) throws IOException {
    LOGGER.entering("init");

    /*//from  ww  w  . j  a va 2  s . c  om
     * Create a proxy server.
     */
    this.server = new ProxyServer(this.handler, this.router);

    final String pluginPath = System.getProperty("nor.plugin");
    if (pluginPath != null) {

        final File dir = new File(pluginPath);
        if (dir.isDirectory()) {

            for (final File f : dir.listFiles()) {

                try {

                    jarUrls.add(f.toURI().toURL());

                } catch (final MalformedURLException e) {

                    LOGGER.catched(Level.WARNING, "init", e);

                }

            }

        }

    }

    /*
     * Load installed plugins
     */
    for (final URL url : jarUrls) {

        final URLClassLoader loader = new URLClassLoader(new URL[] { url });
        for (final Plugin p : ServiceLoader.load(Plugin.class, loader)) {

            final String name = p.getClass().getName();
            if (this.enable(p)) {

                final File common = new File(this.rootConfDir, String.format(ConfigFileTemplate, name));
                final File local = new File(this.localConfDir, String.format(ConfigFileTemplate, name));
                p.init(common, local);

                this.server.attach(p);
                this.plugins.add(p);

                LOGGER.info("init", "Loading a plugin {0}", p.getClass().getName());

            }

        }

    }

    /*
     * Load a routing table.
     */
    final File route = new File(this.localConfDir, "route.conf");
    if (!route.exists()) {

        final InputStream in = this.getClass().getResourceAsStream("route.conf");
        final BufferedReader r = new BufferedReader(new InputStreamReader(in));
        final PrintWriter w = new PrintWriter(new FileWriter(route));

        String buf;
        while ((buf = r.readLine()) != null) {

            w.println(buf);

        }
        w.close();
        r.close();

    }

    final Properties routings = new Properties();
    final Reader rin = new FileReader(route);
    routings.load(rin);
    rin.close();
    for (final Object key : routings.keySet()) {

        final String skey = (String) key;
        this.router.put(skey, routings.getProperty(skey));

    }

    LOGGER.exiting("init");
}

From source file:me.springframework.di.maven.AbstractGeneratorMojo.java

/**
 * Produces the {@link JavaDocBuilder} used to analyze classes and source files.
 * /*from   w w  w.j  a  va2 s .c  o  m*/
 * @return The {@link JavaDocBuilder} used to analyze classes and source files.
 * @throws MojoExecutionException If we fail to produce the {@link JavaDocBuilder}. (Fail
 *             early.)
 */
@SuppressWarnings("unchecked")
private JavaDocBuilder createJavaDocBuilder() throws MojoExecutionException {
    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSourceTree(new File(project.getBuild().getSourceDirectory()));
    // Quick and dirty hack for adding Classloaders with the definitions of
    // classes the sources depend upon.
    try {
        Set<Artifact> artifacts = MavenMetadataSource.createArtifacts(artifactFactory,
                project.getDependencies(), Artifact.SCOPE_RUNTIME, new ArtifactFilter() {

                    public boolean include(Artifact artifact) {
                        return true;
                    }

                }, project);
        List<URL> urls = new ArrayList<URL>();
        for (Artifact artifact : artifacts) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Adding artifact " + artifact.getId());
            }
            if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
                urls.add(artifact.getFile().toURL());
            } else {
                urls.add(new File(localRepository.getBasedir(), localRepository.pathOf(artifact)).toURL());
            }
        }
        URL[] template = new URL[0];
        URLClassLoader loader = new URLClassLoader(urls.toArray(template));
        builder.getClassLibrary().addClassLoader(loader);
    } catch (InvalidDependencyVersionException idve) {
        idve.printStackTrace();
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Malformed artifact URLs.");
    }
    return builder;
}

From source file:org.apache.cactus.integration.maven.CactusScanner.java

/**
 * @param theClasspath the classpaths needed to load the test classes
 * @return a ClassLoader that has all the needed classpaths for loading
 *         the Cactus tests classes//from  w ww  .java2s.c  om
 */
private ClassLoader createClassLoader(Path theClasspath) {
    URL[] urls = new URL[theClasspath.size()];

    try {
        for (int i = 0; i < theClasspath.size(); i++) {
            log.debug(
                    "Adding [" + new File(theClasspath.list()[i]).toURL() + "] " + "to class loader classpath");
            urls[i] = new File(theClasspath.list()[i]).toURL();
        }
    } catch (MalformedURLException e) {
        log.debug("Invalid URL", e);
    }

    return new URLClassLoader(urls);
}