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.trianacode.taskgraph.tool.ClassLoaders.java

public static URL getResource(String name) {
    final String className = name;

    // Get the class within a doPrivleged block
    Object ret = AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            log.debug("trying to find " + className);

            // Check if the class is a registered class then
            // use the classloader for that class.
            ClassLoader classLoader = getClassLoader(className);
            if (classLoader != null) {
                URL url = classLoader.getResource(className);
                if (url != null) {
                    return url;
                }// w w w.  j  a  v  a 2s  . c o m
            }
            //check the list of loaders
            for (int i = 0; i < loaders.size(); i++) {
                classLoader = loaders.get(i);
                log.debug("next class loader:" + classLoader);
                URL url = classLoader.getResource(className);
                if (url != null) {
                    return url;
                }
            }

            // Try the context class loader
            classLoader = Thread.currentThread().getContextClassLoader();
            log.debug("next class loader:" + classLoader);
            URL url = classLoader.getResource(className);
            if (url != null) {
                return url;
            }

            // Try the classloader that loaded this class.
            classLoader = ClassLoaders.class.getClassLoader();
            log.debug("next class loader:" + classLoader);
            url = classLoader.getResource(className);
            if (url != null) {
                return url;
            }

            classLoader = ClassLoader.getSystemClassLoader();
            log.debug("next class loader:" + classLoader);
            return classLoader.getResource(className);

        }

    });
    if (ret instanceof URL) {
        return (URL) ret;
    }
    return null;

}

From source file:org.gtdfree.ApplicationHelper.java

