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.allcolor.yahp.converter.CClassLoader.java

/**
 * Install a custom URLStreamHandlerFactory which handle nested jar loading,
 * and memory url. The installation is done only if necessary.
 * //from   ww w  .j a va  2  s.  c o m
 */
private static void installURLStreamHandlerFactory() {
    synchronized (URL.class) {
        try {
            try {
                new URL("yahpjarloader://test/test");
                return;
            } catch (MalformedURLException e) {
            }
            if (CClassLoader.class.getClassLoader() != ClassLoader.getSystemClassLoader()) {
                try {
                    Class c = ClassLoader.getSystemClassLoader()
                            .loadClass("org.allcolor.yahp.converter.CYaHPURLStreamHandlerFactory");
                    if (c != null) {
                        return;
                    }
                } catch (Throwable ignore) {
                }
            }
            final Field factory = URL.class.getDeclaredField("factory");
            factory.setAccessible(true);
            final URLStreamHandlerFactory oldFactory = (URLStreamHandlerFactory) factory.get(null);
            if ((oldFactory == null)
                    || (oldFactory.getClass().getName().indexOf("CYaHPURLStreamHandlerFactory") == -1)) {
                synchronized (factory) {
                    System.out.println("Installing new URLStreamHandlerFactory...");
                    final Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass",
                            new Class[] { String.class, byte[].class, int.class, int.class });
                    defineClass.setAccessible(true);
                    final byte[] bauc = CClassLoader.loadByteArray(CClassLoader.class.getClassLoader()
                            .getResource("org/allcolor/yahp/converter/CByteArrayUrlConnection.class"));
                    final byte[] crypt = CClassLoader.loadByteArray(CClassLoader.class.getClassLoader()
                            .getResource("org/allcolor/yahp/converter/CCryptoUtils.class"));
                    final byte[] b64c = CClassLoader.loadByteArray(CClassLoader.class.getClassLoader()
                            .getResource("org/allcolor/yahp/converter/CBASE64Codec.class"));
                    final byte[] muh = CClassLoader.loadByteArray(CClassLoader.class.getClassLoader()
                            .getResource("org/allcolor/yahp/converter/CMemoryURLHandler.class"));
                    final byte[] juhgc = CClassLoader
                            .loadByteArray(CClassLoader.class.getClassLoader().getResource(
                                    "org/allcolor/yahp/converter/CJarLoaderURLStreamHandler$CGCCleaner.class"));
                    final byte[] juh = CClassLoader.loadByteArray(CClassLoader.class.getClassLoader()
                            .getResource("org/allcolor/yahp/converter/CJarLoaderURLStreamHandler.class"));
                    final byte[] hf = CClassLoader.loadByteArray(CClassLoader.class.getClassLoader()
                            .getResource("org/allcolor/yahp/converter/CYaHPURLStreamHandlerFactory.class"));
                    defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CByteArrayUrlConnection", bauc,
                                    new Integer(0), new Integer(bauc.length) });
                    defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CCryptoUtils", crypt, new Integer(0),
                                    new Integer(crypt.length) });
                    defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CBASE64Codec", b64c, new Integer(0),
                                    new Integer(b64c.length) });
                    defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CMemoryURLHandler", muh, new Integer(0),
                                    new Integer(muh.length) });
                    defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CJarLoaderURLStreamHandler$CGCCleaner",
                                    juhgc, new Integer(0), new Integer(juhgc.length) });
                    defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CJarLoaderURLStreamHandler", juh,
                                    new Integer(0), new Integer(juh.length) });
                    final Class c = (Class) defineClass.invoke(ClassLoader.getSystemClassLoader(),
                            new Object[] { "org.allcolor.yahp.converter.CYaHPURLStreamHandlerFactory", hf,
                                    new Integer(0), new Integer(hf.length) });
                    final Constructor cons = c.getConstructor(new Class[] { URLStreamHandlerFactory.class });
                    final URLStreamHandlerFactory fact = (URLStreamHandlerFactory) cons
                            .newInstance(new Object[] { oldFactory });
                    factory.set(null, fact);
                    System.out.println("Installing new URLStreamHandlerFactory DONE.");
                }
            }
        } catch (final Throwable ignore) {
            ignore.printStackTrace();
        }
    }
}

From source file:ResourceBundleSupport.java

