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.hama.pipes.util.DistributedCacheUtil.java

/**
 * Add the JARs from the given HDFS paths to the Classpath
 * /*from ww  w .  j  a  v a2  s  .  co m*/
 * @param conf The job's configuration
 */
public static URL[] addJarsToJobClasspath(Configuration conf) {
    URL[] classLoaderURLs = ((URLClassLoader) conf.getClassLoader()).getURLs();
    String files = conf.get("tmpjars", "");

    if (!files.isEmpty()) {
        String[] fileArr = files.split(",");
        URL[] libjars = new URL[fileArr.length + classLoaderURLs.length];

        for (int i = 0; i < fileArr.length; i++) {
            String tmp = fileArr[i];

            URI pathURI;
            try {
                pathURI = new URI(tmp);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e);
            }

            try {
                FileSystem hdfs = FileSystem.get(conf);
                Path pathSrc = new Path(pathURI.getPath());
                // LOG.info("pathSrc: " + pathSrc);

                if (hdfs.exists(pathSrc)) {
                    LocalFileSystem local = LocalFileSystem.getLocal(conf);

                    // File dst = File.createTempFile(pathSrc.getName() + "-", ".jar");
                    Path pathDst = new Path(local.getWorkingDirectory(), pathSrc.getName());

                    LOG.debug("copyToLocalFile: " + pathDst);
                    hdfs.copyToLocalFile(pathSrc, pathDst);
                    local.deleteOnExit(pathDst);

                    libjars[i] = new URL(local.makeQualified(pathDst).toString());
                }

            } catch (IOException ex) {
                throw new RuntimeException("Error setting up classpath", ex);
            }
        }

        // Add old classLoader entries
        int index = fileArr.length;
        for (int i = 0; i < classLoaderURLs.length; i++) {
            libjars[index] = classLoaderURLs[i];
            index++;
        }

        // Set classloader in current conf/thread
        conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));

        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader()));

        // URL[] urls = ((URLClassLoader) conf.getClassLoader()).getURLs();
        // for (URL u : urls)
        // LOG.info("newClassLoader: " + u.getPath());

        // Set tmpjars
        // hdfs to local path
        String jars = "";
        for (int i = 0; i < fileArr.length; i++) {
            URL url = libjars[i];
            if (jars.length() > 0) {
                jars += ",";
            }
            jars += url.toString();
        }
        conf.set("tmpjars", jars);

        return libjars;
    }
    return null;
}

From source file:org.openvpms.maven.archetype.AbstractHibernateMojo.java

/**
 * Helper to create a class loader using the project's test class path.
 *
 * @return a new classloader/*from  w  ww . j a v  a  2s  . co  m*/
 */
private ClassLoader getClassLoader() {
    try {
        List classpathElements = getProject().getTestClasspathElements();

        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.", e);
        return this.getClass().getClassLoader();
    }
}

From source file:org.apache.woden.internal.resolver.SimpleURIResolver.java

