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.opoo.press.impl.SiteImpl.java

private ClassLoader createClassLoader(Config config, Theme theme) {
    log.debug("Create site ClassLoader.");

    ClassLoader parent = SiteImpl.class.getClassLoader();
    if (parent == null) {
        parent = ClassLoader.getSystemClassLoader();
    }/*  www .  ja  v a  2s  . c  o m*/

    String sitePluginDir = config.get("plugin_dir");
    String themePluginDir = (String) theme.get("plugin_dir");

    List<File> classPathEntries = new ArrayList<File>(2);

    if (StringUtils.isNotBlank(sitePluginDir)) {
        File sitePlugins = PathUtils.canonical(new File(config.getBasedir(), sitePluginDir));
        addClassPathEntries(classPathEntries, sitePlugins);
    }

    if (StringUtils.isNotBlank(themePluginDir)) {
        File themePlugins = PathUtils.canonical(new File(theme.getPath(), themePluginDir));
        addClassPathEntries(classPathEntries, themePlugins);
    }

    //theme classes
    File themeClasses = new File(theme.getPath(), "target/classes");
    File themeSrc = new File(theme.getPath(), "src");
    if (themeSrc.exists() && themeClasses.exists() && themeClasses.isDirectory()) {
        classPathEntries.add(themeClasses);
    }

    //theme target/plugins
    File themeTargetPlugins = new File(theme.getPath(), "target/plugins");
    if (themeTargetPlugins.exists() && themeTargetPlugins.list().length > 0) {
        addClassPathEntries(classPathEntries, themeTargetPlugins);
    }

    if (classPathEntries.isEmpty()) {
        log.info("No custom classpath entries.");
        return parent;
    }

    URL[] urls = new URL[classPathEntries.size()];

    try {
        for (int i = 0; i < classPathEntries.size(); i++) {
            urls[i] = classPathEntries.get(i).toURI().toURL();
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    return new URLClassLoader(urls, parent);
}

From source file:com.jhash.oimadmin.Utils.java

public static ObjectInputStream getObjectInputStream(InputStream inputStream, URL... jars) throws IOException {
    logger.debug("Creating new Input Stream with input stream {}, URLS {}", inputStream, jars);
    if (jars != null) {
        try {/*from   w  w w . j a va 2 s .  c  o m*/
            ClassLoader urlClassLoader = new URLClassLoader(jars, null);
            return new ObjectInputStream(inputStream) {

                protected Class<?> resolveClass(ObjectStreamClass desc)
                        throws IOException, ClassNotFoundException {
                    logger.debug("Trying to resolve class using description {}", desc);
                    String name = null;
                    try {
                        name = desc.getName();
                        logger.debug("Trying to load class {} using URL Class Loader {}", name, urlClassLoader);
                        Class<?> classValue = Class.forName(name, false, urlClassLoader);
                        logger.debug("Located class as {}", classValue);
                        return classValue;
                    } catch (ClassNotFoundException ex) {
                        logger.debug("Failed to locate Class " + name + ". Invoking parent method.", ex);
                        return super.resolveClass(desc);
                    }
                }
            };
        } catch (Exception exception) {
            logger.warn(
                    "Failed to create Class Loader with URL " + jars
                            + ". Returning standard object input stream with input stream " + inputStream,
                    exception);
            return new ObjectInputStream(inputStream);
        }
    } else {
        logger.debug("Returning standard object input stream since no additional urls were provided.");
        return new ObjectInputStream(inputStream);
    }
}

From source file:net.sourceforge.fullsync.cli.Main.java

@Override
public void launchGui(Injector injector) throws Exception {
    String arch = "x86"; //$NON-NLS-1$
    String osName = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$
    String os = "unknown"; //$NON-NLS-1$
    if (-1 != System.getProperty("os.arch").indexOf("64")) { //$NON-NLS-1$ //$NON-NLS-2$
        arch = "x86_64"; //$NON-NLS-1$
    }//from  www.j  a va 2  s.  com
    if (-1 != osName.indexOf("linux")) { //$NON-NLS-1$
        os = "gtk.linux"; //$NON-NLS-1$
    } else if (-1 != osName.indexOf("windows")) { //$NON-NLS-1$
        os = "win32.win32"; //$NON-NLS-1$
    } else if (-1 != osName.indexOf("mac")) { //$NON-NLS-1$
        os = "cocoa.macosx"; //$NON-NLS-1$
    }
    CodeSource cs = getClass().getProtectionDomain().getCodeSource();
    String libDirectory = cs.getLocation().toURI().toString().replaceAll("^(.*)/[^/]+\\.jar$", "$1/"); //$NON-NLS-1$ //$NON-NLS-2$

    List<URL> jars = new ArrayList<>();
    jars.add(new URL(libDirectory + "net.sourceforge.fullsync-fullsync-assets.jar")); //$NON-NLS-1$
    jars.add(new URL(libDirectory + "net.sourceforge.fullsync-fullsync-ui.jar")); //$NON-NLS-1$
    // add correct SWT implementation to the class-loader
    jars.add(new URL(libDirectory + String.format("org.eclipse.platform-org.eclipse.swt.%s.%s.jar", os, arch))); //$NON-NLS-1$

    // instantiate an URL class-loader with the constructed class-path and load the UI
    URLClassLoader cl = new URLClassLoader(jars.toArray(new URL[jars.size()]), Main.class.getClassLoader());
    Thread.currentThread().setContextClassLoader(cl);
    Class<?> cls = cl.loadClass("net.sourceforge.fullsync.ui.GuiController"); //$NON-NLS-1$
    Method launchUI = cls.getDeclaredMethod("launchUI", Injector.class); //$NON-NLS-1$
    launchUI.invoke(null, injector);
}

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

@Override
public int run(String[] args) throws Exception {
    JobConf conf = new JobConf(getConf());
    int cardinality = Integer.MAX_VALUE;
    boolean cleanLogs = false;
    String listInput = null;//from www  . j a va2 s . c o m

    // @TODO: use commons getopts, org.apache.hadoop.util.GenericOptionsParser used it
    ArrayList<String> other_args = new ArrayList<String>();
    for (int i = 0; i < args.length; ++i) {
        try {
            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 ("-l".equals(args[i])) {
                listInput = args[++i];
            } else if ("-t".equals(args[i])) {
                cardinality = Integer.parseInt(args[++i]);
            } 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 3.");
        return printUsage();
    }

    if (listInput == null || listInput.length() == 0) {
        System.out.println("Need kmer sequence file path!");
        return printUsage();
    }

    long now = System.currentTimeMillis();
    Path listInputPath = new Path(listInput);
    Path listOutputPath = new Path(listInputPath.getParent(), "kmer_" + Long.toHexString(now) + "_tmp");
    LOG.info(String.format("Loading %d sorted k-mers from %s to %s", cardinality, listInputPath.toString(),
            listOutputPath.toString()));
    int num = CompleteCompositionVectorUtils.flattenKmerEntropySequenceFile(conf, cardinality,
            listInputPath.toString(), listOutputPath.toString(), cleanLogs);

    initJob(conf, listOutputPath.toString(), num, other_args.get(0), other_args.get(1), cleanLogs);
    return 0;
}

From source file:org.codehaus.mojo.hibernate3.HibernateExporterMojo.java

/**
 * Returns the an isolated classloader./*from   w ww  . j av  a2 s .  c  o  m*/
 *
 * @return ClassLoader
 * @noinspection unchecked
 */
private ClassLoader getClassLoader() {
    try {
        List classpathElements = project.getCompileClasspathElements();
        classpathElements.add(project.getBuild().getOutputDirectory());
        classpathElements.add(project.getBuild().getTestOutputDirectory());
        URL urls[] = new URL[classpathElements.size()];
        for (int i = 0; i < classpathElements.size(); ++i) {
            urls[i] = new File((String) classpathElements.get(i)).toURL();
        }
        return new URLClassLoader(urls, this.getClass().getClassLoader());
    } catch (Exception e) {
        getLog().debug("Couldn't get the classloader.");
        return this.getClass().getClassLoader();
    }
}

From source file:fr.jayasoft.ivy.Main.java

private static void invoke(Ivy ivy, File cache, ModuleDescriptor md, String[] confs, String mainclass,
        String[] args) {// w  w w.  j  a  v  a 2 s  . c o m
    List urls = new ArrayList();

    try {
        XmlReportParser parser = new XmlReportParser();
        Collection all = new LinkedHashSet();
        for (int i = 0; i < confs.length; i++) {
            Artifact[] artifacts = parser.getArtifacts(md.getModuleRevisionId().getModuleId(), confs[i], cache);
            all.addAll(Arrays.asList(artifacts));
        }
        for (Iterator iter = all.iterator(); iter.hasNext();) {
            Artifact artifact = (Artifact) iter.next();

            urls.add(ivy.getArchiveFileInCache(cache, artifact).toURL());
        }
    } catch (Exception ex) {
        throw new RuntimeException("impossible to build ivy cache path: " + ex.getMessage(), ex);
    }

    URLClassLoader classLoader = new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]),
            Main.class.getClassLoader());

    try {
        Class c = classLoader.loadClass(mainclass);

        Method mainMethod = c.getMethod("main", new Class[] { String[].class });

        // Split up arguments 
        mainMethod.invoke(null, new Object[] { args });
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("Could not find class: " + mainclass, cnfe);
    } catch (SecurityException e) {
        throw new RuntimeException("Could not find main method: " + mainclass, e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Could not find main method: " + mainclass, e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("No permissions to invoke main method: " + mainclass, e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Unexpected exception invoking main method: " + mainclass, e);
    }
}

