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:de.metanome.backend.algorithm_loading.AlgorithmFinder.java

/**
 * Finds out which subclass of Algorithm is implemented by the source code in the
 * algorithmJarFile.//from w  w  w  . j av  a  2 s.co  m
 *
 * @param algorithmJarFile the algorithm's jar file
 * @return the interfaces of the algorithm implementation in algorithmJarFile
 * @throws java.io.IOException if the algorithm jar file could not be opened
 * @throws java.lang.ClassNotFoundException if the algorithm contains a not supported interface
 */
public Set<Class<?>> getAlgorithmInterfaces(File algorithmJarFile) throws IOException, ClassNotFoundException {
    JarFile jar = new JarFile(algorithmJarFile);

    Manifest man = jar.getManifest();
    Attributes attr = man.getMainAttributes();
    String className = attr.getValue(bootstrapClassTagName);

    URL[] url = { algorithmJarFile.toURI().toURL() };
    ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader());

    Class<?> algorithmClass;
    try {
        algorithmClass = Class.forName(className, false, loader);
    } catch (ClassNotFoundException e) {
        System.out.println("Could not find class " + className);
        return new HashSet<>();
    } finally {
        jar.close();
    }

    return new HashSet<>(ClassUtils.getAllInterfaces(algorithmClass));
}

From source file:com.googlecode.jsonschema2pojo.ant.Jsonschema2PojoTask.java

/**
 * Build a classloader using the additional elements specified in
 * <code>classpath</code> and <code>classpathRef</code>.
 * //from  w ww. j av  a 2s . c  o m
 * @return a new classloader that includes the extra path elements found in
 *         the <code>classpath</code> and <code>classpathRef</code> config
 *         values
 */
private ClassLoader buildExtendedClassloader() {
    final List<URL> classpathUrls = new ArrayList<URL>();
    for (String pathElement : getClasspath().list()) {
        try {
            classpathUrls.add(new File(pathElement).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new BuildException(
                    "Unable to use classpath entry as it could not be understood as a valid URL: "
                            + pathElement,
                    e);
        }
    }

    final ClassLoader parentClassloader = Thread.currentThread().getContextClassLoader();

    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parentClassloader);
        }
    });
}

From source file:com.visural.stereotyped.ui.service.StereotypeServiceImpl.java

private synchronized void initComponentClassLoader() {
    if (urlLoader == null) {
        File jarDir = new File(getComponentJarsPath());
        if (jarDir.exists() && jarDir.isDirectory()) {
            try {
                ArrayList<URL> urls = new ArrayList<URL>();
                File[] files = jarDir.listFiles();
                for (File file : files) {
                    if (file.isFile() && file.getName().endsWith(".jar")) {
                        urls.add(file.toURI().toURL());
                    }/*from   w w w. ja v  a2s.c  o  m*/
                }
                urlLoader = new URLClassLoader(urls.toArray(new URL[] {}),
                        Thread.currentThread().getContextClassLoader());
            } catch (Exception e) {
                throw new IllegalStateException("Failed while loading component jars.", e);
            }
        } else {
            throw new IllegalStateException("Bad component jar folder: " + getComponentJarsPath());
        }
    }
}

From source file:eu.peppol.persistence.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 {/*from w w w . jav a2s.c  o m*/
        Connection connection = basicDataSource.getConnection();
        assertNotNull(connection);
    } catch (SQLException e) {
        // As expected when using DBCP 1.4
    }
}

From source file:org.mitre.ccv.mapred.SortKmerRevisedRelativeEntropies.java