public SimpleURIResolver() throws WSDLException {

    Properties schemaCatalog = null;
    /* Unlike the user catalog case, the schema catalog does not refer to RESOLVER_PROPERTIES_PROPERTY
     * for its catalog location (it's hard coded) or to RESOLVER_BASE_PROPERTY (it uses only the unmodified
     * system classloader to yield absolute URLs from any relative "resolve-to" URLs in the catalog).
     * The principle is that the schema catalog behaviour should be unaffected by the use of the public user catalog.
     *//*from  w w  w.  ja va2  s .  c o  m*/

    Properties userCatalog = null;

    // check if resolver logging required
    logging = (LOGGING_ON.equalsIgnoreCase(loggingRequest));

    // find location of schema catalog on the classpath. 
    // This catalog has a hardcoded name and relative location.
    ClassLoader systemLoader = this.getClass().getClassLoader();
    URL schemaCatalogURL = systemLoader.getResource(schemaCatalogLocation + schemaCatalogFile);

    if (schemaCatalogURL == null) {
        // schema catalog is not in expected location on classpath, so look for an immediate
        // entry under the classpath.
        schemaCatalogURL = systemLoader.getResource(schemaCatalogFile);
    }

    // read & retain the system resolver references 
    schemaCatalog = loadCatalog(schemaCatalogURL);

    if (userCatalogFile != null) { // user catalog file specified, so use it...
        // read & retain the user resolver references from user catalog properties file
        try {
            userCatalog = loadCatalog(new URL(userCatalogFile));
        } catch (MalformedURLException e) {
            throw new WSDLException(WSDLException.CONFIGURATION_ERROR,
                    "Problem locating the URI resolver user catalog: " + userCatalogFile, e);
        }
    }

    // build a URL[] from a (possibly empty) list of search URL directories/jars
    URL[] rootURLs = urlPathList(rootURLsList);
    URLClassLoader userLoader = new URLClassLoader(rootURLs, systemLoader);

    // convert provided keys and values to URIs
    try {
        // process the schema catalog contents
        Hashtable interrimUriTable = toURI(schemaCatalog, systemLoader);
        // append the processed user catalog to the schema catalog
        uriTable = toURI(userCatalog, userLoader, interrimUriTable);
    } catch (URISyntaxException e) {
        throw new WSDLException(WSDLException.CONFIGURATION_ERROR,
                "Problem instantiating the URI resolution table.", e);
    }
}

From source file:org.apache.maven.plugin.checkstyle.DefaultCheckstyleExecutor.java

public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request)
        throws CheckstyleExecutorException, CheckstyleException {
    // checkstyle will always use the context classloader in order
    // to load resources (dtds),
    // so we have to fix it
    // olamy this hack is not anymore needed in maven 3.x
    ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
    Thread.currentThread().setContextClassLoader(checkstyleClassLoader);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation());
    }/* w w w . j  ava  2  s . co  m*/

    MavenProject project = request.getProject();

    configureResourceLocator(locator, request);

    configureResourceLocator(licenseLocator, request);

    File[] files;
    try {
        files = getFilesToProcess(request);
    } catch (IOException e) {
        throw new CheckstyleExecutorException("Error getting files to process", e);
    }

    final String suppressionsFilePath = getSuppressionsFilePath(request);
    FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath);

    Checker checker = new Checker();

    // setup classloader, needed to avoid "Unable to get class information
    // for ..." errors
    List<String> classPathStrings = new ArrayList<String>();
    List<String> outputDirectories = new ArrayList<String>();
    File sourceDirectory = request.getSourceDirectory();
    File testSourceDirectory = request.getTestSourceDirectory();
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories,
                    new File(childProject.getBuild().getSourceDirectory()),
                    new File(childProject.getBuild().getTestSourceDirectory()));
        }
    } else {
        prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectory,
                testSourceDirectory);
    }

    List<URL> urls = new ArrayList<URL>(classPathStrings.size());

    for (String path : classPathStrings) {
        try {
            urls.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    for (String outputDirectoryString : outputDirectories) {
        try {
            if (outputDirectoryString != null) {
                File outputDirectoryFile = new File(outputDirectoryString);
                if (outputDirectoryFile.exists()) {
                    URL outputDirectoryUrl = outputDirectoryFile.toURL();
                    request.getLog().debug("Adding the outputDirectory " + outputDirectoryUrl.toString()
                            + " to the Checkstyle class path");
                    urls.add(outputDirectoryUrl);
                }
            }
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    URLClassLoader projectClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
    checker.setClassloader(projectClassLoader);

    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());

    if (filterSet != null) {
        checker.addFilter(filterSet);
    }
    Configuration configuration = getConfiguration(request);
    checker.configure(configuration);

    AuditListener listener = request.getListener();

    if (listener != null) {
        checker.addListener(listener);
    }

    if (request.isConsoleOutput()) {
        checker.addListener(request.getConsoleListener());
    }

    CheckstyleReportListener sinkListener = new CheckstyleReportListener(configuration);
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            addSourceDirectory(sinkListener, new File(childProject.getBuild().getSourceDirectory()),
                    new File(childProject.getBuild().getTestSourceDirectory()), childProject.getResources(),
                    request);
        }
    } else {
        addSourceDirectory(sinkListener, sourceDirectory, testSourceDirectory, request.getResources(), request);
    }

    checker.addListener(sinkListener);

    List<File> filesList = Arrays.asList(files);
    int nbErrors = checker.process(filesList);

    checker.destroy();

    if (projectClassLoader instanceof Closeable) {
        try {
            ((Closeable) projectClassLoader).close();
        } catch (IOException ex) {
            // Nothing we can do - and not detrimental to the build (save running out of file handles).
            getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex);
        }
    }

    if (request.getStringOutputStream() != null) {
        request.getLog().info(request.getStringOutputStream().toString());
    }

    if (request.isFailsOnError() && nbErrors > 0) {
        // TODO: should be a failure, not an error. Report is not meant to
        // throw an exception here (so site would
        // work regardless of config), but should record this information
        throw new CheckstyleExecutorException("There are " + nbErrors + " checkstyle errors.");
    } else if (nbErrors > 0) {
        request.getLog().info("There are " + nbErrors + " checkstyle errors.");
    }

    return sinkListener.getResults();
}

