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.pentaho.platform.repository.solution.filebased.FileBasedSolutionRepository.java

public ClassLoader getClassLoader(final String path) {
    File localeDir = new File(PentahoSystem.getApplicationContext().getSolutionPath(path));
    try {//from   w  w  w  . java 2 s.c  o m
        URLClassLoader loader = new URLClassLoader(new URL[] { localeDir.toURL() }, null);
        return loader;
    } catch (Exception e) {
        error(Messages.getErrorString("SolutionRepository.ERROR_0024_CREATING_CLASSLOADER")); //$NON-NLS-1$
    }
    return null;
}

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

private static URLClassLoader getOxalisClassLoaderForJdbc(String jdbcDriverClassPath) {
    URLClassLoader urlClassLoader = null;

    try {/*w w  w . j  a va 2  s.  c o  m*/
        urlClassLoader = new URLClassLoader(new URL[] { new URL(jdbcDriverClassPath) },
                Thread.currentThread().getContextClassLoader());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid jdbc driver class path: '" + jdbcDriverClassPath
                + "', check property oxalis.jdbc.class.path. Cause: " + e.getMessage(), e);
    }
    return urlClassLoader;
}

From source file:org.apache.wiki.util.ClassUtil.java

/**
 * Setup the plugin classloader.//from  w w  w.  ja va  2 s. c  om
 * Check if there are external JARS to add via property {@link org.apache.wiki.api.engine.PluginManager#PROP_EXTERNALJARS}
 *
 * @return the classloader that can load classes from the configured external jars or
 *         ,if not specified, the classloader that loaded this class.
 * @param externaljars
 */
private static ClassLoader setupClassLoader(List<String> externaljars) {
    classLoaderSetup = true;
    log.info("setting up classloaders for external (plugin) jars");
    if (externaljars.size() == 0) {
        log.info("no external jars configured, using standard classloading");
        return ClassUtil.class.getClassLoader();
    }
    URL[] urls = new URL[externaljars.size()];
    int i = 0;
    try {
        for (String externaljar : externaljars) {
            File jarFile = new File(externaljar);
            URL ucl = jarFile.toURI().toURL();
            urls[i++] = ucl;
            log.info("added " + ucl + " to list of external jars");
        }
    } catch (MalformedURLException e) {
        log.error("exception while setting up classloaders for external jars via property"
                + PluginManager.PROP_EXTERNALJARS + ", continuing without external jars.");
        return ClassUtil.class.getClassLoader();
    }
    return new URLClassLoader(urls, ClassUtil.class.getClassLoader());
}

From source file:org.apache.zeppelin.interpreter.InterpreterFactory.java

private void init() throws InterpreterException, IOException {
    ClassLoader oldcl = Thread.currentThread().getContextClassLoader();

    // Load classes
    File[] interpreterDirs = new File(conf.getInterpreterDir()).listFiles();
    if (interpreterDirs != null) {
        for (File path : interpreterDirs) {
            logger.info("Reading " + path.getAbsolutePath());
            URL[] urls = null;/*w w  w.j a  v  a  2 s.c o m*/
            try {
                urls = recursiveBuildLibList(path);
            } catch (MalformedURLException e1) {
                logger.error("Can't load jars ", e1);
            }
            URLClassLoader ccl = new URLClassLoader(urls, oldcl);

            for (String className : interpreterClassList) {
                try {
                    Class.forName(className, true, ccl);
                    Set<String> keys = Interpreter.registeredInterpreters.keySet();
                    for (String intName : keys) {
                        if (className.equals(Interpreter.registeredInterpreters.get(intName).getClassName())) {
                            Interpreter.registeredInterpreters.get(intName).setPath(path.getAbsolutePath());
                            logger.info("Interpreter " + intName + " found. class=" + className);
                            cleanCl.put(path.getAbsolutePath(), ccl);
                        }
                    }
                } catch (ClassNotFoundException e) {
                    // nothing to do
                }
            }
        }
    }

    loadFromFile();

    // if no interpreter settings are loaded, create default set
    synchronized (interpreterSettings) {
        if (interpreterSettings.size() == 0) {
            HashMap<String, List<RegisteredInterpreter>> groupClassNameMap = new HashMap<String, List<RegisteredInterpreter>>();

            for (String k : Interpreter.registeredInterpreters.keySet()) {
                RegisteredInterpreter info = Interpreter.registeredInterpreters.get(k);

                if (!groupClassNameMap.containsKey(info.getGroup())) {
                    groupClassNameMap.put(info.getGroup(), new LinkedList<RegisteredInterpreter>());
                }

                groupClassNameMap.get(info.getGroup()).add(info);
            }

            for (String className : interpreterClassList) {
                for (String groupName : groupClassNameMap.keySet()) {
                    List<RegisteredInterpreter> infos = groupClassNameMap.get(groupName);

                    boolean found = false;
                    Properties p = new Properties();
                    for (RegisteredInterpreter info : infos) {
                        if (found == false && info.getClassName().equals(className)) {
                            found = true;
                        }

                        for (String k : info.getProperties().keySet()) {
                            p.put(k, info.getProperties().get(k).getDefaultValue());
                        }
                    }

                    if (found) {
                        // add all interpreters in group
                        add(groupName, groupName, defaultOption, p);
                        groupClassNameMap.remove(groupName);
                        break;
                    }
                }
            }
        }
    }

    for (String settingId : interpreterSettings.keySet()) {
        InterpreterSetting setting = interpreterSettings.get(settingId);
        logger.info("Interpreter setting group {} : id={}, name={}", setting.getGroup(), settingId,
                setting.getName());
        for (Interpreter interpreter : setting.getInterpreterGroup()) {
            logger.info("  className = {}", interpreter.getClassName());
        }
    }
}

