Example usage for java.net URLClassLoader newInstance

List of usage examples for java.net URLClassLoader newInstance

Introduction

In this page you can find the example usage for java.net URLClassLoader newInstance.

Prototype

public static URLClassLoader newInstance(final URL[] urls, final ClassLoader parent) 

Source Link

Document

Creates a new instance of URLClassLoader for the specified URLs and parent class loader.

Usage

From source file:org.apache.hadoop.sqoop.util.ClassLoaderStack.java

/**
 * Adds a ClassLoader to the top of the stack that will load from the Jar file
 * of your choice. Returns the previous classloader so you can restore it
 * if need be, later./*from   w w w.  j a v  a 2 s  . c  o  m*/
 *
 * @param jarFile The filename of a jar file that you want loaded into this JVM
 * @param tableClassName The name of the class to load immediately (optional)
 */
public static ClassLoader addJarFile(String jarFile, String testClassName) throws IOException {

    // load the classes from the ORM JAR file into the current VM
    ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
    String urlPath = "jar:file://" + new File(jarFile).getAbsolutePath() + "!/";
    LOG.debug("Attempting to load jar through URL: " + urlPath);
    LOG.debug("Previous classloader is " + prevClassLoader);
    URL[] jarUrlArray = { new URL(urlPath) };
    URLClassLoader cl = URLClassLoader.newInstance(jarUrlArray, prevClassLoader);
    try {
        if (null != testClassName) {
            // try to load a class from the jar to force loading now.
            Class.forName(testClassName, true, cl);
        }
        LOG.info("Loaded jar into current JVM: " + urlPath);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException(
                "Could not load jar " + jarFile + " into JVM. (Could not find class " + testClassName + ".)",
                cnfe);
    }

    LOG.info("Added classloader for jar " + jarFile + ": " + cl);
    Thread.currentThread().setContextClassLoader(cl);
    return prevClassLoader;
}

From source file:org.sonar.batch.RemoteClassLoader.java

public RemoteClassLoader(URL[] urls, ClassLoader parent) {
    ClassLoader parentClassLoader = (parent == null ? RemoteClassLoader.class.getClassLoader() : parent);
    classLoader = URLClassLoader.newInstance(urls, parentClassLoader);
}

From source file:com.cloudera.sqoop.util.ClassLoaderStack.java

/**
 * Adds a ClassLoader to the top of the stack that will load from the Jar
 * file of your choice. Returns the previous classloader so you can restore
 * it if need be, later./*from   w  ww  . ja  v a  2s  .c  o  m*/
 *
 * @param jarFile The filename of a jar file that you want loaded into this
 * JVM.
 * @param testClassName The name of the class to load immediately
 * (optional).
 */
public static ClassLoader addJarFile(String jarFile, String testClassName) throws IOException {

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

    if (null != testClassName) {
        try {
            // Test to see if testClassName is already available. If so, do not
            // load this jar.
            LOG.debug("Checking for existing class: " + testClassName);
            Class.forName(testClassName, true, prevClassLoader);
            LOG.debug("Class is already available. Skipping jar " + jarFile);
            return prevClassLoader;
        } catch (ClassNotFoundException cnfe) {
            // Expected this; we need to load the jar. continue.
        }
    }

    String urlPath = "jar:file://" + new File(jarFile).getAbsolutePath() + "!/";
    LOG.debug("Attempting to load jar through URL: " + urlPath);
    LOG.debug("Previous classloader is " + prevClassLoader);
    URL[] jarUrlArray = { new URL(urlPath) };
    URLClassLoader cl = URLClassLoader.newInstance(jarUrlArray, prevClassLoader);
    try {
        if (null != testClassName) {
            // try to load a class from the jar to force loading now.
            LOG.debug("Testing class in jar: " + testClassName);
            Class.forName(testClassName, true, cl);
        }
        LOG.debug("Loaded jar into current JVM: " + urlPath);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException(
                "Could not load jar " + jarFile + " into JVM. (Could not find class " + testClassName + ".)",
                cnfe);
    }

    LOG.debug("Added classloader for jar " + jarFile + ": " + cl);
    Thread.currentThread().setContextClassLoader(cl);
    return prevClassLoader;
}

From source file:com.teradata.tempto.internal.query.JdbcUtils.java

