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.asakusafw.runtime.stage.launcher.LauncherOptionsParser.java

private URLClassLoader buildApplicationClassLoader(List<Path> libraryPaths, String applicationClassName)
        throws IOException, InterruptedException {
    List<URL> libraries = processLibraries(libraryPaths, applicationClassName);
    ClassLoader parent = configuration.getClassLoader();
    URLClassLoader application = AccessController
            .doPrivileged((PrivilegedAction<URLClassLoader>) () -> new URLClassLoader(
                    libraries.toArray(new URL[libraries.size()]), parent));
    this.applicationResources.add(application);
    configuration.setClassLoader(application);
    return application;
}

From source file:org.fusesource.hawtjni.generator.HawtJNI.java

private void findClasses(ArrayList<JNIClass> jni, ArrayList<JNIClass> structs) throws UsageException {

    ArrayList<URL> urls = new ArrayList<URL>();
    for (String classpath : classpaths) {
        String[] fileNames = classpath.replace(';', ':').split(":");
        for (String fileName : fileNames) {
            try {
                File file = new File(fileName);
                if (file.isDirectory()) {
                    urls.add(new URL(url(file) + "/"));
                } else {
                    urls.add(new URL(url(file)));
                }// w w  w  .j  a v a2 s .  co  m
            } catch (Exception e) {
                throw new UsageException("Invalid class path.  Not a valid file: " + fileName);
            }
        }
    }
    LinkedHashSet<Class<?>> jniClasses = new LinkedHashSet<Class<?>>();
    try {
        URLClassLoader classLoader = new URLClassLoader(array(URL.class, urls),
                JniClass.class.getClassLoader());
        UrlSet urlSet = new UrlSet(classLoader);
        urlSet = urlSet.excludeJavaHome();
        ClassFinder finder = new ClassFinder(classLoader, urlSet.getUrls());
        collectMatchingClasses(finder, JniClass.class, jniClasses);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (Class<?> clazz : jniClasses) {
        ReflectClass rc = new ReflectClass(clazz);
        if (rc.getFlag(ClassFlag.STRUCT)) {
            structs.add(rc);
        }
        if (!rc.getNativeMethods().isEmpty()) {
            jni.add(rc);
        }
    }
}

From source file:com.alexnederlof.jasperreport.JasperReporter.java

private ClassLoader getClassLoader(ClassLoader classLoader) throws MojoExecutionException {
    List<URL> classpath = new ArrayList<URL>();
    if (classpathElements != null) {
        for (String element : classpathElements) {
            try {
                File f = new File(element);
                classpath.add(f.toURI().toURL());
                log.debug("Added to classpath " + element);
            } catch (Exception e) {
                throw new MojoExecutionException("Error setting classpath " + element + " " + e.getMessage());
            }/*from   w w  w.j av a 2  s .c  o  m*/
        }
    }

    URL[] urls = classpath.toArray(new URL[classpath.size()]);
    return new URLClassLoader(urls, classLoader);
}

From source file:org.apache.sysml.runtime.codegen.CodegenUtils.java

private static byte[] getClassAsByteArray(String name) {
    String classAsPath = name.replace('.', '/') + ".class";

    URLClassLoader classLoader = null;
    InputStream stream = null;/*from ww  w  .  ja  va  2 s .  c o m*/

    try {
        //dynamically load compiled class
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir },
                CodegenUtils.class.getClassLoader());
        stream = classLoader.getResourceAsStream(classAsPath);
        return IOUtils.toByteArray(stream);
    } catch (IOException e) {
        throw new DMLRuntimeException(e);
    } finally {
        IOUtilFunctions.closeSilently(classLoader);
        IOUtilFunctions.closeSilently(stream);
    }
}

From source file:org.bigloupe.web.scheduler.InitializeScheduler.java