@Override
public int run(String[] args) throws Exception {
    JobConf conf = new JobConf(getConf());
    boolean cleanLogs = false;

    // @TODO: use commons getopts, org.apache.hadoop.util.GenericOptionsParser used it
    ArrayList<String> other_args = new ArrayList<String>();
    for (int i = 0; i < args.length; ++i) {
        try {//w  ww  .j a v a  2 s . c o m
            if ("-m".equals(args[i])) {
                conf.setNumMapTasks(Integer.parseInt(args[++i]));
            } else if ("-r".equals(args[i])) {
                conf.setNumReduceTasks(Integer.parseInt(args[++i]));
            } else if ("-c".equals(args[i])) {
                cleanLogs = true;
            } else if ("-t".equals(args[i])) {
                conf.setBoolean(TEXT_OUTPUT, true);
            } else if ("-libjars".equals(args[i])) {
                conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf));

                URL[] libjars = FileUtils.getLibJars(conf);
                if (libjars != null && libjars.length > 0) {
                    // Add libjars to client/tasks classpath
                    conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));
                    // Adds libjars to our classpath
                    Thread.currentThread().setContextClassLoader(
                            new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader()));
                }
            } else {
                other_args.add(args[i]);
            }
        } catch (NumberFormatException except) {
            System.out.println("ERROR: Integer expected instead of " + args[i]);
            return printUsage();
        } catch (ArrayIndexOutOfBoundsException except) {
            System.out.println("ERROR: Required parameter missing from " + args[i - 1]);
            return printUsage();
        }
    }
    // Make sure there are exactly 2 parameters left.
    if (other_args.size() != 2) {
        System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 3.");
        return printUsage();
    }

    return initJob(conf, other_args.get(0), other_args.get(1), cleanLogs);
}

From source file:azkaban.webapp.TriggerPluginLoader.java

public Map<String, TriggerPlugin> loadTriggerPlugins(final Context root) {
    /*/*from   w w  w. java2  s.  c om*/
     * TODO spyne: TriggerPluginLoader should not have any dependency on Azkaban Web Server
     **/
    final AzkabanWebServer azkabanWebServer = SERVICE_PROVIDER.getInstance(AzkabanWebServer.class);
    final File triggerPluginPath = new File(this.pluginPath);
    if (!triggerPluginPath.exists()) {
        return new HashMap<>();
    }

    final Map<String, TriggerPlugin> installedTriggerPlugins = new HashMap<>();
    final ClassLoader parentLoader = AzkabanWebServer.class.getClassLoader();
    final File[] pluginDirs = triggerPluginPath.listFiles();
    final ArrayList<String> jarPaths = new ArrayList<>();
    for (final File pluginDir : pluginDirs) {
        if (!pluginDir.exists()) {
            log.error("Error! Trigger plugin path " + pluginDir.getPath() + " doesn't exist.");
            continue;
        }

        if (!pluginDir.isDirectory()) {
            log.error("The plugin path " + pluginDir + " is not a directory.");
            continue;
        }

        // Load the conf directory
        final File propertiesDir = new File(pluginDir, "conf");
        Props pluginProps = null;
        if (propertiesDir.exists() && propertiesDir.isDirectory()) {
            final File propertiesFile = new File(propertiesDir, "plugin.properties");
            final File propertiesOverrideFile = new File(propertiesDir, "override.properties");

            if (propertiesFile.exists()) {
                if (propertiesOverrideFile.exists()) {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile, propertiesOverrideFile);
                } else {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile);
                }
            } else {
                log.error("Plugin conf file " + propertiesFile + " not found.");
                continue;
            }
        } else {
            log.error("Plugin conf path " + propertiesDir + " not found.");
            continue;
        }

        final String pluginName = pluginProps.getString("trigger.name");
        final List<String> extLibClasspath = pluginProps.getStringList("trigger.external.classpaths",
                (List<String>) null);

        final String pluginClass = pluginProps.getString("trigger.class");
        if (pluginClass == null) {
            log.error("Trigger class is not set.");
        } else {
            log.error("Plugin class " + pluginClass);
        }

        URLClassLoader urlClassLoader = null;
        final File libDir = new File(pluginDir, "lib");
        if (libDir.exists() && libDir.isDirectory()) {
            final File[] files = libDir.listFiles();

            final ArrayList<URL> urls = new ArrayList<>();
            for (int i = 0; i < files.length; ++i) {
                try {
                    final URL url = files[i].toURI().toURL();
                    urls.add(url);
                } catch (final MalformedURLException e) {
                    log.error(e);
                }
            }
            if (extLibClasspath != null) {
                for (final String extLib : extLibClasspath) {
                    try {
                        final File file = new File(pluginDir, extLib);
                        final URL url = file.toURI().toURL();
                        urls.add(url);
                    } catch (final MalformedURLException e) {
                        log.error(e);
                    }
                }
            }

            urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader);
        } else {
            log.error("Library path " + propertiesDir + " not found.");
            continue;
        }

        Class<?> triggerClass = null;
        try {
            triggerClass = urlClassLoader.loadClass(pluginClass);
        } catch (final ClassNotFoundException e) {
            log.error("Class " + pluginClass + " not found.");
            continue;
        }

        final String source = FileIOUtils.getSourcePathFromClass(triggerClass);
        log.info("Source jar " + source);
        jarPaths.add("jar:file:" + source);

        Constructor<?> constructor = null;
        try {
            constructor = triggerClass.getConstructor(String.class, Props.class, Context.class,
                    AzkabanWebServer.class);
        } catch (final NoSuchMethodException e) {
            log.error("Constructor not found in " + pluginClass);
            continue;
        }

        Object obj = null;
        try {
            obj = constructor.newInstance(pluginName, pluginProps, root, azkabanWebServer);
        } catch (final Exception e) {
            log.error(e);
        }

        if (!(obj instanceof TriggerPlugin)) {
            log.error("The object is not an TriggerPlugin");
            continue;
        }

        final TriggerPlugin plugin = (TriggerPlugin) obj;
        installedTriggerPlugins.put(pluginName, plugin);
    }

    // Velocity needs the jar resource paths to be set.
    final String jarResourcePath = StringUtils.join(jarPaths, ", ");
    log.info("Setting jar resource path " + jarResourcePath);
    final VelocityEngine ve = azkabanWebServer.getVelocityEngine();
    ve.addProperty("jar.resource.loader.path", jarResourcePath);

    return installedTriggerPlugins;
}

