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:com.liferay.arquillian.maven.internal.tasks.ToolsClasspathTask.java

/**
 * (non-Javadoc)/*from  ww w  . j  a  v a 2  s .c  o m*/
 * @see
 * org.jboss.shrinkwrap.resolver.impl.maven.task.MavenWorkingSessionTask
 * #execute(org.jboss.shrinkwrap.resolver.api.maven.MavenWorkingSession)
 */
@Override
public URLClassLoader execute(MavenWorkingSession session) {
    final ParsedPomFile pomFile = session.getParsedPomFile();

    LiferayPluginConfiguration configuration = new LiferayPluginConfiguration(pomFile);

    System.setProperty("liferayVersion", configuration.getLiferayVersion());

    File appServerLibGlobalDir = new File(configuration.getAppServerLibGlobalDir());

    File appServerLibPortalDir = new File(configuration.getAppServerLibPortalDir());

    List<URI> liferayToolArchives = new ArrayList<>();

    if ((appServerLibGlobalDir != null) && appServerLibGlobalDir.exists()) {

        // app server global libraries

        Collection<File> appServerLibs = FileUtils.listFiles(appServerLibGlobalDir, new String[] { "jar" },
                true);

        for (File file : appServerLibs) {
            liferayToolArchives.add(file.toURI());
        }

        // All Liferay Portal Lib jars

        Collection<File> liferayPortalLibs = FileUtils.listFiles(appServerLibPortalDir, new String[] { "jar" },
                true);

        for (File file : liferayPortalLibs) {
            liferayToolArchives.add(file.toURI());
        }

        // Util jars

        File[] utilJars = Maven.resolver().loadPomFromClassLoaderResource("liferay-tool-deps.xml")
                .importCompileAndRuntimeDependencies().resolve().using(AcceptAllStrategy.INSTANCE).asFile();

        for (int i = 0; i < utilJars.length; i++) {
            liferayToolArchives.add(utilJars[i].toURI());
        }
    }

    if (_log.isTraceEnabled()) {
        _log.trace("Jars count in Tools classpath Archive:" + liferayToolArchives.size());
    }

    List<URL> classpathUrls = new ArrayList<>();

    try {
        if (!liferayToolArchives.isEmpty()) {
            ListIterator<URI> toolsJarItr = liferayToolArchives.listIterator();
            while (toolsJarItr.hasNext()) {
                URI jarURI = toolsJarItr.next();
                classpathUrls.add(jarURI.toURL());
            }
        }
    } catch (MalformedURLException e) {
        _log.error("Error building Tools classpath", e);
    }

    return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), null);
}

From source file:org.ops4j.pax.runner.platform.InProcessJavaRunner.java

/**
 * Creates the clasloader to usefor loading the framework main class.
 *
 * @param classpath classpath entries//from  w  ww . j a  v  a  2s  . c om
 *
 * @return classloader
 *
 * @throws PlatformException if classpath entries cannot be converted to urls
 */
private static URLClassLoader createClassLoader(final String[] classpath) throws PlatformException {
    final List<URL> classpathUrls = new ArrayList<URL>();
    if (classpath != null) {
        for (String path : classpath) {
            try {
                classpathUrls.add(new File(path).toURL());
            } catch (MalformedURLException e) {
                throw new PlatformException("Cannot setup target framework classpath", e);
            }
        }
    }
    return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]),
            InProcessJavaRunner.class.getClassLoader().getParent());
}

From source file:com.liferay.maven.arquillian.internal.tasks.ToolsClasspathTask.java