private ClassLoader getBaseClassloader() throws MalformedURLException {
    final ClassLoader retVal;

    String hadoopHome = System.getenv("HADOOP_HOME");
    if (hadoopHome == null) {
        logger.info("HADOOP_HOME not set, using default hadoop config.");
        retVal = getClass().getClassLoader();
    } else {/* ww  w .  j av  a 2s .  co m*/
        logger.info("Using hadoop config found in " + hadoopHome);
        retVal = new URLClassLoader(new URL[] { new File(hadoopHome, "conf").toURI().toURL() },
                getClass().getClassLoader());
    }

    return retVal;
}

From source file:com.huawei.streaming.cql.DriverContext.java

private ClassLoader addToClassPath(ClassLoader classLoader, String[] newPaths) throws ExecutorException {
    URLClassLoader loader = (URLClassLoader) classLoader;
    List<URL> curPath = Arrays.asList(loader.getURLs());
    List<URL> newPath = Lists.newArrayList();

    for (URL onePath : curPath) {
        newPath.add(onePath);//from w ww.j  a  va2 s  .com
    }
    curPath = newPath;
    if (newPaths != null) {
        for (String onestr : newPaths) {
            if (StringUtils.indexOf(onestr, FILE_PREFIX) == 0) {
                onestr = StringUtils.substring(onestr, CQLConst.I_7);
            }

            URL oneurl = getFileURL(onestr);

            if (!curPath.contains(oneurl)) {
                curPath.add(oneurl);
            }
        }
    }

    return new URLClassLoader(curPath.toArray(new URL[0]), loader);
}

From source file:org.kchine.rpf.db.DBLayer.java

public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException {
    Statement stmt = null;// ww w .ja v  a  2  s  . c  om
    ResultSet rset = null;
    try {
        checkConnection();
        stmt = _connection.createStatement();
        rset = stmt.executeQuery("select STUB_HEX,CODEBASE from SERVANTS where NAME='" + name + "'");
        if (rset.next()) {

            final String stubHex = rset.getString(1);
            final String codeBaseStr = rset.getString(2);
            final ClassLoader cl = (codeBaseStr != null
                    ? new URLClassLoader(PoolUtils.getURLS(codeBaseStr), DBLayer.class.getClassLoader())
                    : DBLayer.class.getClassLoader());
            System.out.println("codeBaseStr ::" + codeBaseStr);

            final Object[] resultHolder = new Object[1];
            Runnable lookupRunnable = new Runnable() {
                public void run() {
                    try {
                        resultHolder[0] = hexToStub(stubHex, cl);
                    } catch (Exception e) {
                        final boolean wasInterrupted = Thread.interrupted();
                        if (wasInterrupted) {
                            resultHolder[0] = new LookUpInterrupted();
                        } else {
                            resultHolder[0] = e;
                        }
                    }
                }
            };

            Thread lookupThread = InterruptibleRMIThreadFactory.getInstance().newThread(lookupRunnable);
            lookupThread.start();

            long t1 = System.currentTimeMillis();
            while (resultHolder[0] == null) {
                if ((System.currentTimeMillis() - t1) > PoolUtils.LOOKUP_TIMEOUT_MILLISEC) {
                    lookupThread.interrupt();
                    resultHolder[0] = new LookUpTimeout();
                    registerPingFailure(name);
                    break;
                }
                Thread.sleep(10);
            }

            if (resultHolder[0] instanceof Throwable) {
                if (resultHolder[0] instanceof NotBoundException)
                    throw (NotBoundException) resultHolder[0];
                else
                    throw (RemoteException) resultHolder[0];
            }

            return (Remote) resultHolder[0];

        } else {
            throw new NotBoundException();
        }
    } catch (NotBoundException nbe) {
        throw nbe;
    } catch (AccessException ae) {
        throw ae;
    } catch (LookUpTimeout lue) {
        throw lue;
    } catch (LookUpInterrupted lui) {
        throw lui;
    } catch (SQLException sqle) {
        if (isNoConnectionError(sqle) && canReconnect()) {
            return lookup(name);
        } else {
            throw new RemoteException("", (sqle));
        }
    } catch (Exception e) {
        throw new RemoteException("", (e));
    } finally {
        if (rset != null)
            try {
                stmt.close();
            } catch (Exception e) {
                throw new RemoteException("", (e));
            }
        if (stmt != null)
            try {
                stmt.close();
            } catch (Exception e) {
                throw new RemoteException("", (e));
            }
    }
}