From source file:org.apache.zeppelin.spark.PySparkInterpreter.java

@Override
public void open() {
    DepInterpreter depInterpreter = getDepInterpreter();

    // load libraries from Dependency Interpreter
    URL[] urls = new URL[0];

    if (depInterpreter != null) {
        DependencyContext depc = depInterpreter.getDependencyContext();
        if (depc != null) {
            List<File> files = depc.getFiles();
            List<URL> urlList = new LinkedList<URL>();
            if (files != null) {
                for (File f : files) {
                    try {
                        urlList.add(f.toURI().toURL());
                    } catch (MalformedURLException e) {
                        logger.error("Error", e);
                    }/*  ww w.  j  a va2s  .c om*/
                }

                urls = urlList.toArray(urls);
            }
        }
    }

    ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
    try {
        URLClassLoader newCl = new URLClassLoader(urls, oldCl);
        Thread.currentThread().setContextClassLoader(newCl);
        createGatewayServerAndStartScript();
    } catch (Exception e) {
        logger.error("Error", e);
        throw new InterpreterException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(oldCl);
    }
}

From source file:io.fabric8.maven.core.util.ClassUtil.java

public static URLClassLoader createProjectClassLoader(final MavenProject project, Logger log) {

    try {//from   w  w w. j  a va  2 s .  c  o  m

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

        for (String element : project.getCompileClasspathElements()) {
            compileJars.add(new File(element).toURI().toURL());
        }

        return new URLClassLoader(compileJars.toArray(new URL[compileJars.size()]),
                PluginServiceFactory.class.getClassLoader());

    } catch (Exception e) {
        log.warn("Instructed to use project classpath, but cannot. Continuing build if we can: ", e);
    }

    // return an empty CL .. don't want to have to deal with NULL later
    // if somehow we incorrectly call this method
    return new URLClassLoader(new URL[] {});
}

From source file:org.gradle.api.plugins.jetty.AbstractJettyRunTask.java

