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.apache.accumulo.start.classloader.vfs.ContextManagerTest.java

@Test
public void differentContexts() throws Exception {

    ContextManager cm = new ContextManager(vfs, new ReloadingClassLoader() {
        @Override/*  ww  w . j  a  v a  2 s . c o  m*/
        public ClassLoader getClassLoader() {
            return ClassLoader.getSystemClassLoader();
        }
    });

    cm.setContextConfig(new ContextsConfig() {
        @Override
        public ContextConfig getContextConfig(String context) {
            if (context.equals("CX1")) {
                return new ContextConfig(uri1, true);
            } else if (context.equals("CX2")) {
                return new ContextConfig(uri2, true);
            }
            return null;
        }
    });

    FileObject testDir = vfs.resolveFile(folder1.getRoot().toURI().toString());
    FileObject[] dirContents = testDir.getChildren();
    ClassLoader cl1 = cm.getClassLoader("CX1");
    FileObject[] files = ((VFSClassLoader) cl1).getFileObjects();
    Assert.assertArrayEquals(createFileSystems(dirContents), files);

    FileObject testDir2 = vfs.resolveFile(folder2.getRoot().toURI().toString());
    FileObject[] dirContents2 = testDir2.getChildren();
    ClassLoader cl2 = cm.getClassLoader("CX2");
    FileObject[] files2 = ((VFSClassLoader) cl2).getFileObjects();
    Assert.assertArrayEquals(createFileSystems(dirContents2), files2);

    Class<?> defaultContextClass = cl1.loadClass("test.HelloWorld");
    Object o1 = defaultContextClass.newInstance();
    Assert.assertEquals("Hello World!", o1.toString());

    Class<?> myContextClass = cl2.loadClass("test.HelloWorld");
    Object o2 = myContextClass.newInstance();
    Assert.assertEquals("Hello World!", o2.toString());

    Assert.assertFalse(defaultContextClass.equals(myContextClass));

    cm.removeUnusedContexts(new HashSet<String>());
}

From source file:Main.java

/**
 * Load a given resources. <p/> This method will try to load the resources
 * using the following methods (in order):
 * <ul>// www. j a va2s  .c o  m
 * <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) {
        //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) {
            // ignore
        }
    }

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

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

        if (cl != null) {
            try {
                urls = cl.getResources(resourceName);
            } catch (IOException 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.anite.zebra.avalon.impl.ZebraAvalonDefsFactory.java

public void initialize() throws Exception {
    lff = new LoadFromFile();
    lff.setProcessDefinitionClass(ClassLoader.getSystemClassLoader().loadClass(processDefClassName));
    lff.setTaskDefinitionClass(ClassLoader.getSystemClassLoader().loadClass(taskDefClassName));
    lff.loadProcessDefs(appRootPath + filePath);

}

From source file:org.sakaiproject.entitybroker.util.spring.ResourceFinder.java

private static Resource makeResource(String path) {
    if (path.startsWith("/")) {
        path = path.substring(1);/*from w  ww. j ava 2 s . c om*/
    }
    Resource r = null;
    // try the environment path first
    String envPath = getEnvironmentPath() + path;
    r = new FileSystemResource(envPath);
    if (!r.exists()) {
        // try the relative path next
        String relPath = getRelativePath() + path;
        r = new FileSystemResource(relPath);
        if (!r.exists()) {
            // now try the classloader
            ClassLoader cl = ResourceFinder.class.getClassLoader();
            r = new ClassPathResource(path, cl);
            if (!r.exists()) {
                // finally try the system classloader
                cl = ClassLoader.getSystemClassLoader();
                r = new ClassPathResource(path, cl);
            }
        }
    }
    if (!r.exists()) {
        throw new IllegalArgumentException(
                "Could not find this resource (" + path + ") in any of the checked locations");
    }
    return r;
}

From source file:org.ajax4jsf.cache.CacheManager.java

private ClassLoader findClassLoader() {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null)
        cl = ClassLoader.getSystemClassLoader();
    return cl;/*from   ww w .j av  a  2 s.c  o  m*/
}

From source file:at.ac.tuwien.infosys.jcloudscale.test.unit.ClassLoaderTest.java