From source file:io.druid.initialization.Initialization.java

/**
 * @param extension The File instance of the extension we want to load
 *
 * @return a URLClassLoader that loads all the jars on which the extension is dependent
 *
 * @throws MalformedURLException//from w  ww . j av a2s  . c om
 */
public static URLClassLoader getClassLoaderForExtension(File extension) throws MalformedURLException {
    URLClassLoader loader = loadersMap.get(extension);
    if (loader == null) {
        final Collection<File> jars = FileUtils.listFiles(extension, new String[] { "jar" }, false);
        final URL[] urls = new URL[jars.size()];
        int i = 0;
        for (File jar : jars) {
            final URL url = jar.toURI().toURL();
            log.info("added URL[%s]", url);
            urls[i++] = url;
        }
        loadersMap.putIfAbsent(extension, new URLClassLoader(urls, Initialization.class.getClassLoader()));
        loader = loadersMap.get(extension);
    }
    return loader;
}

From source file:com.wangzhe.autojoin.wangfw.server.jetty9.JettyRunner.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  ww w  .  ja va  2  s.  c o m*/
private ClassLoader getUrlClassLoader() {
    ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
    // jspClassLoader=Thread.currentThread().getContextClassLoader();
    // //???
    return jspClassLoader;
}

From source file:org.apache.hadoop.util.GenericOptionsParser.java

/**
 * Modify configuration according user-specified generic options
 * @param conf Configuration to be modified
 * @param line User-specified generic options
 *///  w w w.j  a  v a2 s .  com
private void processGeneralOptions(Configuration conf, CommandLine line) throws IOException {
    if (line.hasOption("fs")) {
        FileSystem.setDefaultUri(conf, line.getOptionValue("fs"));
    }

    if (line.hasOption("jt")) {
        String optionValue = line.getOptionValue("jt");
        if (optionValue.equalsIgnoreCase("local")) {
            conf.set("mapreduce.framework.name", optionValue);
        }

        conf.set("yarn.resourcemanager.address", optionValue, "from -jt command line option");
    }
    if (line.hasOption("conf")) {
        String[] values = line.getOptionValues("conf");
        for (String value : values) {
            conf.addResource(new Path(value));
        }
    }
    if (line.hasOption("libjars")) {
        conf.set("tmpjars", validateFiles(line.getOptionValue("libjars"), conf),
                "from -libjars command line option");
        //setting libjars in client classpath
        URL[] libjars = getLibJars(conf);
        if (libjars != null && libjars.length > 0) {
            conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));
            Thread.currentThread().setContextClassLoader(
                    new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader()));
        }
    }
    if (line.hasOption("files")) {
        conf.set("tmpfiles", validateFiles(line.getOptionValue("files"), conf),
                "from -files command line option");
    }
    if (line.hasOption("archives")) {
        conf.set("tmparchives", validateFiles(line.getOptionValue("archives"), conf),
                "from -archives command line option");
    }
    if (line.hasOption('D')) {
        String[] property = line.getOptionValues('D');
        for (String prop : property) {
            String[] keyval = prop.split("=", 2);
            if (keyval.length == 2) {
                conf.set(keyval[0], keyval[1], "from command line");
            }
        }
    }
    conf.setBoolean("mapreduce.client.genericoptionsparser.used", true);

    // tokensFile
    if (line.hasOption("tokenCacheFile")) {
        String fileName = line.getOptionValue("tokenCacheFile");
        // check if the local file exists
        FileSystem localFs = FileSystem.getLocal(conf);
        Path p = localFs.makeQualified(new Path(fileName));
        if (!localFs.exists(p)) {
            throw new FileNotFoundException("File " + fileName + " does not exist.");
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("setting conf tokensFile: " + fileName);
        }
        UserGroupInformation.getCurrentUser().addCredentials(Credentials.readTokenStorageFile(p, conf));
        conf.set("mapreduce.job.credentials.json", p.toString(), "from -tokenCacheFile command line option");

    }
}