@TaskAction
protected void start() {
    ClassLoader originalClassloader = Server.class.getClassLoader();
    List<File> additionalClasspath = new ArrayList<File>();
    for (File additionalRuntimeJar : getAdditionalRuntimeJars()) {
        additionalClasspath.add(additionalRuntimeJar);
    }/*from   w ww  .  j av  a  2 s .c  o m*/
    URLClassLoader jettyClassloader = new URLClassLoader(
            new DefaultClassPath(additionalClasspath).getAsURLArray(), originalClassloader);
    try {
        Thread.currentThread().setContextClassLoader(jettyClassloader);
        startJetty();
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassloader);
    }
}

From source file:com.google.api.server.spi.tools.GetDiscoveryDocAction.java

/**
 * Generates a Java client library for an API.  Combines the steps of generating API
 * configuration, generating Discovery doc and generating client library into one.
 * @param classPath Class path to load service classes and their dependencies
 * @param outputDirPath Directory to write output files into
 * @param warPath Directory or file containing a WAR layout
 * @param serviceClassNames Array of service class names of the API
 * @param debug Whether or not to output intermediate output files
 * @param outputToDisk Whether or not to output discovery docs to disk
 *///from  w w  w  .  ja v a  2  s. c  om
public Map<String, String> getDiscoveryDoc(URL[] classPath, String outputDirPath, String warPath,
        List<String> serviceClassNames, boolean debug, boolean outputToDisk)
        throws ClassNotFoundException, IOException, ApiConfigException {
    File outputDir = new File(outputDirPath);
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException(outputDirPath + " is not a directory");
    }

    ClassLoader classLoader = new URLClassLoader(classPath, getClass().getClassLoader());
    ApiConfig.Factory configFactory = new ApiConfig.Factory();
    TypeLoader typeLoader = new TypeLoader(classLoader);
    SchemaRepository schemaRepository = new SchemaRepository(typeLoader);
    ApiConfigValidator validator = new ApiConfigValidator(typeLoader, schemaRepository);
    DiscoveryGenerator discoveryGenerator = new DiscoveryGenerator(typeLoader);
    List<ApiConfig> apiConfigs = Lists.newArrayListWithCapacity(serviceClassNames.size());
    ImmutableListMultimap<ApiKey, ApiConfig> configsByKey = Multimaps.index(apiConfigs,
            new Function<ApiConfig, ApiKey>() {
                @Override
                public ApiKey apply(ApiConfig input) {
                    return input.getApiKey();
                }
            });
    for (ApiKey key : configsByKey.keys()) {
        validator.validate(configsByKey.get(key));
    }
    ApiConfigLoader configLoader = new ApiConfigLoader(configFactory, typeLoader,
            new ApiConfigAnnotationReader(typeLoader.getAnnotationTypes()));
    ServiceContext serviceContext = ServiceContext.create(AppEngineUtil.getApplicationId(warPath),
            ServiceContext.DEFAULT_API_NAME);
    for (Class<?> serviceClass : loadClasses(classLoader, serviceClassNames)) {
        apiConfigs.add(configLoader.loadConfiguration(serviceContext, serviceClass));
    }
    DiscoveryGenerator.Result result = discoveryGenerator.writeDiscovery(apiConfigs,
            new DiscoveryContext().setHostname(serviceContext.getAppHostName()), schemaRepository);
    ObjectWriter writer = ObjectMapperUtil.createStandardObjectMapper().writer(new EndpointsPrettyPrinter());
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    for (Map.Entry<ApiKey, RestDescription> entry : result.discoveryDocs().entrySet()) {
        ApiKey key = entry.getKey();
        String discoveryDocFilePath = outputDir + "/" + key.getName() + "-" + key.getVersion()
                + "-rest.discovery";
        String docString = writer.writeValueAsString(entry.getValue());
        if (outputToDisk) {
            Files.write(docString, new File(discoveryDocFilePath), UTF_8);
            System.out.println("API Discovery Document written to " + discoveryDocFilePath);
        }
        builder.put(discoveryDocFilePath, docString);
    }
    return builder.build();
}