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:dip.world.variant.VariantManager.java

/** Returns the URLClassLoader for a given URL, or creates a new one.... */
private static URLClassLoader getClassLoader(URL packageURL) {
    // WARNING: this method is not (itself) threadsafe
    if (packageURL == null) {
        throw new IllegalArgumentException();
    }//  w ww.j av a  2s  .  c o  m

    // see if a classloader for this url already exists (cache of 1)
    if (packageURL.equals(vm.currentPackageURL)) {
        return vm.currentUCL;
    }

    vm.currentUCL = new URLClassLoader(new URL[] { packageURL });
    vm.currentPackageURL = packageURL;
    return vm.currentUCL;
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

private boolean doPostDownload() throws NetworkException {
    boolean b;/*from  w w  w.j  a va  2  s.c o m*/
    PrintStream originalOut = System.out;
    log.setIndeterminate();
    log.setStatusText("running post-download");
    System.setOut(new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            byte[] x = new byte[1];
            x[0] = (byte) b;
            log.print(new String(x));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            log.print(new String(b, off, len));
        }
    }));
    try {
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File(workingDir).toURI().toURL() });
        Class postDownloadClass = urlClassLoader.loadClass("PostDownload");
        Constructor constructor = postDownloadClass.getConstructor();
        Object pd = constructor.newInstance();
        Method method = postDownloadClass.getMethod("invoke", new Class[] { String.class, String.class });
        b = (boolean) method.invoke(pd, config.getInstallDir().getAbsolutePath(), workingDir);
        if (b) {
            showReadMe();
        }
        return b;
    } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException
            | InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoClassDefFoundError ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        log.println("Executing post-download failed.");
    } finally {
        System.setOut(originalOut);
        log.reset();
    }
    return false;
}

From source file:org.codehaus.mojo.webstart.AbstractBaseJnlpMojo.java

private ClassLoader getCompileClassLoader() throws MalformedURLException {
    URL[] urls = new URL[compileClassPath.size()];
    for (int i = 0; i < urls.length; i++) {
        String spec = compileClassPath.get(i).toString();
        URL url = new File(spec).toURI().toURL();
        urls[i] = url;/*  w ww  . j  a v a  2  s .  com*/
    }
    return new URLClassLoader(urls);
}

From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java

/** {@inheritDoc} */
public SiteRenderingContext createContextForSkin(Artifact skin, Map<String, ?> attributes,
        DecorationModel decoration, String defaultWindowTitle, Locale locale)
        throws IOException, RendererException {
    SiteRenderingContext context = createSiteRenderingContext(attributes, decoration, defaultWindowTitle,
            locale);//  www .  ja  v  a 2s  .  com

    context.setSkin(skin);

    ZipFile zipFile = getZipFile(skin.getFile());
    InputStream in = null;

    try {
        if (zipFile.getEntry(SKIN_TEMPLATE_LOCATION) != null) {
            context.setTemplateName(SKIN_TEMPLATE_LOCATION);
            context.setTemplateClassLoader(new URLClassLoader(new URL[] { skin.getFile().toURI().toURL() }));
        } else {
            context.setTemplateName(DEFAULT_TEMPLATE);
            context.setTemplateClassLoader(getClass().getClassLoader());
            context.setUsingDefaultTemplate(true);
        }

        ZipEntry skinDescriptorEntry = zipFile.getEntry(SkinModel.SKIN_DESCRIPTOR_LOCATION);
        if (skinDescriptorEntry != null) {
            in = zipFile.getInputStream(skinDescriptorEntry);

            SkinModel skinModel = new SkinXpp3Reader().read(in);
            context.setSkinModel(skinModel);

            String toolsPrerequisite = skinModel.getPrerequisites() == null ? null
                    : skinModel.getPrerequisites().getDoxiaSitetools();

            Package p = DefaultSiteRenderer.class.getPackage();
            String current = (p == null) ? null : p.getImplementationVersion();

            if (StringUtils.isNotBlank(toolsPrerequisite) && (current != null)
                    && !matchVersion(current, toolsPrerequisite)) {
                throw new RendererException("Cannot use skin: has " + toolsPrerequisite
                        + " Doxia Sitetools prerequisite, but current is " + current);
            }
        }
    } catch (XmlPullParserException e) {
        throw new RendererException("Failed to parse " + SkinModel.SKIN_DESCRIPTOR_LOCATION
                + " skin descriptor from " + skin.getId() + " skin", e);
    } finally {
        IOUtil.close(in);
        closeZipFile(zipFile);
    }

    return context;
}

From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java

/** {@inheritDoc} */
@Deprecated/*from  w w  w. jav a 2  s  .com*/
public SiteRenderingContext createContextForTemplate(File templateFile, Map<String, ?> attributes,
        DecorationModel decoration, String defaultWindowTitle, Locale locale) throws MalformedURLException {
    SiteRenderingContext context = createSiteRenderingContext(attributes, decoration, defaultWindowTitle,
            locale);

    context.setTemplateName(templateFile.getName());
    context.setTemplateClassLoader(
            new URLClassLoader(new URL[] { templateFile.getParentFile().toURI().toURL() }));

    return context;
}

From source file:org.lnicholls.galleon.server.Server.java