From source file:azkaban.app.JobManager.java

/**
 * Create a classloader that has all the jars in the local directory on the
 * classpath//from   w  w w.j a va 2s.co m
 * 
 * @param parentClassLoader The parent classloader
 * @param dir The directory to look for jars in
 * @return The classloader
 */
private ClassLoader createClassLoaderForDir(ClassLoader parentClassLoader, File dir) {
    ArrayList<URL> urls = new ArrayList<URL>();
    File[] files = dir.listFiles();
    if (files == null) {
        return parentClassLoader;
    } else {
        for (File f : files) {
            if (f.getName().endsWith(".jar")) {
                try {
                    logger.debug("Adding jar " + f.getName() + " to the classpath");
                    urls.add(f.toURI().toURL());
                } catch (MalformedURLException e) {
                    throw new JobLoadException(e);
                }
            }
        }
        URL[] jars = urls.toArray(new URL[urls.size()]);
        if (jars.length == 0)
            return parentClassLoader;
        else
            return new URLClassLoader(jars, parentClassLoader);
    }
}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * The method performs:/*w w  w . j a v a 2 s. c  o m*/
 * <ul>
 * <li>Compilation of given set of Java source files
 * <li>Construction of custom class loader
 * <li>Creation of JAXB context
 * </ul>
 * 
 * @param packageName
 *            package name to which java classes belong to
 * @param targetDir
 *            the target directory
 * @param generatedJavaSources
 *            list of Java source files which should become a part of JAXB context
 */
