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.apache.pig.impl.util.JarManager.java

/**
 * Creates a Classloader based on the passed jarFile and any extra jar files.
 *
 * @param jarFile/*from ww  w.  j  a v  a  2 s . c o  m*/
 *            the jar file to be part of the newly created Classloader. This jar file plus any
 *            jars in the extraJars list will constitute the classpath.
 * @return the new Classloader.
 * @throws MalformedURLException
 */
static ClassLoader createCl(String jarFile, PigContext pigContext) throws MalformedURLException {
    int len = pigContext.extraJars.size();
    int passedJar = jarFile == null ? 0 : 1;
    URL urls[] = new URL[len + passedJar];
    if (jarFile != null) {
        urls[0] = new URL("file:" + jarFile);
    }
    for (int i = 0; i < pigContext.extraJars.size(); i++) {
        urls[i + passedJar] = new URL("file:" + pigContext.extraJars.get(i));
    }
    return new URLClassLoader(urls, PigMapReduce.class.getClassLoader());
}

From source file:org.jboss.wise.core.client.impl.reflection.BasicWSDynamicClientImpl.java

/**
 * @param outputDir file//from   w  ww . j ava  2  s.co m
 * @throws WiseRuntimeException wapper of runtime exception
 */

private synchronized void initClassLoader(File outputDir) throws WiseRuntimeException {
    try {

        final ClassLoader oldLoader = SecurityActions.getContextClassLoader();
        // we need a custom classloader pointing the temp dir
        // in order to load the generated classes on the fly
        this.setClassLoader(new URLClassLoader(new URL[] { outputDir.toURI().toURL(), }, oldLoader));

        try {
            SecurityActions.setContextClassLoader(this.getClassLoader());
            Class<?> clazz = JavaUtils.loadJavaType("javax.xml.ws.spi.Provider", this.getClassLoader());
            clazz.getMethod("provider", new Class[] {}).invoke(null, new Object[] {});
        } finally {
            // restore the original classloader
            SecurityActions.setContextClassLoader(oldLoader);
        }
    } catch (Exception e) {
        throw new WiseRuntimeException(
                "Error occurred while setting up classloader for generated class in directory: " + outputDir,
                e);
    }
}

From source file:io.smartspaces.workbench.project.test.IsolatedClassloaderJavaTestRunner.java

/**
 * Detect and run any JUnit test classes.
 *
 * @param testCompilationFolder//from  ww  w .  j  av  a  2  s  .  com
 *          folder where the test classes were compiled
 * @param jarDestinationFile
 *          the jar that was built
 * @param extension
 *          the Java project extension for the project (can be {@code null})
 * @param context
 *          the build context
 *
 * @throws SmartSpacesException
 *           the tests failed
 */
private void runJavaUnitTests(File testCompilationFolder, File jarDestinationFile,
        JvmProjectExtension extension, ProjectTaskContext context) throws SmartSpacesException {
    List<File> classpath = getClasspath(context, extension, jarDestinationFile, testCompilationFolder);

    List<URL> urls = new ArrayList<>();
    for (File classpathElement : classpath) {
        try {
            urls.add(classpathElement.toURL());
        } catch (MalformedURLException e) {
            context.getWorkbenchTaskContext().getWorkbench().getLog().error(String.format(
                    "Error while adding %s to the unit test classpath", classpathElement.getAbsolutePath()), e);
        }
    }

    URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
            context.getWorkbenchTaskContext().getWorkbench().getBaseClassLoader());

    runTestsInIsolation(testCompilationFolder, classLoader, context);
}

From source file:com.moss.schematrax.SchemaUpdater.java

/**
 * For use when the updates are not already on the classpath
 * @param updatesLocation the location of the schematrax file to load
 *///from w  ww . ja v  a 2  s  .c  om