public static byte[] loadResource(String name) {

    InputStream is = null;/*from   ww w.ja v  a 2 s .c  o  m*/

    try {

        is = ApplicationHelper.class.getResourceAsStream(name);

        if (is == null) {
            is = ClassLoader.getSystemClassLoader().getResourceAsStream(name);
            if (is == null) {

                File f = new File(name);
                if (f.exists()) {
                    is = new BufferedInputStream(new FileInputStream(f));
                }

            } else {
                Logger.getLogger(ApplicationHelper.class).info("Loaded '" + name + "' with SystemClassLoader"); //$NON-NLS-1$ //$NON-NLS-2$
            }
        } else {
            Logger.getLogger(ApplicationHelper.class).info("Loaded '" + name + "' with ApplicationHelper"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (is == null) {
            Logger.getLogger(ApplicationHelper.class).error("Failed to load '" + name + "'."); //$NON-NLS-1$ //$NON-NLS-2$
            return null;
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream(is.available());
        while (is.available() > 0) {
            os.write(is.read());
        }
        return os.toByteArray();

    } catch (Exception e) {
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                //
            }
        }
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    final ServletContext servletContext = servletContextEvent.getServletContext();
    stopThreads = !"false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
    stopTimerThreads = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
    executeShutdownHooks = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
    threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs",
            THREAD_WAIT_MS_DEFAULT);/*from w  ww . j  av  a  2s.  c  om*/
    shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs",
            SHUTDOWN_HOOK_WAIT_MS_DEFAULT);

    info("Settings for " + this.getClass().getName() + " (CL: 0x"
            + Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
    info("  stopThreads = " + stopThreads);
    info("  stopTimerThreads = " + stopTimerThreads);
    info("  executeShutdownHooks = " + executeShutdownHooks);
    info("  threadWaitMs = " + threadWaitMs + " ms");
    info("  shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");

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

    try {
        // If package org.jboss is found, we may be running under JBoss
        mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
    } catch (Exception ex) {
        // Do nothing
    }

    info("Initializing context by loading some known offenders with system classloader");

    // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener  
    // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
    try {
        // Switch to system classloader in before we load/call some JRE stuff that will cause 
        // the current classloader to be available for garbage collection
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread

        java.security.Security.getProviders();

        java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader

        javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()

        try {
            Class.forName("javax.security.auth.Policy").getMethod("getPolicy").invoke(null);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (ClassNotFoundException e) {
            // Ignore silently - class is deprecated
        }

        try {
            javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception ex) { // Example: ParserConfigurationException
            error(ex);
        }

        try {
            Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        try {
            Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        // This probably does not affect classloaders, but prevents some problems with .jar files
        try {
            // URL needs to be well-formed, but does not need to exist
            new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
        } catch (Exception ex) {
            error(ex);
        }

        /////////////////////////////////////////////////////
        // Load Sun specific classes that may cause leaks

        final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");

        try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        }

        try {
            Class.forName("sun.java2d.Disposer"); // Will start a Thread
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE && !mayBeJBoss) // JBoss blocks this package/class, so don't warn
                error(cnfex);
        }

        try {
            Class<?> gcClass = Class.forName("sun.misc.GC");
            final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
            requestLatency.invoke(null, 3600000L);
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        }

        // Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader  
        try {
            Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
        } catch (ClassNotFoundException e) {
            // Ignore silently - class not present
        }
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.eucalyptus.upgrade.TestHarness.java

@SuppressWarnings("unchecked")
private static Multimap<Class, Method> getTestMethods() throws Exception {
    final Multimap<Class, Method> testMethods = ArrayListMultimap.create();
    List<Class> classList = Lists.newArrayList();
    for (File f : new File(System.getProperty("euca.home") + "/usr/share/eucalyptus").listFiles()) {
        if (f.getName().startsWith("eucalyptus") && f.getName().endsWith(".jar")
                && !f.getName().matches(".*-ext-.*")) {
            try {
                JarFile jar = new JarFile(f);
                Enumeration<JarEntry> jarList = jar.entries();
                for (JarEntry j : Collections.list(jar.entries())) {
                    if (j.getName().matches(".*\\.class.{0,1}")) {
                        String classGuess = j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
                        try {
                            Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
                            for (final Method m : candidate.getDeclaredMethods()) {
                                if (Iterables.any(testAnnotations,
                                        new Predicate<Class<? extends Annotation>>() {
                                            public boolean apply(Class<? extends Annotation> arg0) {
                                                return m.getAnnotation(arg0) != null;
                                            }
                                        })) {
                                    System.out.println("Added test class: " + candidate.getCanonicalName());
                                    testMethods.put(candidate, m);
                                }/*from ww  w.  j a va 2s  . co  m*/
                            }
                        } catch (ClassNotFoundException e) {
                        }
                    }
                }
                jar.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                continue;
            }
        }
    }
    return testMethods;
}

From source file:com.oltpbenchmark.util.ClassUtil.java

/**
 * //from  www . j a  v  a  2  s  .  co m
 * @param class_name
 * @return
 */
public static Class<?> getClass(String class_name) {
    Class<?> target_class = null;
    try {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        target_class = (Class<?>) loader.loadClass(class_name);
    } catch (Exception ex) {
        throw new RuntimeException("Failed to retrieve class for " + class_name, ex);
    }
    return (target_class);

}

From source file:org.apache.flink.client.program.rest.RestClusterClientTest.java

@Test
public void testJobSubmitCancelStop() throws Exception {
    TestJobSubmitHandler submitHandler = new TestJobSubmitHandler();
    TestJobTerminationHandler terminationHandler = new TestJobTerminationHandler();
    TestJobExecutionResultHandler testJobExecutionResultHandler = new TestJobExecutionResultHandler(
            JobExecutionResultResponseBody
                    .created(new JobResult.Builder().applicationStatus(ApplicationStatus.SUCCEEDED).jobId(jobId)
                            .netRuntime(Long.MAX_VALUE).build()));

    try (TestRestServerEndpoint ignored = createRestServerEndpoint(submitHandler, terminationHandler,
            testJobExecutionResultHandler)) {

        Assert.assertFalse(submitHandler.jobSubmitted);
        restClusterClient.submitJob(jobGraph, ClassLoader.getSystemClassLoader());
        Assert.assertTrue(submitHandler.jobSubmitted);

        Assert.assertFalse(terminationHandler.jobCanceled);
        restClusterClient.cancel(jobId);
        Assert.assertTrue(terminationHandler.jobCanceled);

        Assert.assertFalse(terminationHandler.jobStopped);
        restClusterClient.stop(jobId);// w w w.j a v a2s .  c o m
        Assert.assertTrue(terminationHandler.jobStopped);
    }
}

From source file:org.uncommons.reportng.HTMLReporter.java

/**
 * Reads the CSS and JavaScript files from the JAR file and writes them to
 * the output directory./*www .  ja  v a 2s. c o m*/
 * @param outputDirectory Where to put the resources.
 * @throws java.io.IOException If the resources can't be read or written.
 */
private void copyResources(File outputDirectory) throws IOException {
    copyClasspathResource(outputDirectory, "reportng.css", "reportng.css");
    copyClasspathResource(outputDirectory, "reportng.js", "reportng.js");
    //copyClasspathResource(outputDirectory, "AI-logo.png", "ai_logo.png");

    //copyFile(outputDirectory, new File("src/main/resources/img/AI-logo.png"), "ai_logo.png");

    FileUtils.copyFileToDirectory(new File("src/main/resources/img/AI-logo.png"), outputDirectory);

    // If there is a custom stylesheet, copy that.
    File customStylesheet = META.getStylesheetPath();

    if (customStylesheet != null) {
        if (customStylesheet.exists()) {
            copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);
        } else {
            // If not found, try to read the file as a resource on the classpath
            // useful when reportng is called by a jarred up library
            InputStream stream = ClassLoader.getSystemClassLoader()
                    .getResourceAsStream(customStylesheet.getPath());
            if (stream != null) {
                copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);
            }
        }
    }
}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

public void contextInitialized(ServletContextEvent servletContextEvent) {

    final ServletContext servletContext = servletContextEvent.getServletContext();
    stopThreads = !"false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
    stopTimerThreads = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
    executeShutdownHooks = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
    threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs",
            THREAD_WAIT_MS_DEFAULT);/*  w  w  w  . j a  v  a2  s .c  o m*/
    shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs",
            SHUTDOWN_HOOK_WAIT_MS_DEFAULT);

    info("Settings for " + this.getClass().getName() + " (CL: 0x"
            + Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
    info("  stopThreads = " + stopThreads);
    info("  stopTimerThreads = " + stopTimerThreads);
    info("  executeShutdownHooks = " + executeShutdownHooks);
    info("  threadWaitMs = " + threadWaitMs + " ms");
    info("  shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");

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

    try {
        // If package org.jboss is found, we may be running under JBoss
        mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
    } catch (Exception ex) {
        // Do nothing
    }

    info("Initializing context by loading some known offenders with system classloader");

    // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener  
    // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
    try {
        // Switch to system classloader in before we load/call some JRE stuff that will cause 
        // the current classloader to be available for garbage collection
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        // Christopher: Uncommented as it will not work on some containers as google app engine  
        //java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
        java.security.Security.getProviders();

        java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader

        // Christopher: Uncommented as it will not work on some containers as google app engine  
        //javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()

        try {
            Class.forName("javax.security.auth.Policy").getMethod("getPolicy").invoke(null);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (ClassNotFoundException e) {
            // Ignore silently - class is deprecated
        }

        try {
            javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception ex) { // Example: ParserConfigurationException
            error(ex);
        }

        try {
            Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        try {
            Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        // This probably does not affect classloaders, but prevents some problems with .jar files
        try {
            // URL needs to be well-formed, but does not need to exist
            new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
        } catch (Exception ex) {
            error(ex);
        }

        /////////////////////////////////////////////////////
        // Load Sun specific classes that may cause leaks

        final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");

        try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        }

        try {
            Class.forName("sun.java2d.Disposer"); // Will start a Thread
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE && !mayBeJBoss) // JBoss blocks this package/class, so don't warn
                error(cnfex);
        }

        try {
            Class<?> gcClass = Class.forName("sun.misc.GC");
            final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
            requestLatency.invoke(null, 3600000L);
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        }

        // Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader  
        try {
            Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
        } catch (ClassNotFoundException e) {
            // Ignore silently - class not present
        }
    } catch (Throwable ex) {
        error(ex);
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:org.xbasej.Util.java

/**
 * static class method to build the properties file input stream see
 * org.xBaseJ.properties file/*from w  w w. j a  va  2 s .  c o m*/
 * <ul>search for org.xBaseJ.properties file
 * <li>as specified by system property xBase.properties
 * <li>local directory
 * <li>user.home directory
 * <li>java.home directory
 * <li>classpath environment variable
 * </ul>
 *
 * @return InputStream org.xBaseJ.properties file
 * @throws xBaseJException
 *             io error most likely
 */
private static InputStream getPropertiesFile() {
    String xBaseJPropertiesFileName = "org.xBaseJ.properties";

    String _fileName = System.getProperty(xBaseJPropertiesFileName);
    if (_fileName != null)
        xBaseJPropertiesFileName = _fileName;
    File f3, f2, f1 = new File(xBaseJPropertiesFileName);
    if (f1.exists())
        try {
            propFile = f1;
            logr.debug("properties file loaded from " + f1.getAbsolutePath());
            return new FileInputStream(f1);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
            return null;
        }
    else {
        xBaseJPropertiesFileName = System.getProperty("user.home") + "/org.xBaseJ.properties";
        f2 = new File(xBaseJPropertiesFileName);
        if (f2.exists())
            try {
                propFile = f2;
                logr.debug("properties file loaded from " + f2.getAbsolutePath());
                return new FileInputStream(f2);
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
                return null;
            }
        else {
            xBaseJPropertiesFileName = System.getProperty("java.home") + "/org.xBaseJ.properties";
            f3 = new File(xBaseJPropertiesFileName);
            if (f3.exists()) {
                try {
                    propFile = f3;
                    logr.debug("properties file loaded from " + f3.getAbsolutePath());
                    return new FileInputStream(f3);
                } catch (FileNotFoundException fnfe) {
                    fnfe.printStackTrace();
                    return null;
                }
            } else {

                InputStream is = (new Util()).getClass().getResourceAsStream("/org.xBaseJ.properties");
                if (is == null) {
                    if (servletContextPath == null) // try it again
                        is = ClassLoader.getSystemClassLoader().getResourceAsStream("org.xBaseJ.properties");
                    else { // context is not null
                        try {
                            is = new FileInputStream(servletContextPath + "/org.xBaseJ.properties");
                            logr.debug("properties file loaded from servlet context path " + servletContextPath
                                    + "/org.xBaseJ.properties");
                            propFile = new File(servletContextPath + "/org.xBaseJ.properties");

                        } catch (IOException ioe) {
                            logr.debug("Searched for org.xBaseJ.properties as " + servletContextPath
                                    + "/org.xBaseJ.properties");
                        }
                    }
                }
                if (is != null) {
                    logr.debug("properties file loaded from classpath");
                    return is;
                } else {
                    logr.debug("Searched for org.xBaseJ.properties as " + f1.getAbsolutePath());
                    logr.debug("Searched for org.xBaseJ.properties as " + f2.getAbsolutePath());
                    logr.debug("Searched for org.xBaseJ.properties as " + f3.getAbsolutePath());
                    logr.debug("Searched for org.xBaseJ.properties in classpath environment variable");
                    return null;
                }
            }
        }

    }

}

From source file:org.owasp.jbrofuzz.core.Verifier.java

/**
 * <p>Return the contents of an internal file a String.</p>
 *  //w  w  w  . j a v  a2s .  co m
 * @param fileName e.g. fuzzers.jbrf; headers.jbrf
 * @return the contents of the file as a String
 * 
 * @author subere@uncon.org
 * @version 2.0
 * @since 2.0
 */
private static String parseFile(String fileName) {

    final StringBuffer fileContents = new StringBuffer();

    // Attempt to read from the jar file
    final URL fileURL = ClassLoader.getSystemClassLoader().getResource(fileName);

    if (fileURL == null) {
        throw new RuntimeException(ERROR_MSG + "could not find " + fileName);
    }

    // Read the characters from the file
    BufferedReader in = null;
    try {
        final URLConnection connection = fileURL.openConnection();
        connection.connect();

        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        int counter = 0;
        int c;
        while (((c = in.read()) > 0) && (counter < MAX_CHARS)) {
            // Allow the character only if its printable ascii or \n
            if ((CharUtils.isAsciiPrintable((char) c)) || (((char) c) == '\n')) {
                fileContents.append((char) c);
            }
            counter++;
        }
        in.close();

        if (counter == MAX_CHARS) {

            throw new RuntimeException(ERROR_MSG + "\n... stopped reading file :" + fileName + "\nafter "
                    + MAX_CHARS + " characters.\n\n");

        }

    } catch (final IOException e1) {
        throw new RuntimeException(ERROR_MSG + "could not read " + fileName);
    } finally {
        IOUtils.closeQuietly(in);
    }

    return fileContents.toString();
}