private static ClassLoader getDriverClassLoader(JdbcConnectivityParamsState jdbcParamsState) {
    try {/*from  w w  w.j av a2s . c  o m*/
        ClassLoader myClassLoader = JdbcUtils.class.getClassLoader();
        if (!jdbcParamsState.jar.isPresent()) {
            return myClassLoader;
        }
        URL jarURL = new File(jdbcParamsState.jar.get()).toURL();
        return URLClassLoader.newInstance(new URL[] { jarURL }, myClassLoader);
    } catch (MalformedURLException e) {
        throw new RuntimeException("could not create classloader for file" + jdbcParamsState.jar.get(), e);
    }
}

From source file:org.wso2.appserver.integration.common.utils.SpringServiceMaker.java

public SpringBeansData getSpringBeanNames(String springContextFilePath, String springBeanFilePath,
        ClassLoader bundleClassLoader) throws AxisFault {

    SpringBeansData data = new SpringBeansData();
    File urlFile = new File(springBeanFilePath);

    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    ClassLoader urlCl;//w  ww.j a va 2  s .  com
    try {
        URL url = urlFile.toURL();
        urlCl = URLClassLoader.newInstance(new URL[] { url }, bundleClassLoader);

        // Save the class loader so that you can restore it later
        Thread.currentThread().setContextClassLoader(urlCl);

        ApplicationContext aCtx = GenericApplicationContextUtil
                .getSpringApplicationContext(springContextFilePath, springBeanFilePath);
        String[] beanDefintions = aCtx.getBeanDefinitionNames();
        data.setBeans(beanDefintions);
    } catch (Exception e) {
        String msg = "Spring cannot load spring beans";
        handleException(msg, e);
    } finally {
        Thread.currentThread().setContextClassLoader(prevCl);
    }
    return data;
}

From source file:net.riccardocossu.autodoc.maven.AutodocMojo.java

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
    try {/*from ww w  .j av  a2  s .c o  m*/
        Set<URL> urls = new HashSet<URL>();
        List<String> elements = project.getCompileClasspathElements();
        for (String element : elements) {
            urls.add(new File(element).toURI().toURL());
        }

        ClassLoader contextClassLoader = URLClassLoader.newInstance(urls.toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader());

        Thread.currentThread().setContextClassLoader(contextClassLoader);

    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error expanding classloader", e);
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Error expanding classloader", e);
    }
    File f = new File(outputDirectory.getAbsolutePath() + "/autodoc");

    if (!f.exists()) {
        f.mkdirs();
    }

    BaseConfiguration conf = new BaseConfiguration();
    conf.addProperty(Engine.CONFIG_PACKAGES, packages);
    conf.addProperty(Engine.CONFIG_INPUT_PLUGINS, inputPlugins);
    conf.addProperty(Engine.CONFIG_OUTPUT_PLUGINS, outputPlugins);
    conf.addProperty(Engine.CONFIG_BASE_OUTPUT_DIR, f.getAbsolutePath());
    Engine eng = new Engine(conf);
    List<PackageContainer> parsedPackages = eng.execute();
    getLog().info(String.format("Parsed %d packages", parsedPackages.size()));
}

From source file:org.wso2.carbon.springservices.ui.SpringServiceMaker.java