public SchemaUpdater(URL updatesLocation) throws Exception {
    URL[] locations = { updatesLocation };
    updatesLoader = new URLClassLoader(locations, null);

    String classpathRoot = "";
    InputStream propertiesData = updatesLoader.getResourceAsStream("schematrax.properties");
    if (propertiesData != null) {
        Properties props = new Properties();
        props.load(propertiesData);
        String root = props.getProperty("classpath-root");
        if (root != null)
            classpathRoot = root;
    }

    init(classpathRoot);
}

From source file:interactivespaces.workbench.project.test.JavaTestRunner.java

/**
 * Detect and run any JUnit test classes.
 *
 * @param testCompilationFolder// w  w w . j  a  va 2 s . c  o  m
 *          folder where the test classes were compiled
 * @param jarDestinationFile
 *          the jar that was built
 * @param projectType
 *          the project type
 * @param extension
 *          the Java project extension for the project (can be {@code null})
 * @param context
 *          the build context
 *
 * @return {@code true} if all tests passed
 */
private boolean runJavaUnitTests(File testCompilationFolder, File jarDestinationFile,
        JavaProjectType projectType, JavaProjectExtension extension, ProjectTaskContext context) {
    List<File> classpath = Lists.newArrayList();
    classpath.add(jarDestinationFile);
    classpath.add(testCompilationFolder);
    projectType.getProjectClasspath(true, context, classpath, extension, context.getWorkbenchTaskContext());

    List<URL> urls = Lists.newArrayList();
    for (File classpathElement : classpath) {
        try {
            urls.add(classpathElement.toURL());
        } catch (MalformedURLException e) {
            context.getWorkbenchTaskContext().getWorkbench().getLog().error(String.format(
                    "Error while adding %s to the unit test classpath", classpathElement.getAbsolutePath()), e);
        }
    }

    URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
            context.getWorkbenchTaskContext().getWorkbench().getBaseClassLoader());

    return runTestsInIsolation(testCompilationFolder, classLoader, context);
}

From source file:interactivespaces.workbench.project.test.IsolatedClassloaderJavaTestRunner.java

/**
 * Detect and run any JUnit test classes.
 *
 * @param testCompilationFolder//from  w  w  w .  ja  v  a  2 s .c  o m
 *          folder where the test classes were compiled
 * @param jarDestinationFile
 *          the jar that was built
 * @param projectType
 *          the project type
 * @param extension
 *          the Java project extension for the project (can be {@code null})
 * @param context
 *          the build context
 *
 * @throws InteractiveSpacesException
 *           the tests failed
 */
private void runJavaUnitTests(File testCompilationFolder, File jarDestinationFile, JavaProjectType projectType,
        JavaProjectExtension extension, ProjectTaskContext context) throws InteractiveSpacesException {
    List<File> classpath = Lists.newArrayList();
    classpath.add(jarDestinationFile);
    classpath.add(testCompilationFolder);
    projectType.getProjectClasspath(true, context, classpath, extension, context.getWorkbenchTaskContext());

    List<URL> urls = Lists.newArrayList();
    for (File classpathElement : classpath) {
        try {
            urls.add(classpathElement.toURL());
        } catch (MalformedURLException e) {
            context.getWorkbenchTaskContext().getWorkbench().getLog().error(String.format(
                    "Error while adding %s to the unit test classpath", classpathElement.getAbsolutePath()), e);
        }
    }

    URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
            context.getWorkbenchTaskContext().getWorkbench().getBaseClassLoader());

    runTestsInIsolation(testCompilationFolder, classLoader, context);
}

From source file:android.databinding.tool.reflection.java.JavaAnalyzer.java

public static void initForTests() {
    String androidHome = loadAndroidHome();
    if (Strings.isNullOrEmpty(androidHome) || !new File(androidHome).exists()) {
        throw new IllegalStateException(
                "you need to have ANDROID_HOME set in your environment" + " to run compiler tests");
    }/*  w  w  w  .j  ava  2s .c om*/
    File androidJar = new File(androidHome + "/platforms/android-21/android.jar");
    if (!androidJar.exists() || !androidJar.canRead()) {
        throw new IllegalStateException("cannot find android jar at " + androidJar.getAbsolutePath());
    }
    // now load android data binding library as well

    try {
        ClassLoader classLoader = new URLClassLoader(new URL[] { androidJar.toURI().toURL() },
                ModelAnalyzer.class.getClassLoader());
        new JavaAnalyzer(classLoader);
    } catch (MalformedURLException e) {
        throw new RuntimeException("cannot create class loader", e);
    }

    SdkUtil.initialize(8, new File(androidHome));
}

