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.sonar.core.plugins.PluginFileExtractor.java

private void completeDeprecatedMetadata(DefaultPluginMetadata metadata) throws IOException {
    String mainClass = metadata.getMainClass();
    File pluginFile = metadata.getFile();
    try {//from   w w w . jav  a 2 s  . c  o m
        // copy file in a temp directory because Windows+Oracle JVM Classloader lock the JAR file
        File tempFile = File.createTempFile(pluginFile.getName(), null);
        FileUtils.copyFile(pluginFile, tempFile);

        URLClassLoader pluginClassLoader = URLClassLoader.newInstance(new URL[] { tempFile.toURI().toURL() },
                getClass().getClassLoader());
        Plugin pluginInstance = (Plugin) pluginClassLoader.loadClass(mainClass).newInstance();
        metadata.setKey(PluginKeyUtils.sanitize(pluginInstance.getKey()));
        metadata.setDescription(pluginInstance.getDescription());
        metadata.setName(pluginInstance.getName());

    } catch (Exception e) {
        throw new RuntimeException("The metadata main class can not be created. Plugin file="
                + pluginFile.getName() + ", class=" + mainClass, e);
    }
}

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

public static ClassLoader toClassLoader(Collection<String> classPaths, ClassLoader parent)
        throws MalformedURLException {
    Set<URL> dependencies = new HashSet<URL>();
    for (String classPath : classPaths) {
        File dependency = new File(classPath);
        dependencies.add(dependency.toURI().toURL());
    }/*from w  w  w  .  j av a  2 s.co m*/
    ClassLoader classLoader = URLClassLoader.newInstance(dependencies.toArray(new URL[dependencies.size()]),
            parent);
    return classLoader;
}

From source file:Which4J.java

/**
 * Iterate over the system classpath defined by "java.class.path" searching
 * for all occurrances of the given class name.
 * /* w  ww .  jav a  2  s .c  o m*/
 * @param classname the fully qualified class name to search for
 */
private static void findIt(String classname) {

    try {
        // get the system classpath
        String classpath = System.getProperty("java.class.path", "");

        if (classpath.equals("")) {
            System.err.println("error: classpath is not set");
        }

        if (debug) {
            System.out.println("classname: " + classname);
            System.out.println("system classpath = " + classpath);
        }

        if (isPrimitiveOrVoid(classname)) {
            System.out.println("'" + classname + "' primitive");
            return;
        }

        StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator);

        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            File classpathElement = new File(token);

            if (debug)
                System.out.println(classpathElement.isDirectory() ? "dir: " + token : "jar: " + token);

            URL[] url = { classpathElement.toURL() };

            URLClassLoader cl = URLClassLoader.newInstance(url, null);

            String classnameAsResource = classname.replace('.', '/') + ".class";

            URL it = cl.findResource(classnameAsResource);
            if (it != null) {
                System.out.println("found in: " + token);
                System.out.println("     url: " + it.toString());
                System.out.println("");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * Writes entries to a JAR and loads it up.
 * @param entries class nodes to put in to jar
 * @return class loader with files in newly created JAR available
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null}
 * @throws IllegalArgumentException if {@code classNodes} is empty
 *//*from   w w w .  j  av a 2  s  .  com*/
public static URLClassLoader createJarAndLoad(JarEntry... entries) throws IOException {
    Validate.notNull(entries);
    Validate.noNullElements(entries);

    File jarFile = createJar(entries);
    return URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() }, TestUtils.class.getClassLoader());
}

From source file:org.apache.impala.extdatasource.ExternalDataSourceExecutor.java

/**
 * Returns the ExternalDataSource class, loading the jar if necessary. The
 * class is cached if initString_ starts with CACHE_CLASS_PREFIX.
 *///from  w  w w. j a v  a  2s  .  com
private Class<?> getDataSourceClass() throws Exception {
    Class<?> c = null;
    // Cache map key needs to contain both the class name and init string in case
    // the same class is used for multiple tables where some are cached and others
    // are not.
    String cacheMapKey = String.format("%s.%s", className_, initString_);
    synchronized (cachedClassesLock_) {
        c = cachedClasses_.get(cacheMapKey);
        if (c == null) {
            URL url = new File(jarPath_).toURI().toURL();
            URLClassLoader loader = URLClassLoader.newInstance(new URL[] { url }, getClass().getClassLoader());
            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(), apiVersion_.name()));
            }
            // Only cache the class if the init string starts with CACHE_CLASS_PREFIX
            if (initString_ != null && initString_.startsWith(CACHE_CLASS_PREFIX)) {
                cachedClasses_.put(cacheMapKey, c);
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Loaded jar for class {} at path {}", className_, jarPath_);
            }
            numClassCacheMisses_++;
        } else {
            numClassCacheHits_++;
        }
    }
    return c;
}