@Override
public URLClassLoader execute(MavenWorkingSession session) {

    final Logger log = LoggerFactory.getLogger(ToolsClasspathTask.class);

    final ParsedPomFile pomFile = session.getParsedPomFile();

    LiferayPluginConfiguration configuration = new LiferayPluginConfiguration(pomFile);

    System.setProperty("liferayVersion", configuration.getLiferayVersion());

    File appServerLibGlobalDir = new File(configuration.getAppServerLibGlobalDir());

    File appServerLibPortalDir = new File(configuration.getAppServerLibPortalDir());

    List<URI> liferayToolArchives = new ArrayList<URI>();

    if (appServerLibGlobalDir != null && appServerLibGlobalDir.exists()) {

        // app server global libraries
        Collection<File> appServerLibs = FileUtils.listFiles(appServerLibGlobalDir, new String[] { "jar" },
                true);/*from  ww w  .  j  av  a 2s.  c  om*/

        for (File file : appServerLibs) {
            liferayToolArchives.add(file.toURI());
        }

        // All Liferay Portal Lib jars
        Collection<File> liferayPortalLibs = FileUtils.listFiles(appServerLibPortalDir, new String[] { "jar" },
                true);

        for (File file : liferayPortalLibs) {
            liferayToolArchives.add(file.toURI());
        }

        // Util jars
        File[] utilJars = Maven.resolver().loadPomFromClassLoaderResource("liferay-tool-deps.xml")
                .importCompileAndRuntimeDependencies().resolve().using(AcceptAllStrategy.INSTANCE).asFile();

        for (int i = 0; i < utilJars.length; i++) {
            liferayToolArchives.add(utilJars[i].toURI());
        }

    }

    log.trace("Jars count in Tools classpath Archive:" + liferayToolArchives.size());

    List<URL> classpathUrls = new ArrayList<URL>();

    try {
        if (!liferayToolArchives.isEmpty()) {

            ListIterator<URI> toolsJarItr = liferayToolArchives.listIterator();
            while (toolsJarItr.hasNext()) {
                URI jarURI = toolsJarItr.next();
                classpathUrls.add(jarURI.toURL());
            }

        }
    } catch (MalformedURLException e) {
        log.error("Error building Tools classpath", e);
    }

    return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), null);
}

From source file:org.exnebula.bootstrap.BootConfigLocatorTest.java

private Class<?> createClassLoaderAndLoadClass(File jarFile, String classToLoad)
        throws MalformedURLException, ClassNotFoundException {
    URL[] urls = { jarFile.toURI().toURL() };
    URLClassLoader classLoader = new URLClassLoader(urls, null);
    return classLoader.loadClass(classToLoad);
}

From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java

/**
 * Constructs a Class Loader based on a list of paths to classes and a
 * parent Class Loader//from ww  w .j  av  a  2s  . com
 * 
 * @param paths
 * @param mojoClassLoader
 * @return The constructed ClassLoader
 * @throws MalformedURLException
 */
public static ClassLoader getClassLoader(List<String> paths, ClassLoader mojoClassLoader)
        throws MalformedURLException {
    final List<URL> pathURLs = new ArrayList<URL>();

    for (String curPath : paths) {

        URL newClassPathURL = new File(curPath).toURI().toURL();

        getLog().debug("Adding " + newClassPathURL.toString() + " to class loader");

        pathURLs.add(newClassPathURL);

    }

    return new URLClassLoader(pathURLs.toArray(new URL[0]), mojoClassLoader);
}

From source file:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java