From source file:com.hortonworks.minicluster.InJvmContainerExecutor.java

/**
 * Will launch containers within the same JVM as this Container Executor. It
 * will do so by: - extracting Container's class name and program arguments
 * from the launch script (e.g., launch_container.sh) - Creating an isolated
 * ClassLoader for each container - Calling doLaunchContainer(..) method to
 * launch Container/*ww w  .  j a v  a 2s.c o  m*/
 */
private int doLaunch(Container container, Path containerWorkDir) {
    Map<String, String> environment = container.getLaunchContext().getEnvironment();
    EnvironmentUtils.putAll(environment);

    Set<URL> additionalClassPathUrls = this.filterAndBuildUserClasspath(container);

    ExecJavaCliParser javaCliParser = this.createExecCommandParser(containerWorkDir.toString());

    UserGroupInformation.setLoginUser(null);
    try {
        // create Isolated Class Loader for each container and set it as context
        // class loader
        URLClassLoader containerCl = new URLClassLoader(
                additionalClassPathUrls.toArray(additionalClassPathUrls.toArray(new URL[] {})), null);
        Thread.currentThread().setContextClassLoader(containerCl);
        String containerLauncher = javaCliParser.getMain();
        Class<?> containerClass = Class.forName(containerLauncher, true, containerCl);
        Method mainMethod = containerClass.getMethod("main", new Class[] { String[].class });
        mainMethod.setAccessible(true);
        String[] arguments = javaCliParser.getMainArguments();

        this.doLaunchContainer(containerClass, mainMethod, arguments);
    } catch (Exception e) {
        logger.error("Failed to launch container " + container, e);
        container.handle(new ContainerDiagnosticsUpdateEvent(container.getContainerId(), e.getMessage()));
        return -1;
    } finally {
        logger.info("Removing symlinks");
        this.cleanUp();
    }
    return 0;
}

From source file:com.streamsets.pipeline.maven.rbgen.RBGenMojo.java

private ClassLoader getProjectClassLoader() throws Exception {
    List<String> cp = project.getCompileClasspathElements();
    URL[] urls = new URL[cp.size()];
    for (int i = 0; i < cp.size(); i++) {
        urls[i] = new File(cp.get(i)).toURI().toURL();
    }/*ww  w . j  a va2 s. c om*/
    return new URLClassLoader(urls, this.getClass().getClassLoader());
}

From source file:SerialVersionUID.java

/**
 * Create a Map<String, ClassVersionInfo> for the jboss dist jars.
 * //from   w ww. j av a 2  s  .c o  m
 * @param j2eeHome -
 *          the j2ee ri dist root directory
 * @return Map<String, ClassVersionInfo>
 * @throws IOException
 */
public static Map generateRISerialVersionUIDReport(File j2eeHome) throws IOException {
    // Obtain the jars from the /lib
    HashSet jarFiles = new HashSet();
    File lib = new File(j2eeHome, "lib");
    buildJarSet(lib, jarFiles);
    URL[] cp = new URL[jarFiles.size()];
    jarFiles.toArray(cp);
    ClassLoader parent = Thread.currentThread().getContextClassLoader();
    URLClassLoader completeClasspath = new URLClassLoader(cp, parent);

    TreeMap classVersionMap = new TreeMap();
    Iterator jarIter = jarFiles.iterator();
    while (jarIter.hasNext()) {
        URL jar = (URL) jarIter.next();
        try {
            generateJarSerialVersionUIDs(jar, classVersionMap, completeClasspath, "javax");
        } catch (IOException e) {
            log.info("Failed to process jar: " + jar);
        }
    }

    return classVersionMap;
}