From source file:com.carrotgarden.maven.scr.CarrotOsgiScrGenerate.java

/**
 * Generate extended class loader./*  ww  w  .  ja  v a  2 s .  c  o m*/
 * 
 * @return class loader that will include both project and plug-in
 *         dependencies
 **/
protected ClassLoader makeClassLoader(final ClassesSelector selector) throws Exception {

    final List<String> pathList = selector.getClasspathElements(project);

    final URL[] entryUrlArray = new URL[pathList.size()];

    int index = 0;
    for (final String path : pathList) {
        final URL entryURL = absolute(path).toURI().toURL();
        logDebug("\t dependency = " + entryURL);
        entryUrlArray[index++] = entryURL;
    }

    /** Maven plug-in class loader. */
    final ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();

    /** Combo class path loader for a selector. */
    final URLClassLoader customLoader = new URLClassLoader(entryUrlArray, parentLoader);

    return customLoader;

}

From source file:org.eclipse.jetty.demo.Main.java

/**
 * Set Classloader of Context to be sane (needed for JSTL)
 * JSP requires a non-System classloader, this simply wraps the
 * embedded System classloader in a way that makes it suitable
 * for JSP to use//from  w w w  .  ja  v a2s.  c  o  m
 */
private ClassLoader getUrlClassLoader() {
    ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
    return jspClassLoader;
}

From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private ConnectionFactory createConnectionFactory(boolean profileSql) throws MalformedURLException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();
    URL url = new URL(jdbcDriverClassPath);
    try {//from w  ww . j a v  a2s .c  om
        File file = new File(url.toURI());
        if (!file.exists()) {
            throw new IllegalStateException("JDBC driver class path not found: " + file);
        }
    } catch (URISyntaxException e) {
        throw new IllegalStateException(
                "Unable to convert URL " + url.toExternalForm() + " into URI: " + e.getMessage(), e);
    }
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url },
            Thread.currentThread().getContextClassLoader());

    String jdbcDriverClassName = globalConfiguration.getJdbcDriverClassName();
    String connectURI = globalConfiguration.getJdbcConnectionURI(); // + "?initialTimeout=2";
    String userName = globalConfiguration.getJdbcUsername();
    String password = globalConfiguration.getJdbcPassword();

    Class<?> aClass = null;
    try {
        aClass = Class.forName(jdbcDriverClassName, true, urlClassLoader);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Unable to locate class " + jdbcDriverClassName + " in class path '"
                + jdbcDriverClassPath + "'");
    }
    Driver driver = (Driver) aClass.newInstance();
    assertTrue(driver.acceptsURL(connectURI));

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);
    if (profileSql) {
        properties.put("profileSQL", "true"); // MySQL debug option
    }
    return new DriverConnectionFactory(driver, connectURI, properties);
}

From source file:org.agiso.tempel.core.DefaultTemplateExecutor.java