@Test(timeout = TIMEOUT)
public void testSystemClassLoader() throws Exception {

    SystemClassLoaderConfiguration classLoaderConfiguration = new SystemClassLoaderConfiguration();
    startup(classLoaderConfiguration);//from   w w w .  j  a v a2  s .  c om

    ClassLoader classLoader = classLoaderConfiguration.createClassLoader();
    assertSame(ClassLoader.getSystemClassLoader().getClass(), classLoader.getClass());

    InputStream stream = classLoader.getResourceAsStream(RESOURCE);
    assertNotNull(stream);
    assertEquals(CONTENT, IOUtils.toString(stream));
}

From source file:com.sun.socialsite.web.listeners.ContextListener.java

/**
 * Responds to context initialization event by processing context
 * parameters for easy access by the rest of the application.
 *//* w ww. j a  va2 s.c  o  m*/
public void contextInitialized(ServletContextEvent sce) {

    log.info("SocialSite Initializing ... ");

    // Keep a reference to ServletContext object
    servletContext = sce.getServletContext();

    // Set a "context.realpath" property, allowing others to find our filesystem basedir
    Config.setProperty("context.realpath", sce.getServletContext().getRealPath("/"));

    try {
        URL baseUrl = new URL(Config.getProperty("socialsite.base.url"));
        Config.setProperty("context.contextpath", baseUrl.getPath());
        log.debug("Config[context.contextpath]=" + Config.getProperty("context.contextpath"));
    } catch (MalformedURLException ex) {
        String msg = String.format("Could not decode socialsite.base.url[%s]",
                Config.getProperty("socialsite.base.url"));
        log.error(msg, ex);
    }

    // Log system information (if enabled)
    // TODO: move this down to DEBUG level
    if (log.isInfoEnabled()) {
        logClassLoaderInfo(ClassLoader.getSystemClassLoader(), "systemClassLoader");
        logClassLoaderInfo(Thread.currentThread().getContextClassLoader(), "contextClassLoader");
    }

    // Set a "context.contextpath" property, allowing others to find our webapp base
    // Now prepare the core services of the app so we can bootstrap
    try {
        Startup.prepare();
    } catch (StartupException ex) {
        log.fatal("SocialSite startup failed during app preparation", ex);
        return;
    }

    // If preparation failed or is incomplete then we are done
    if (!Startup.isPrepared()) {
        log.info("SocialSite startup requires interaction from user to continue");
        return;
    }

    try {
        Factory.bootstrap();
        Factory.getSocialSite().initialize();
    } catch (BootstrapException ex) {
        log.fatal("Factory bootstrap failed", ex);
    } catch (SocialSiteException ex) {
        log.fatal("Factory initialization failed", ex);
    }

    log.info("SocialSite Initialization Complete");
}

From source file:com.googlecode.xmlzen.utils.FileUtils.java

/**
 * Gets a {@link File} form a String that represents file path which is
 * relative to current Class Path. Uses system's default ClassLoader.
 * // w  ww  .  ja v  a 2s  . com
 * @see #getClassPathFile(String, ClassLoader)
 * @param path Path to File
 * @return {@link File} object or null if nothing is found
 */
public static File getClassPathFile(final String path) {
    return getClassPathFile(path, ClassLoader.getSystemClassLoader());
}

From source file:org.echocat.nodoodle.transport.HandlerUnpacker.java

public HandlerUnpacker(ClassLoader classLoader) {
    _classLoader = classLoader != null ? classLoader : ClassLoader.getSystemClassLoader();
}

From source file:org.jboss.test.selenium.AbstractSeleniumTestCase.java

/**
 * Loads properties from specified resource file
 * //www. ja v  a  2 s . c om
 * @param resource
 *            where in classpath the file is located
 * @return loaded properties
 * @throws IOException
 *             if an error occurred when reading resource file
 */
protected static Properties getProperties(String resource) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    InputStream is = cl.getResourceAsStream(resource);

    Properties props = new Properties();

    if (is == null) {
        is = AbstractSeleniumTestCase.class.getResourceAsStream(resource);
    }

    if (is != null) {
        props.load(is);
    }

    return props;
}