private Class<?> loadClass(File jarFile, String paramName) {
    try {/*from w w w.  ja v a  2 s .  c om*/
        Properties props = getPluginProps(jarFile);
        if (props == null)
            throw new IllegalArgumentException("No props file in " + jarFile.getName() + " found");

        String pluginClassName = props.getProperty(paramName);
        if (pluginClassName == null || pluginClassName.length() == 0) {
            return null;
        }

        URL jarURL = jarFile.toURI().toURL();
        //         URLClassLoader classLoader = new URLClassLoader(
        //               new URL[] { jarURL }, getClass().getClassLoader());
        URLClassLoader classLoader = new URLClassLoader(new URL[] { jarURL },
                org.springframework.util.ClassUtils.getDefaultClassLoader());
        Class<?> pluginClass = classLoader.loadClass(pluginClassName);
        //         classLoader.close();
        return pluginClass;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.opengamma.maven.scripts.ScriptableScriptGeneratorMojo.java

@SuppressWarnings("unchecked")
@Override//from   w  w  w .ja v a2  s  .  co m
public void execute() throws MojoExecutionException, MojoFailureException {
    boolean templateSet = !StringUtils.isBlank(_template);
    boolean templateMapSet = _baseClassTemplateMap != null && _baseClassTemplateMap.isEmpty();
    if ((templateSet && templateMapSet) || (!templateSet && !templateMapSet)) {
        throw new MojoExecutionException("Exactly one of 'template' or 'baseClassTemplateMap' must be set");
    }
    if (!_outputDir.exists()) {
        try {
            getLog().debug("Creating output directory " + _outputDir);
            if (!_outputDir.mkdirs()) {
                throw new MojoExecutionException(
                        "Unable to create output directory " + _outputDir.getAbsolutePath());
            }
        } catch (Exception e) {
            throw new MojoExecutionException("Error creating output directory " + _outputDir.getAbsolutePath());
        }
    }

    List<String> classpathElementList;
    try {
        classpathElementList = _project.getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error obtaining dependencies", e);
    }
    URL[] classpathUrls = ClasspathUtils.getClasspathURLs(classpathElementList);
    Set<String> annotationClasses = ClassNameAnnotationScanner.scan(classpathUrls, Scriptable.class.getName());
    getLog().info("Generating " + annotationClasses.size() + " scripts");

    ClassLoader classLoader = new URLClassLoader(classpathUrls, this.getClass().getClassLoader());
    Map<Class<?>, Template> templateMap = resolveTemplateMap(classLoader);

    for (String className : annotationClasses) {
        Map<String, Object> templateData = new HashMap<String, Object>();
        templateData.put("className", className);
        Template template = getTemplateForClass(className, classLoader, templateMap);
        if (template == null) {
            getLog().warn("No template for scriptable class " + className);
            continue;
        }
        ScriptsGenerator.generate(className, _outputDir, template, templateData);
    }

    if (_additionalScripts != null) {
        getLog().info("Copying " + _additionalScripts.length + " additional script(s)");
        for (String script : _additionalScripts) {
            File scriptFile = new File(script);
            if (scriptFile.exists()) {
                if (!scriptFile.isFile()) {
                    throw new MojoExecutionException(
                            "Can only copy files, but additional script '" + scriptFile + "' is not a file");
                }
                try {
                    FileUtils.copyFileToDirectory(scriptFile, _outputDir);
                    File copiedFile = new File(_outputDir, scriptFile.getName());
                    copiedFile.setReadable(true, false);
                    copiedFile.setExecutable(true, false);
                } catch (IOException e) {
                    throw new MojoExecutionException("Unable to copy additional script '" + scriptFile + "'",
                            e);
                }
            }
        }
    }
}

From source file:net.morematerials.manager.HandlerManager.java

public void load(File handlerClass) {
    String className = handlerClass.getName().substring(0, handlerClass.getName().lastIndexOf("."));
    String useName = className.replaceAll("Handler$", "");
    try {/*w  w  w  . j  a v  a 2  s .co  m*/
        @SuppressWarnings("resource")
        ClassLoader loader = new URLClassLoader(new URL[] { handlerClass.getParentFile().toURI().toURL() },
                GenericHandler.class.getClassLoader());
        Class<?> clazz = loader.loadClass(className);
        Object object = clazz.newInstance();
        if (!(object instanceof GenericHandler)) {
            this.plugin.getUtilsManager().log("Not a handler: " + useName, Level.WARNING);
        } else {
            GenericHandler handler = (GenericHandler) object;
            handler.init(this.plugin);
            this.handlers.put(useName, handler);
            this.plugin.getUtilsManager().log("Loaded handler: " + useName);
        }
    } catch (Exception exception) {
        this.plugin.getUtilsManager().log("Error loading handler: " + useName, Level.SEVERE);
    }
}

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

@Test
public void testBasicDataSource() throws Exception {

    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new URL(jdbcDriverClassPath) },
            Thread.currentThread().getContextClassLoader());

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(globalConfiguration.getJdbcDriverClassName());
    basicDataSource.setUrl(globalConfiguration.getJdbcConnectionURI());
    basicDataSource.setUsername(globalConfiguration.getJdbcUsername());
    basicDataSource.setPassword(globalConfiguration.getJdbcPassword());

    // Does not work in 1.4, fixed in 1.4.1
    basicDataSource.setDriverClassLoader(urlClassLoader);

    try {/*w ww. j av  a2  s  .com*/
        Connection connection = basicDataSource.getConnection();
        assertNotNull(connection);
        fail("Wuhu! They have finally fixed the bug in DBCP; ignoring the classloader. Consider changing the code!");
    } catch (SQLException e) {
        // As expected when using DBCP 1.4
    }
}

From source file:com.lewisd.maven.lint.plugin.CheckMojo.java

private void initializeConfig() throws DependencyResolutionRequiredException, IOException {

    @SuppressWarnings("rawtypes")
    List testClasspathElements = project.getTestClasspathElements();
    URL[] testUrls = new URL[testClasspathElements.size()];
    for (int i = 0; i < testClasspathElements.size(); i++) {
        String element = (String) testClasspathElements.get(i);
        testUrls[i] = new File(element).toURI().toURL();
    }/*  www.ja  v a2  s .  c  o  m*/
    classLoader = new URLClassLoader(testUrls, Thread.currentThread().getContextClassLoader());

    applicationContext = new GenericApplicationContext();
    ClassPathResource classPathResource = new ClassPathResource(configLocation, classLoader);
    XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
    xmlBeanDefinitionReader.loadBeanDefinitions(classPathResource);

    applicationContext.getBeanFactory().registerSingleton("log", getLog());

    applicationContext.refresh();
}