/**
 * Returns the classloader, which was responsible for loading the given
 * class./*from  ww  w  .jav a  2s .  co m*/
 *
 * @param c the classloader, either an application class loader or the
 *          boot loader.
 * @return the classloader, never null.
 * @throws SecurityException if the SecurityManager does not allow to grab
 *                           the context classloader.
 */
public static ClassLoader getClassLoader(final Class c) {
    final String localClassLoaderSource;
    synchronized (ObjectUtilities.class) {
        if (classLoader != null) {
            return classLoader;
        }
        localClassLoaderSource = classLoaderSource;
    }

    if ("ThreadContext".equals(localClassLoaderSource)) {
        final ClassLoader threadLoader = Thread.currentThread().getContextClassLoader();
        if (threadLoader != null) {
            return threadLoader;
        }
    }

    // Context classloader - do not cache ..
    final ClassLoader applicationCL = c.getClassLoader();
    if (applicationCL == null) {
        return ClassLoader.getSystemClassLoader();
    } else {
        return applicationCL;
    }
}

From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java

private ClassLoader createClassLoader() throws MojoExecutionException {
    URL[] classpath = createClasspath();

    return new URLClassLoader(classpath, ClassLoader.getSystemClassLoader());
}

From source file:org.mousephenotype.www.testing.model.TestUtils.java

/**
 * Returns the classpath, prefaced by the string 'Classpath:\n'. Each
 * file is separated by a newline./*from  ww w .  ja  va  2 s . c om*/
 * 
 * @return the classpath, prefaced by the string 'Classpath:\n'. Each
 * file is separated by a newline.
 */
public static String getClasspath() {
    StringBuilder sb = new StringBuilder("Classpath:\n");
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();

    for (URL url : urls) {
        sb.append(url.getFile()).append("\n");
    }

    return sb.toString();
}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