private void doExecuteTemplate(Template<?> template, MapStack<String, Object> properties, String workDir) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {//from   w w  w . java  2  s  .co  m
        StringBuilder deps = null;
        if (coreLogger.isTraceEnabled()) {
            deps = new StringBuilder();
        } else if (coreLogger.isDebugEnabled())
            coreLogger.debug(Logs.LOG_01,
                    ansiString(GREEN,
                            ansiString(GREEN, template.getKey()) + ": "
                                    + ansiString(GREEN, template.getGroupId() + ":" + template.getTemplateId()
                                            + ":" + template.getVersion())));

        // FIXME: Zastosowa zbir Set<URL>
        Set<String> classPath = template.getTemplateClassPath();
        if (classPath != null && !classPath.isEmpty()) {
            List<URL> urls = new ArrayList<URL>(classPath.size());
            for (String classPathEntry : classPath) {
                urls.add(new File(classPathEntry).toURI().toURL());
                if (coreLogger.isTraceEnabled()) {
                    if (deps.length() > 0) {
                        deps.append(", ");
                    }
                    deps.append(classPathEntry);
                }
            }
            ClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
                    contextClassLoader);
            Thread.currentThread().setContextClassLoader(classLoader);
        }

        if (coreLogger.isTraceEnabled())
            coreLogger.trace(Logs.LOG_02, ansiString(GREEN,
                    ansiString(GREEN, template.getKey()) + ": " + ansiString(GREEN, template.getGroupId() + ":"
                            + template.getTemplateId() + ":" + template.getVersion())),
                    ansiString(GREEN, deps.toString()));

        doExecuteTemplateInternal(template, properties, workDir);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:org.bonitasoft.console.common.server.utils.FormsResourcesUtils.java

/**
 * Create a classloader for the process/*from   ww  w  .j a  v  a 2 s .c  o  m*/
 *
 * @param processDefinitionID
 *            the process definition ID
 * @param processApplicationsResourcesDir
 *            the process application resources directory
 * @return a Classloader
 * @throws java.io.IOException
 */
private static ClassLoader createProcessClassloader(final long processDefinitionID,
        final File processApplicationsResourcesDir) throws IOException {
    ClassLoader processClassLoader = null;
    try {
        final URL[] librariesURLs = getLibrariesURLs(processApplicationsResourcesDir);
        if (librariesURLs.length > 0) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "Creating the classloader for process " + processDefinitionID);
            }
            processClassLoader = new URLClassLoader(librariesURLs,
                    Thread.currentThread().getContextClassLoader());
        }
    } catch (final IOException e) {
        final String message = "Unable to create the class loader for the process's libraries";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, message, e);
        }
        throw new IOException(message);
    }
    return processClassLoader;
}

From source file:org.bonitasoft.engine.home.BonitaHomeServerTest.java

@Test
public void should_getPropertiesFromClassPath_get_properties_of_all_files_from_classpath() throws Exception {
    //given//from  w  w  w .j av a 2  s. c  o  m
    File jar1 = temporaryFolder.newFile("myJar1.jar");
    FileUtils.writeByteArrayToFile(jar1, IOUtil
            .generateJar(Collections.singletonMap("myPropertiesFile1.properties", "prop1=value1".getBytes())));
    File jar2 = temporaryFolder.newFile("myJar2.jar");
    FileUtils.writeByteArrayToFile(jar2, IOUtil
            .generateJar(Collections.singletonMap("myPropertiesFile2.properties", "prop2=value2".getBytes())));
    File jar3 = temporaryFolder.newFile("myJar3.jar");
    FileUtils.writeByteArrayToFile(jar3, IOUtil
            .generateJar(Collections.singletonMap("myPropertiesFile3.properties", "prop3=value3".getBytes())));
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader urlClassLoader = new URLClassLoader(
            new URL[] { jar1.toURI().toURL(), jar2.toURI().toURL(), jar3.toURI().toURL() }, contextClassLoader);
    try {
        Thread.currentThread().setContextClassLoader(urlClassLoader);
        //when
        Properties propertiesFromClassPath = bonitaHomeServer.getPropertiesFromClassPath(
                "myPropertiesFile1.properties", "myPropertiesFile2.properties",
                "anUnexistingProperty.properties");
        //then
        assertThat(propertiesFromClassPath).containsOnly(entry("prop1", "value1"), entry("prop2", "value2"));
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}