From source file:org.apache.ode.jbi.OdeServiceUnit.java

public ClassLoader getConfigurationClassLoader() throws DeploymentException {
    return new URLClassLoader(getDefaultLocations(), getClass().getClassLoader());
}

From source file:no.sr.ringo.persistence.jdbc.RingoDataSourceFactoryDbcpImpl.java

/**
 * Creates a {@link URLClassLoader} if the supplied JDBC driver class path was supplied, otherwise uses the
 * default class loader.//from   ww w  .j  ava2  s.  c  o m
 *
 * @param jdbcDriverClassPath
 * @return
 */
private static ClassLoader getOxalisClassLoaderForJdbc(Optional<String> jdbcDriverClassPath) {
    URLClassLoader urlClassLoader;

    if (!jdbcDriverClassPath.isPresent()) {
        return Thread.currentThread().getContextClassLoader();
    } else {
        try {
            urlClassLoader = new URLClassLoader(new URL[] { new URL(jdbcDriverClassPath.get()) },
                    Thread.currentThread().getContextClassLoader());
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Invalid jdbc driver class path: '" + jdbcDriverClassPath, e);
        }
        return urlClassLoader;
    }
}

From source file:com.heimuheimu.runningtask.task.service.support.SimpleURLClassLoaderFactory.java

@Override
public URLClassLoader create(boolean useParentClassLoader, String... localFilePaths)
        throws NullPointerException, IllegalArgumentException {
    long startTime = System.currentTimeMillis();
    URL[] urls = getURLArray(localFilePaths);
    URLClassLoader parent = useParentClassLoader ? parentClassLoader : null;
    URLClassLoader loader = new URLClassLoader(urls, parent);
    LOG.info("Create URLClassLoader success. Cost `{}`ms. Local file paths: `{}`.",
            System.currentTimeMillis() - startTime, Arrays.toString(urls));
    return loader;
}

From source file:org.ow2.chameleon.core.utils.FrameworkClassLoader.java

/**
 * Creates the classloader./*from   w w w .  ja v a 2  s  . c  o m*/
 * <p>
 * All jars from the 'libs' directory are added to the classloader.
 *
 * @param basedir               the base directory. The 'libs' folder must be a direct child of this directory.
 * @param librariesParentPolicy the delegation policy for the library classloader
 */
private FrameworkClassLoader(File basedir, String librariesParentPolicy) {
    super(jars(new File(basedir.getAbsoluteFile(), "libs")), FrameworkClassLoader.class.getClassLoader());

    ClassLoader parent = null;
    if (librariesParentPolicy == null || "system".equalsIgnoreCase(librariesParentPolicy)) {
        parent = null;
    } else if ("application".equalsIgnoreCase(librariesParentPolicy)) {
        parent = FrameworkClassLoader.class.getClassLoader();
    } else if ("parent".equalsIgnoreCase(librariesParentPolicy)) {
        parent = FrameworkClassLoader.class.getClassLoader().getParent();
    } else {
        throw new IllegalArgumentException("Unrecognized 'chameleon.libraries.parent', are"
                + " supported: {system, application and parent}");
    }

    libsClassLoader = new URLClassLoader(jars(new File(basedir.getAbsoluteFile(), "libs")), parent);
}

From source file:org.kuali.kra.test.infrastructure.ApplicationServer.java

