Example usage for java.lang ClassLoader getSystemClassLoader

List of usage examples for java.lang ClassLoader getSystemClassLoader

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemClassLoader.

Prototype

@CallerSensitive
public static ClassLoader getSystemClassLoader() 

Source Link

Document

Returns the system class loader.

Usage

From source file:org.obm.sync.ObmSyncArchiveUtils.java

private static File[] replaceServiceJar(File[] asFile) {
    return FluentIterable.from(Arrays.asList(asFile)).transform(new Function<File, File>() {

        @Override//from   w ww .  jav  a 2 s . co  m
        public File apply(File input) {
            if (input.getName().contains("services-module")) {
                ZipFile servicesZip = null;
                try {
                    File outputFile = File.createTempFile("services-module", ".jar");
                    servicesZip = new ZipFile(input);

                    ChangeSet changeSet = new ChangeSet();
                    changeSet.add(new JarArchiveEntry("META-INF/MANIFEST.MF"),
                            ClassLoader.getSystemClassLoader().getResourceAsStream("MANIFEST.MF"));
                    ChangeSetPerformer changeSetPerformer = new ChangeSetPerformer(changeSet);
                    JarArchiveOutputStream jarArchiveOutputStream = new JarArchiveOutputStream(
                            new FileOutputStream(outputFile));
                    changeSetPerformer.perform(servicesZip, jarArchiveOutputStream);
                    return outputFile;
                } catch (IOException e) {
                    Throwables.propagate(e);
                } finally {
                    try {
                        if (servicesZip != null) {
                            servicesZip.close();
                        }
                    } catch (IOException e) {
                        Throwables.propagate(e);
                    }
                }
            }
            return input;
        }
    }).toArray(File.class);
}

From source file:org.opt4j.config.ModuleAutoFinder.java

/**
 * Returns all not abstract classes that implement {@link PropertyModule}.
 * /*from   w  w  w .j a  v a 2 s.  c o  m*/
 * @return all property modules
 */