From source file:org.wso2.carbon.java2wsdl.Java2WSDL.java

/**
 * This is the fall though method for wsdlview. This will check for required resources.
 *
 * @param options options array//from ww  w  . jav a2s.  c o  m
 * @param uuids   uuid array
 * @return String id
 * @throws AxisFault will be thrown.
 */
public String java2wsdlWithResources(String[] options, String[] uuids) throws AxisFault {

    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    try {
        URL[] urls = new URL[uuids.length];
        for (int i = 0; i < uuids.length; i++) {
            urls[i] = new File(uuids[i]).toURL();
        }
        ClassLoader newCl = URLClassLoader.newInstance(urls, prevCl);
        Thread.currentThread().setContextClassLoader(newCl);
        return java2wsdl(options);
    } catch (MalformedURLException e) {
        throw AxisFault.makeFault(e);
    } finally {
        Thread.currentThread().setContextClassLoader(prevCl);
    }

}

From source file:fi.uta.infim.usaproxyreportgenerator.App.java

private static void setupDataProvider() {
    // A data provider class can be specified on the CLI.
    if (cli.hasOption("dataProvider")) {
        // Look for JAR files in the plugin dir
        File[] jars = PLUGINS_DIR.listFiles((FileFilter) new WildcardFileFilter("*.jar", IOCase.INSENSITIVE));
        URL[] jarUrls = new URL[jars.length];
        for (int i = 0; i < jars.length; ++i) {
            try {
                jarUrls[i] = jars[i].toURI().toURL();
            } catch (MalformedURLException e) {
                // Skip URL if not valid
                continue;
            }//  w w w. j a  va 2s .c  om
        }

        ClassLoader loader = URLClassLoader.newInstance(jarUrls, ClassLoader.getSystemClassLoader());
        String className = cli.getOptionValue("dataProvider");

        // Try to load the named class using a class loader. Fall back to
        // default if this fails.
        try {
            @SuppressWarnings("unchecked")
            Class<? extends DataProvider> cliOptionClass = (Class<? extends DataProvider>) Class
                    .forName(className, true, loader);
            if (!DataProvider.class.isAssignableFrom(cliOptionClass)) {
                throw new ClassCastException(cliOptionClass.getCanonicalName());
            }
            dataProviderClass = cliOptionClass;
        } catch (ClassNotFoundException e) {
            System.out.flush();
            System.err.println("Specified data provider class not found: " + e.getMessage());
            System.err.println("Falling back to default provider.");
        } catch (ClassCastException e) {
            System.out.flush();
            System.err.println("Specified data provider class is invalid: " + e.getMessage());
            System.err.println("Falling back to default provider.");
        }
        System.err.flush();
    }
}

From source file:org.springframework.osgi.web.deployer.internal.util.JasperUtils.java

/**
 * Creates an URLClassLoader that wraps the given class loader meaning that
 * all its calls will be delegated to the backing class loader. However, the
 * bundle context will be used inside {@link URLClassLoader#getURLs()} so
 * that Tomcat Jasper detects the taglibs available inside the given bundle
 * and its imports./*from   ww  w .  j  av  a  2s.c o m*/
 * 
 * <p/> To avoid unneeded lookups, the method will check for the presence of
 * Jasper compiler. If it's not found, then no taglibs will be searched.
 * 
 * @param bundle OSGi backing bundle
 * @param unpackLocation location where the bundle is unpacked
 * @param parent parent class loader
 * 
 * @return Tomcat Jasper 2 suited URLClassLoader wrapper around the given
 * class loader.
 */