private void createAppClassLoader() {
    ArrayList urls = new ArrayList();
    File directory = new File(System.getProperty("apps"));
    if (directory.exists()) {
        // TODO Handle reloading; what if list changes?
        File[] files = directory.listFiles(new FileFilter() {
            public final boolean accept(File file) {
                return !file.isDirectory() && !file.isHidden() && file.getName().toLowerCase().endsWith(".jar");
            }/*from www . j av  a2  s .  c om*/
        });
        if (files != null) {
            for (int i = 0; i < files.length; ++i) {
                try {
                    URL url = files[i].toURI().toURL();
                    urls.add(url);
                    log.debug("Found app: " + url);
                } catch (Exception ex) {
                    // should never happen
                }
            }
        }
    }

    directory = new File(System.getProperty("hme"));
    if (directory.exists()) {
        // TODO Handle reloading; what if list changes?
        File[] files = directory.listFiles(new FileFilter() {
            public final boolean accept(File file) {
                return !file.isDirectory() && !file.isHidden() && file.getName().toLowerCase().endsWith(".jar");
            }
        });
        if (files != null) {
            for (int i = 0; i < files.length; ++i) {
                try {
                    URL url = files[i].toURI().toURL();
                    urls.add(url);
                    log.debug("Found HME app: " + url);
                } catch (Exception ex) {
                    // should never happen
                }
            }
        }
    }

    mAppClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]));
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryFileGenerationTest.java

private Class<?> loadTestProjectClass(String classname, File... srcDirs) throws Exception {
    URL urls[] = new URL[srcDirs.length];
    for (int i = 0; i < srcDirs.length; i++) {
        urls[i] = srcDirs[i].toURI().toURL();
    }// www.j  a va 2  s  .com
    URLClassLoader classloader = new URLClassLoader(urls);
    return classloader.loadClass(classname);
}

From source file:org.apache.openejb.config.DeploymentLoader.java

private void addBeansXmls(final AppModule appModule) {
    final List<URL> urls = appModule.getAdditionalLibraries();
    final URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

    final ArrayList<URL> xmls;
    try {/*  w  w  w  .ja  va  2 s. co  m*/
        xmls = Collections.list(loader.getResources("META-INF/beans.xml"));
    } catch (final IOException e) {

        return;
    }

    final CompositeBeans complete = new CompositeBeans();
    for (final URL url : xmls) {
        if (url == null) {
            continue;
        }
        mergeBeansXml(complete, url);
    }

    if (complete.getDiscoveryByUrl().isEmpty()) {
        return;
    }
    complete.removeDuplicates();

    IAnnotationFinder finder;
    try {
        finder = FinderFactory.createFinder(appModule);
    } catch (final Exception e) {
        finder = new FinderFactory.ModuleLimitedFinder(new FinderFactory.OpenEJBAnnotationFinder(
                new WebappAggregatedArchive(appModule.getClassLoader(), appModule.getAltDDs(), xmls)));
    }
    appModule.setEarLibFinder(finder);

    final EjbModule ejbModule = new EjbModule(appModule.getClassLoader(),
            EAR_SCOPED_CDI_BEANS + appModule.getModuleId(), new EjbJar(), new OpenejbJar());
    ejbModule.setBeans(complete);
    ejbModule.setFinder(finder);
    ejbModule.setEjbJar(new EmptyEjbJar());

    appModule.getEjbModules().add(ejbModule);
}

From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java

/**
 * Build an {@link URLClassLoader} for the given databaseTemplate looking in the templates directory and in the
 * server lib directory, then looks for a driver
 *
 * @param databaseTemplate/*from   ww w  .  j  a  v a  2  s.co m*/
 * @param databaseTemplateDir
 * @param classname Driver class name, defined by {@link #PARAM_DB_DRIVER}
 * @return Driver driver if found, else an Exception must have been raised.
 * @throws IOException
 * @throws FileNotFoundException
 * @throws DatabaseDriverException If there was an error when trying to instantiate the driver.
 * @since 5.6
 */
private Driver lookupDriver(String databaseTemplate, File databaseTemplateDir, String classname)
        throws FileNotFoundException, IOException, DatabaseDriverException {
    File[] files = (File[]) ArrayUtils.addAll( //
            new File(databaseTemplateDir, "lib").listFiles(), //
            serverConfigurator.getServerLibDir().listFiles());
    List<URL> urlsList = new ArrayList<>();
    if (files != null) {
        for (File file : files) {
            if (file.getName().endsWith("jar")) {
                try {
                    urlsList.add(new URL("jar:file:" + file.getPath() + "!/"));
                    log.debug("Added " + file.getPath());
                } catch (MalformedURLException e) {
                    log.error(e);
                }
            }
        }
    }
    URLClassLoader ucl = new URLClassLoader(urlsList.toArray(new URL[0]));
    try {
        return (Driver) Class.forName(classname, true, ucl).newInstance();
    } catch (InstantiationException e) {
        throw new DatabaseDriverException(e);
    } catch (IllegalAccessException e) {
        throw new DatabaseDriverException(e);
    } catch (ClassNotFoundException e) {
        throw new DatabaseDriverException(e);
    }
}

From source file:org.pentaho.di.core.Const.java

/**
 * @return a new ClassLoader/*w ww. j av  a2  s. c  om*/
 */
public static final ClassLoader createNewClassLoader() throws KettleException {
    try {
        // Nothing really in URL, everything is in scope.
        URL[] urls = new URL[] {};
        URLClassLoader ucl = new URLClassLoader(urls);

        return ucl;
    } catch (Exception e) {
        throw new KettleException("Unexpected error during classloader creation", e);
    }
}