protected Collection<Class<? extends Module>> getAll() {

    Starter starter = new Starter();
    Collection<File> files = starter.addPlugins();

    classLoader = ClassLoader.getSystemClassLoader();

    String paths = System.getProperty("java.class.path");
    StringTokenizer st = new StringTokenizer(paths, ";\n:");

    while (st.hasMoreTokens()) {
        String path = st.nextToken();
        File f = new File(path);

        if (f.exists()) {
            try {
                f = f.getCanonicalFile();
                files.add(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    List<Class<?>> classes = new ArrayList<Class<?>>();

    for (File file : files) {

        if (isJar(file)) {

            try {
                classes.addAll(getAllClasses(new ZipFile(file)));
            } catch (ZipException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (UnsupportedClassVersionError e) {
                System.err.println(file + " not supported: bad version number");
            }
        } else {
            classes.addAll(getAllClasses(file));
        }
    }

    List<Class<? extends Module>> modules = new ArrayList<Class<? extends Module>>();

    for (Class<?> clazz : classes) {
        if (Opt4JModule.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
            Class<? extends Module> module = clazz.asSubclass(Module.class);
            Ignore i = module.getAnnotation(Ignore.class);

            if (i == null && !module.isAnonymousClass() && accept.transform(module)
                    && !ignore.transform(module)) {
                modules.add(module);
                invokeOut("Add module: " + module.toString());
            }
        }
    }

    return modules;

}

From source file:fm.last.commons.io.LastFileUtils.java

/**
 * Searches for a file on local filesytem, classpath etc.
 * /*from w w  w. j a  v a 2 s.c  o m*/
 * @param fileName Name of file to find.
 * @param classToLoadFrom Class to use as a base for finding the file via it's classloader, if necessary.
 * @return The file if found on the file system.
 * @throws FileNotFoundException If the File could not be found.
 */
public static File getFile(String fileName, Class<?> classToLoadFrom) throws FileNotFoundException {
    File file = new File(fileName); // first try the path directly
    if (!file.exists()) {
        URL fileURL = classToLoadFrom.getResource(fileName);// next try the class's classpath
        if (fileURL == null) {
            fileURL = classToLoadFrom.getClassLoader().getResource(fileName);// next try the class' classloader's classpath
            if (fileURL == null) {
                fileURL = ClassLoader.getSystemClassLoader().getResource(fileName); // finally try the system classloader's
                // classpath
                if (fileURL == null) {
                    throw new FileNotFoundException(
                            "Could not find " + fileName + " on path, classpath " + "or system classpath");
                }
            }
        }
        file = new File(fileURL.getFile());
    }
    log.debug("Path to file located is " + file.getAbsolutePath());
    return file;
}

From source file:org.apache.spark.tez.utils.HadoopUtils.java

/**
 * Will provision current classpath to YARN and return an array of 
 * {@link Path}s representing provisioned resources
 * If 'generate-jar' system property is set it will also generate the JAR for the current 
 * working directory (mainly used when executing from IDE)
 * //ww  w . j  a  v a2  s . c  o  m
 * @return
 */
private static Path[] provisionClassPath(FileSystem fs, String applicationName, String[] classPathExclusions) {
    String genJarProperty = System.getProperty(TezConstants.GENERATE_JAR);
    boolean generateJar = genJarProperty != null && Boolean.parseBoolean(genJarProperty);
    List<Path> provisionedPaths = new ArrayList<Path>();
    List<File> generatedJars = new ArrayList<File>();

    boolean confFromHadoopConfDir = generateConfigJarFromHadoopConfDir(fs, applicationName, provisionedPaths,
            generatedJars);

    TezConfiguration tezConf = new TezConfiguration(fs.getConf());
    boolean provisionTez = true;
    if (tezConf.get("tez.lib.uris") != null) {
        provisionTez = false;
    }
    URL[] classpath = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
    for (URL classpathUrl : classpath) {
        File f = new File(classpathUrl.getFile());
        if (f.isDirectory()) {
            if (generateJar) {
                String jarFileName = ClassPathUtils.generateJarFileName("application");
                f = doGenerateJar(f, jarFileName, generatedJars, "application");
            } else if (f.getName().equals("conf") && !confFromHadoopConfDir) {
                String jarFileName = ClassPathUtils.generateJarFileName("conf_application");
                f = doGenerateJar(f, jarFileName, generatedJars, "configuration");
            } else {
                f = null;
            }
        }
        if (f != null) {
            if (f.getName().startsWith("tez-") && !provisionTez) {
                logger.info("Skipping provisioning of " + f.getName()
                        + " since Tez libraries are already provisioned");
                continue;
            }
            String destinationFilePath = applicationName + "/" + f.getName();
            Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath);
            if (shouldProvision(provisionedPath.getName(), classPathExclusions)) {
                provisioinResourceToFs(fs, new Path(f.getAbsolutePath()), provisionedPath);
                provisionedPaths.add(provisionedPath);
            }
        }

    }

    for (File generatedJar : generatedJars) {
        try {
            generatedJar.delete();
        } catch (Exception e) {
            logger.warn("Failed to delete generated jars", e);
        }
    }
    return provisionedPaths.toArray(new Path[] {});
}

From source file:org.castor.jaxb.CastorJAXBContextFactoryTest.java

/**
 * Tests the {@link CastorJAXBContextFactory#createContext(String, ClassLoader, java.util.Map)}
 * method./*from   w  w  w . j a  v a  2  s . c  o  m*/
 *
 * @throws Exception
 *             if any error occurs during test
 */
@Test
public void testCreateContextContextPath() throws Exception {

    JAXBContext jaxbContext = CastorJAXBContextFactory.createContext("org.castor.entities",
            ClassLoader.getSystemClassLoader(), new HashMap<String, Object>());

    assertNotNull("CastorJAXBContextFactory created null context.", jaxbContext);
}

From source file:org.commonjava.propulsor.deploy.resteasy.ResteasyDeploymentProvider.java

@Override
public DeploymentInfo getDeploymentInfo() {
    final ResteasyDeployment deployment = new ResteasyDeployment();

    //        deployment.getActualResourceClasses()
    //                  .addAll( resourceClasses );
    ////from w  w  w  . j av a2  s .  c o m
    //        deployment.getActualProviderClasses()
    //                  .addAll( providerClasses );

    LoggerFactory.getLogger(getClass()).debug(
            "\n\n\n\nRESTEasy DeploymentManager Using BeanManager: {} (@{})\n  with ObjectMapper: {}\n\n\n",
            bmgr, bmgr.hashCode());

    deployment.setApplication(this);
    deployment.setInjectorFactoryClass(CdiInjectorFactoryImpl.class.getName());

    final ServletInfo resteasyServlet = Servlets.servlet("REST", HttpServlet30Dispatcher.class)
            .setAsyncSupported(true).setLoadOnStartup(1).addMappings(config.getJaxRsMappings());

    return new DeploymentInfo().addListener(Servlets.listener(RequestScopeListener.class))
            .addServletContextAttribute(ResteasyDeployment.class.getName(), deployment)
            .addServlet(resteasyServlet).setClassLoader(ClassLoader.getSystemClassLoader());
}

From source file:org.jsecurity.util.ClassUtils.java

/**
 * Attempts to load the specified class name from the current thread's
 * {@link Thread#getContextClassLoader() context class loader}, then the
 * current ClassLoader (<code>ClassUtils.class.getClassLoader()</code>), then the system/application
 * ClassLoader (<code>ClassLoader.getSystemClassLoader()</code>, in that order.  If any of them cannot locate
 * the specified class, an <code>UnknownClassException</code> is thrown (our RuntimeException equivalent of
 * the JRE's <code>ClassNotFoundException</code>.
 *
 * @param fqcn the fully qualified class name to load
 * @return the located class/*w  ww. j  a va 2  s . c  o m*/
 * @throws UnknownClassException if the class cannot be found.
 */
public static Class forName(String fqcn) throws UnknownClassException {
    Class clazz = null;
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl != null) {
        try {
            clazz = cl.loadClass(fqcn);
        } catch (ClassNotFoundException e) {
            if (log.isTraceEnabled()) {
                log.trace("Unable to load class named [" + fqcn
                        + "] from the thread context ClassLoader.  Trying the current ClassLoader...");
            }
        }
    }
    if (clazz == null) {
        cl = ClassUtils.class.getClassLoader();
        try {
            clazz = cl.loadClass(fqcn);
        } catch (ClassNotFoundException e1) {
            if (log.isTraceEnabled()) {
                log.trace("Unable to load class named [" + fqcn + "] from the current ClassLoader.  "
                        + "Trying the system/application ClassLoader...");
            }
            cl = ClassLoader.getSystemClassLoader();
            try {
                clazz = cl.loadClass(fqcn);
            } catch (ClassNotFoundException ignored) {
                if (log.isTraceEnabled()) {
                    log.trace("Unable to load class named [" + fqcn + "] from the "
                            + "system/application ClassLoader.");
                }
            }
        }
    }

    if (clazz == null) {
        String msg = "Unable to load class named [" + fqcn + "] from the thread context, current, or "
                + "system/application ClassLoaders.  All heuristics have been exausted.  Class could not be found.";
        throw new UnknownClassException(msg);
    }
    return clazz;
}

From source file:org.kawanfw.file.reflection.ClassPathUtil.java

/**
 * Displays the classpath/* w  ww  .  jav  a  2s. c  o m*/
 */
public static void displayClasspath() {

    System.out.println();
    System.out.println(new Date());
    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader) cl).getURLs();

    for (URL url : urls) {
        System.out.println(url.getFile());
    }

}

From source file:org.apache.xml.security.utils.ClassLoaderUtils.java

/**
 * Load a given resources. <p/> This method will try to load the resources
 * using the following methods (in order):
 * <ul>//w  ww  .j  av a 2s . c  om
 * <li>From Thread.currentThread().getContextClassLoader()
 * <li>From ClassLoaderUtil.class.getClassLoader()
 * <li>callingClass.getClassLoader()
 * </ul>
 * 
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 */
public static List<URL> getResources(String resourceName, Class<?> callingClass) {
    List<URL> ret = new ArrayList<URL>();
    Enumeration<URL> urls = new Enumeration<URL>() {
        public boolean hasMoreElements() {
            return false;
        }

        public URL nextElement() {
            return null;
        }

    };
    try {
        urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
        //ignore
    }
    if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        try {
            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName.substring(1));
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            // ignore
        }
    }

    ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
    if (cluClassloader == null) {
        cluClassloader = ClassLoader.getSystemClassLoader();
    }
    if (!urls.hasMoreElements()) {
        try {
            urls = cluClassloader.getResources(resourceName);
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            // ignore
        }
    }
    if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        try {
            urls = cluClassloader.getResources(resourceName.substring(1));
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            // ignore
        }
    }

    if (!urls.hasMoreElements()) {
        ClassLoader cl = callingClass.getClassLoader();

        if (cl != null) {
            try {
                urls = cl.getResources(resourceName);
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
                // ignore
            }
        }
    }

    if (!urls.hasMoreElements()) {
        URL url = callingClass.getResource(resourceName);
        if (url != null) {
            ret.add(url);
        }
    }
    while (urls.hasMoreElements()) {
        ret.add(urls.nextElement());
    }

    if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
        return getResources('/' + resourceName, callingClass);
    }
    return ret;
}

From source file:com.splout.db.common.SploutConfiguration.java

private static URL loadAsResource(String what) {
    URL url = SploutConfiguration.class.getClassLoader().getResource(what);
    if (url == null) {
        url = ClassLoader.getSystemClassLoader().getResource(what);
        if (url != null) {
            log.info("Loading " + what + " from system classloader at: " + url);
        }/*  www  .  java  2 s  . c om*/
        return url;
    } else {
        log.info(
                "Loading " + what + " from " + SploutConfiguration.class.getName() + " classloader at: " + url);
    }
    return url;
}