private static JAXBContext compileAndLoad(String packageName, File targetDir,
        Collection<String> generatedJavaSources) throws MalformedURLException, JAXBException {
    String[] javaSources = new String[generatedJavaSources.size()];

    int i = 0;
    for (String javaSource : generatedJavaSources) {
        javaSources[i++] = (new File(targetDir, javaSource)).toString();
    }

    StringWriter writer = new StringWriter();

    if (com.sun.tools.javac.Main.compile(javaSources, new PrintWriter(writer)) != 0) {
        fail("javac failed with message: " + writer.toString());
    }

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

    URLClassLoader newClassLoader = new URLClassLoader(
            new URL[] { new File(GENERATED_SOURCES_PREFIX).toURI().toURL() }, currentClassLoader);

    return JAXBContext.newInstance(packageName, newClassLoader);
}

From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java

private void executeAntlrInIsolatedClassLoader(String[] args, Artifact antlrArtifact)
        throws MojoExecutionException {
    try {/*from ww  w.j  a  v a  2 s  .  c om*/
        URLClassLoader classLoader = new URLClassLoader(new URL[] { antlrArtifact.getFile().toURL() },
                ClassLoader.getSystemClassLoader());

        Class toolClass = classLoader.loadClass("antlr.Tool");
        toolClass.getMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { args });
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Unable to resolve antlr:antlr artifact url", e);
    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException("could not locate antlr.Tool class");
    } catch (NoSuchMethodException e) {
        throw new MojoExecutionException("error locating antlt.Tool#main", e);
    } catch (InvocationTargetException e) {
        throw new MojoExecutionException("error perforing antlt.Tool#main", e.getTargetException());
    } catch (IllegalAccessException e) {
        throw new MojoExecutionException("error perforing antlt.Tool#main", e);
    }
}

From source file:org.apache.sling.maven.jspc.JspcMojo.java

/**
 * Initializes the classloader as/if needed for the given compilation
 * context./*w w  w  . j  a  va2 s .  c o m*/
 *
 * @param clctxt The compilation context
 * @throws IOException If an error occurs
 */
private void initClassLoader() throws IOException, DependencyResolutionRequiredException {
    List artifacts = project.getCompileArtifacts();
    URL[] path = new URL[artifacts.size() + 1];
    int i = 0;
    for (Iterator ai = artifacts.iterator(); ai.hasNext();) {
        Artifact a = (Artifact) ai.next();
        path[i++] = a.getFile().toURI().toURL();
    }
    final String targetDirectory = project.getBuild().getOutputDirectory();
    path[path.length - 1] = new File(targetDirectory).toURI().toURL();
    loader = new URLClassLoader(path, this.getClass().getClassLoader());
}