public SpringBeansData getSpringBeanNames(String springContextId, String springBeanId,
        ClassLoader bundleClassLoader) throws AxisFault {
    // Manipulation of springContext to ${RepositoryLocation}/spring

    String springContextFilePath = getFilePathFromArchiveId(springContextId);
    String springBeanFilePath = getFilePathFromArchiveId(springBeanId);
    SpringBeansData data = new SpringBeansData();
    data.setSpringContext(springContextId);

    File urlFile = new File(springBeanFilePath);

    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    ClassLoader urlCl;//from  w ww  .  j av  a 2s . c  o  m
    try {
        URL url = urlFile.toURL();
        urlCl = URLClassLoader.newInstance(new URL[] { url }, bundleClassLoader);

        // Save the class loader so that you can restore it later
        Thread.currentThread().setContextClassLoader(urlCl);

        ApplicationContext aCtx = GenericApplicationContextUtil
                .getSpringApplicationContext(springContextFilePath, springBeanFilePath);
        String[] beanDefintions = aCtx.getBeanDefinitionNames();
        data.setBeans(beanDefintions);
    } catch (Exception e) {
        String msg = bundle.getString("spring.cannot.load.spring.beans");
        handleException(msg, e);
    } finally {
        Thread.currentThread().setContextClassLoader(prevCl);
    }
    return data;
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Opens up a ZIP resource, instruments the classes within, and returns a {@link URLClassLoader} object with access to those classes.
 * @param path path of zip resource/*from   ww w  .ja  v a  2s.c  o m*/
 * @return class loader able to access instrumented classes
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if an IO error occurs
 */
public static URLClassLoader loadClassesInZipResourceAndInstrument(String path) throws IOException {
    Validate.notNull(path);

    // Load original class
    Map<String, byte[]> classContents = readZipFromResource(path);

    // Create JAR out of original classes so it can be found by the instrumenter
    List<JarEntry> originalJarEntries = new ArrayList<>(classContents.size());
    for (Entry<String, byte[]> entry : classContents.entrySet()) {
        originalJarEntries.add(new JarEntry(entry.getKey(), entry.getValue()));
    }
    File originalJarFile = createJar(originalJarEntries.toArray(new JarEntry[0]));

    // Get classpath used to run this Java process and addIndividual the jar file we created to it (used by the instrumenter)
    List<File> classpath = getClasspath();
    classpath.add(originalJarFile);

    // Instrument classes and write out new jar
    Instrumenter instrumenter = new Instrumenter(classpath);
    List<JarEntry> instrumentedJarEntries = new ArrayList<>(classContents.size());
    for (Entry<String, byte[]> entry : classContents.entrySet()) {
        byte[] content = entry.getValue();
        if (entry.getKey().endsWith(".class")) {
            content = instrumenter.instrument(content);
        }
        instrumentedJarEntries.add(new JarEntry(entry.getKey(), content));
    }
    File instrumentedJarFile = createJar(instrumentedJarEntries.toArray(new JarEntry[0]));

    // Load up classloader with instrumented jar
    return URLClassLoader.newInstance(new URL[] { instrumentedJarFile.toURI().toURL() },
            TestUtils.class.getClassLoader());
}

From source file:com.cloudera.impala.extdatasource.ExternalDataSourceExecutor.java

/**
 * @param jarPath The local path to the jar containing the ExternalDataSource.
 * @param className The name of the class implementing the ExternalDataSource.
 * @param apiVersionStr The API version the ExternalDataSource implements.
 *                         Must be a valid value of {@link ApiVersion}.
 *///  w w w.j  ava  2  s. c  o  m
public ExternalDataSourceExecutor(String jarPath, String className, String apiVersionStr)
        throws ImpalaException {
    Preconditions.checkNotNull(jarPath);

    apiVersion_ = ApiVersion.valueOf(apiVersionStr);
    if (apiVersion_ == null) {
        throw new ImpalaRuntimeException("Invalid API version: " + apiVersionStr);
    }
    jarPath_ = jarPath;
    className_ = className;

    try {
        URL url = new File(jarPath).toURI().toURL();
        URLClassLoader loader = URLClassLoader.newInstance(new URL[] { url }, getClass().getClassLoader());
        Class<?> c = Class.forName(className, true, loader);
        if (!ArrayUtils.contains(c.getInterfaces(), apiVersion_.getApiInterface())) {
            throw new ImpalaRuntimeException(
                    String.format("Class '%s' does not implement interface '%s' required for API version %s",
                            className, apiVersion_.getApiInterface().getName(), apiVersionStr));
        }
        Constructor<?> ctor = c.getConstructor();
        dataSource_ = (ExternalDataSource) ctor.newInstance();
    } catch (Exception ex) {
        throw new ImpalaRuntimeException(String.format(
                "Unable to load external data " + "source library from path=%s className=%s apiVersion=%s",
                jarPath, className, apiVersionStr), ex);
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.util.CodeGenerationHelper.java

public static ClassLoader compile(File sourceDirectory, List<String> classpath) {

    List<String> fullClasspath = new ArrayList<String>();
    fullClasspath.addAll(classpath);/*w  w  w.ja v  a 2  s.co  m*/
    fullClasspath.add(System.getProperty("java.class.path"));

    new Compiler().compile(sourceDirectory, join(fullClasspath, File.pathSeparatorChar));

    try {
        return URLClassLoader.newInstance(new URL[] { sourceDirectory.toURI().toURL() },
                Thread.currentThread().getContextClassLoader());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

}