public Process startPythonThread(String batfilePath) throws Exception {

    File file = new File("state.file");
    file.createNewFile();/*from w w w.j ava2s .  c  o  m*/
    try {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        for (URL url : urls) {
            System.out.println(url.getFile());
        }

        Runtime runTime = Runtime.getRuntime();
        pythonProcess = runTime.exec("cmd.exe /k " + batfilePath);
        InputStream inputStream = pythonProcess.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(isr);
        InputStream errorStream = pythonProcess.getErrorStream();
        InputStreamReader esr = new InputStreamReader(errorStream);

        String n1 = "";
        StringBuffer standardOutput = new StringBuffer();
        while ((n1 = reader.readLine()) != null) {
            System.out.println(n1);
        }
        //          System.out.println("Standard Output: " + standardOutput.toString());
        int n2;
        char[] c2 = new char[1024];
        StringBuffer standardError = new StringBuffer();
        while ((n2 = esr.read(c2)) > 0) {
            standardError.append(c2, 0, n2);
        }
        System.out.println("Standard Error: " + standardError.toString());
        return pythonProcess;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.ambari.server.api.services.AmbariMetaInfoTest.java

@Test
public void testBadStack() throws Exception {
    File stackRoot = new File("src/test/resources/bad-stacks");
    File version = new File("src/test/resources/version");
    if (System.getProperty("os.name").contains("Windows")) {
        stackRoot = new File(ClassLoader.getSystemClassLoader().getResource("bad-stacks").getPath());
        version = new File(new File(ClassLoader.getSystemClassLoader().getResource("").getPath()).getParent(),
                "version");
    }//ww w  .  j a va2s  . c o  m
    LOG.info("Stacks file " + stackRoot.getAbsolutePath());

    TestAmbariMetaInfo ambariMetaInfo = createAmbariMetaInfo(stackRoot, version, true);
    Assert.assertEquals(1, ambariMetaInfo.getStackManager().getStacks().size());
    Assert.assertEquals(false, ambariMetaInfo.getStackManager().getStack("HDP", "0.1").isValid());
    Assert.assertEquals(2, ambariMetaInfo.getStackManager().getStack("HDP", "0.1").getErrors().size());

}

From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.FragmentationPatternAnalysis.java

private static TreeBuilder loadTreeBuilder() {
    try {//  w  ww.j  a v  a2  s .  c o m
        // is gurobi.jar in classpath?
        final Class<TreeBuilder> kl = (Class<TreeBuilder>) ClassLoader.getSystemClassLoader()
                .loadClass("de.unijena.bioinf.FragmentationTreeConstruction.computation.tree.ilp.GurobiSolver");
        // is gurobi native library in classpath?
        final TreeBuilder b = kl.newInstance();
        kl.getMethod("setNumberOfCPUs", int.class).invoke(b,
                Math.min(4, Runtime.getRuntime().availableProcessors()));
        return b;
    } catch (Throwable e) {
        // try GLPK tree builder
        try {
            final TreeBuilder solver = ((Class<TreeBuilder>) ClassLoader.getSystemClassLoader().loadClass(
                    "de.unijena.bioinf.FragmentationTreeConstruction.computation.tree.ilp.GLPKSolver"))
                            .newInstance();
            solver.getDescription();
            return solver;
        } catch (Throwable f) {
            return new DPTreeBuilder(12);
        }
    }
}

From source file:org.apache.ws.scout.registry.RegistryImpl.java

/**
 * //from ww  w.  j  a  va  2s  .co  m
 * @param name
 * @return The class object for the name given
 * @throws ClassNotFoundException
 * @throws NoClassDefFoundError
 */
public static Class getClassForName(String name) throws ClassNotFoundException, NoClassDefFoundError {
    Class clazz = null;

    try {
        // log.info("Using the Context ClassLoader");
        ClassLoader ccl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }
        });

        clazz = Class.forName(name, true, ccl);
    } catch (Exception e) {
        log.debug("Failed to load the class " + name + " with context class loader " + e);
    }

    if (null == clazz) {
        ClassLoader scl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return ClassLoader.getSystemClassLoader();
            }
        });

        try {
            clazz = Class.forName(name, true, scl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return clazz;
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * Release a previously allocated memory URL
 * /*from  www. j  av a 2 s .  com*/
 * @param u
 *            the URL to release memory
 */
public static void releaseMemoryURL(final URL u) {
    try {
        final Class c = ClassLoader.getSystemClassLoader()
                .loadClass("org.allcolor.yahp.converter.CMemoryURLHandler");
        final Method m = c.getDeclaredMethod("releaseMemoryURL", new Class[] { URL.class });
        m.setAccessible(true);
        m.invoke(null, new Object[] { u });
    } catch (final Exception ignore) {
        ignore.printStackTrace();
    }
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Runs this application directly in the current VM.
 *///from w  w  w. ja  va2  s  . c om
public void invokeDirect(JApplet applet) throws IOException {
    ClassPath classPath = ClassPaths.buildClassPath(this);
    URL[] jarUrls = classPath.asUrls();

    // create custom class loader
    URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
        @Override
        protected PermissionCollection getPermissions(CodeSource code) {
            Permissions perms = new Permissions();
            perms.add(new AllPermission());
            return perms;
        }
    };
    Thread.currentThread().setContextClassLoader(loader);

    log.info("Configured URL class loader:");
    for (URL url : jarUrls)
        log.info("  " + url);

    // configure any system properties that we can
    for (String jvmarg : _jvmargs) {
        if (jvmarg.startsWith("-D")) {
            jvmarg = processArg(jvmarg.substring(2));
            int eqidx = jvmarg.indexOf("=");
            if (eqidx == -1) {
                log.warning("Bogus system property: '" + jvmarg + "'?");
            } else {
                System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx + 1));
            }
        }
    }

    // pass along any pass-through arguments
    Map<String, String> passProps = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
            key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
            passProps.put(key, (String) entry.getValue());
        }
    }
    // we can't set these in the above loop lest we get a ConcurrentModificationException
    for (Map.Entry<String, String> entry : passProps.entrySet()) {
        System.setProperty(entry.getKey(), entry.getValue());
    }

    // make a note that we're running in "applet" mode
    System.setProperty("applet", "true");

    // prepare our app arguments
    String[] args = new String[_appargs.size()];
    for (int ii = 0; ii < args.length; ii++)
        args[ii] = processArg(_appargs.get(ii));

    try {
        log.info("Loading " + _class);
        Class<?> appclass = loader.loadClass(_class);
        Method main;
        try {
            // first see if the class has a special applet-aware main
            main = appclass.getMethod("main", JApplet.class, SA_PROTO.getClass());
            log.info("Invoking main(JApplet, {" + StringUtil.join(args, ", ") + "})");
            main.invoke(null, new Object[] { applet, args });
        } catch (NoSuchMethodException nsme) {
            main = appclass.getMethod("main", SA_PROTO.getClass());
            log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
            main.invoke(null, new Object[] { args });
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}