/**
 * The jetty server's jsp compiler does not have access to the classpath artifacts to compile the jsps.
 * This method takes the current webapp classloader and creates one containing all of the
 * classpath artifacts on the test's classpath.
 *
 * See http://stackoverflow.com/questions/17685330/how-do-you-get-embedded-jetty-9-to-successfully-resolve-the-jstl-uri
 *
 * @param current the current webapp classpath
 * @return a classloader to replace it with
 * @throws IOException if an error occurs creating the classloader
 */// w  w w .  j av  a2s  .c  o  m
private static ClassLoader createClassLoaderForJasper(ClassLoader current) throws IOException {
    // Replace classloader with a new classloader with all URLs in manifests
    // from the parent loader bubbled up so Jasper looks at them.
    final ClassLoader parentLoader = current.getParent();
    if (current instanceof WebAppClassLoader && parentLoader instanceof URLClassLoader) {
        final LinkedList<URL> allURLs = new LinkedList<URL>(
                Arrays.asList(((URLClassLoader) parentLoader).getURLs()));

        for (URL url : ((LinkedList<URL>) allURLs.clone())) {
            try {
                final URLConnection conn = new URL("jar:" + url.toString() + "!/").openConnection();
                if (conn instanceof JarURLConnection) {
                    final JarURLConnection jconn = (JarURLConnection) conn;
                    final Manifest jarManifest = jconn.getManifest();
                    final String[] classPath = ((String) jarManifest.getMainAttributes().getValue("Class-Path"))
                            .split(" ");

                    for (String cpurl : classPath) {
                        allURLs.add(new URL(url, cpurl));
                    }
                }
            } catch (IOException | NullPointerException e) {
                //do nothing
            }
        }
        LOG.info("Creating new classloader for Application Server");
        return new WebAppClassLoader(new URLClassLoader(allURLs.toArray(new URL[] {}), parentLoader),
                ((WebAppClassLoader) current).getContext());
    }
    LOG.warn("Cannot create new classloader for app server " + current);
    return current;
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.TestApplicationHistoryServer.java

@Before
@SuppressWarnings("all")
public void setup() throws URISyntaxException, IOException {
    folder.create();//from  w w  w.  j  a va  2s  . co  m
    File hbaseSite = folder.newFile("hbase-site.xml");
    File amsSite = folder.newFile("ams-site.xml");

    FileUtils.writeStringToFile(hbaseSite,
            "<configuration>\n" + "  <property>\n" + "    <name>hbase.defaults.for.version.skip</name>\n"
                    + "    <value>true</value>\n" + "  </property>" + "  <property> "
                    + "    <name>hbase.zookeeper.quorum</name>\n" + "    <value>localhost</value>\n"
                    + "  </property>" + "</configuration>");

    FileUtils.writeStringToFile(amsSite, "<configuration>\n" + "  <property>\n" + "    <name>test</name>\n"
            + "    <value>testReady</value>\n" + "  </property>\n" + "  <property>\n"
            + "    <name>timeline.metrics.host.aggregator.hourly.disabled</name>\n"
            + "    <value>true</value>\n" + "    <description>\n"
            + "      Disable host based hourly aggregations.\n" + "    </description>\n" + "  </property>\n"
            + "  <property>\n" + "    <name>timeline.metrics.host.aggregator.minute.disabled</name>\n"
            + "    <value>true</value>\n" + "    <description>\n"
            + "      Disable host based minute aggregations.\n" + "    </description>\n" + "  </property>\n"
            + "  <property>\n" + "    <name>timeline.metrics.cluster.aggregator.hourly.disabled</name>\n"
            + "    <value>true</value>\n" + "    <description>\n"
            + "      Disable cluster based hourly aggregations.\n" + "    </description>\n" + "  </property>\n"
            + "  <property>\n" + "    <name>timeline.metrics.cluster.aggregator.minute.disabled</name>\n"
            + "    <value>true</value>\n" + "    <description>\n"
            + "      Disable cluster based minute aggregations.\n" + "    </description>\n" + "  </property>"
            + "</configuration>");

    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();

    // Add the conf dir to the classpath
    // Chain the current thread classloader
    URLClassLoader urlClassLoader = null;
    try {
        urlClassLoader = new URLClassLoader(new URL[] { folder.getRoot().toURI().toURL() }, currentClassLoader);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    Thread.currentThread().setContextClassLoader(urlClassLoader);
    metricsConf = new Configuration(false);
    metricsConf.addResource(Thread.currentThread().getContextClassLoader()
            .getResource(METRICS_SITE_CONFIGURATION_FILE).toURI().toURL());
    assertNotNull(metricsConf.get("test"));
}