public static URLClassLoader createJasperClassLoader(Bundle bundle, ClassLoader parent) {
    // search for Jasper

    boolean jasperPresent = false;
    try
    // first search the bundle 
    {
        bundle.loadClass(JASPER_CLASS);
        jasperPresent = true;
    } catch (ClassNotFoundException cnfe) {
        //followed by the parent classloader
        jasperPresent = ClassUtils.isPresent(JASPER_CLASS, parent);
    }

    URL[] tldJars = null;
    if (jasperPresent) {
        if (log.isDebugEnabled())
            log.debug("Jasper present in bundle " + OsgiStringUtils.nullSafeSymbolicName(bundle)
                    + "; looking for taglibs...");
        tldJars = createTaglibClasspathJars(bundle);
    } else {
        if (log.isDebugEnabled())
            log.debug("Jasper not present in bundle " + OsgiStringUtils.nullSafeSymbolicName(bundle)
                    + "; ignoring taglibs...");

        tldJars = new URL[0];
    }

    return URLClassLoader.newInstance(tldJars, parent);
}

From source file:com.expedia.tesla.compiler.Util.java

/**
 * Load a Java class by it's full name./*from www.ja v  a 2 s .com*/
 * 
 * @param name
 *            The full name of the Java class to load.
 * @param urls
 *            An array of URL objects represent class paths or jar files.
 * @return The java.lang.Class object represents the Java class.
 * @throws ClassNotFoundException
 *             If the class is not found.
 * @throws IOException
 *             If the jar file cannot open.
 */
public static java.lang.Class<?> loadClass(String name, URL[] urls) throws ClassNotFoundException, IOException {
    java.lang.Class<?> clzz = null;
    if (urls != null && urls.length > 0) {
        URLClassLoader cl = URLClassLoader.newInstance(urls, Util.class.getClassLoader());
        clzz = cl.loadClass(name);
    }

    if (clzz == null) {
        clzz = Class.forName(name);
    }

    return clzz;
}

From source file:org.wso2.carbon.jarservices.JarServiceCreatorAdmin.java

/**
 * This method will list all the public methods for the given classes.
 *
 * @param directoryPath Temp dir innto which all jars were uploaded
 * @param services      Selected classes
 * @return All methods in the selected classes
 * @throws AxisFault Error//from  w  w w.j  a va 2  s.  c  om
 * @throws DuplicateServiceException If  a service  with a given name already exists
 */
public Service[] getClassMethods(String directoryPath, Service[] services)
        throws AxisFault, DuplicateServiceException {
    if (services == null || services.length == 0) {
        String msg = "Cannot find services";
        log.error(msg);
        throw new AxisFault(msg);
    }
    List<String> methodExcludeList = new ArrayList<String>();
    methodExcludeList.add("hashCode");
    methodExcludeList.add("getClass");
    methodExcludeList.add("equals");
    methodExcludeList.add("notify");
    methodExcludeList.add("notifyAll");
    methodExcludeList.add("toString");
    methodExcludeList.add("wait");
    List<URL> resourcesList = new ArrayList<URL>();

    File[] files = new File(directoryPath + File.separator + "lib").listFiles();
    for (File file : files) {
        try {
            resourcesList.add(file.toURI().toURL());
        } catch (MalformedURLException ignored) {
            // This exception will not occur
        }
    }

    AxisConfiguration axisConfig = getAxisConfig();
    URL[] urls = resourcesList.toArray(new URL[resourcesList.size()]);
    ClassLoader classLoader = URLClassLoader.newInstance(urls, axisConfig.getServiceClassLoader());

    for (int i = 0; i < services.length; i++) {
        Service service = services[i];
        String className = service.getClassName();
        if (axisConfig.getService(service.getServiceName()) != null) {
            String msg = "Axis service " + service.getServiceName() + " already exists";
            log.warn(msg);
            throw new DuplicateServiceException(msg);
        }
        try {
            Class clazz = classLoader.loadClass(className);
            java.lang.reflect.Method[] methods = clazz.getMethods();
            List<Operation> operationList = new ArrayList<Operation>();
            for (int j = 0; j < methods.length; j++) {
                java.lang.reflect.Method method = methods[j];
                String methodName = method.getName();
                int modifiers = method.getModifiers();
                if (Modifier.isPublic(modifiers) && !methodExcludeList.contains(methodName)) {
                    Operation operation = new Operation();
                    operation.setOperationName(methodName);
                    operationList.add(operation);
                }
            }
            findOverloadedMethods(operationList);
            service.setOperations(operationList.toArray(new Operation[operationList.size()]));
        } catch (ClassNotFoundException e) {
            String msg = "The class " + className + " cannot be loaded";
            log.error(msg);
        }
    }
    return services;
}