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:com.dianping.resource.io.util.ClassUtils.java

/**
 * Return the default ClassLoader to use: typically the thread context
 * ClassLoader, if available; the ClassLoader that loaded the ClassUtils
 * class will be used as fallback./*from w  w w.  j  a  va2  s .c o m*/
 * <p>Call this method if you intend to use the thread context ClassLoader
 * in a scenario where you clearly prefer a non-null ClassLoader reference:
 * for example, for class path resource loading (but not necessarily for
 * {@code Class.forName}, which accepts a {@code null} ClassLoader
 * reference as well).
 * @return the default ClassLoader (only {@code null} if even the system
 * ClassLoader isn't accessible)
 * @see Thread#getContextClassLoader()
 * @see ClassLoader#getSystemClassLoader()
 */
public static ClassLoader getDefaultClassLoader() {
    ClassLoader cl = null;
    try {
        cl = Thread.currentThread().getContextClassLoader();
    } catch (Throwable ex) {
        // Cannot access thread context ClassLoader - falling back...
    }
    if (cl == null) {
        // No thread context class loader -> use class loader of this class.
        cl = ClassUtils.class.getClassLoader();
        if (cl == null) {
            // getClassLoader() returning null indicates the bootstrap ClassLoader
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (Throwable ex) {
                // Cannot access system ClassLoader - oh well, maybe the caller can live with null...
            }
        }
    }
    return cl;
}

From source file:org.apache.hadoop.gateway.GatewayLocalServiceFuncTest.java

@Test
public void testJerseyService() throws ClassNotFoundException {
    assertThat(ClassLoader.getSystemClassLoader().loadClass("org.glassfish.jersey.servlet.ServletContainer"),
            notNullValue());//w ww .  j a  v a  2  s  . co  m
    assertThat(ClassLoader.getSystemClassLoader()
            .loadClass("org.apache.hadoop.gateway.jersey.JerseyDispatchDeploymentContributor"), notNullValue());
    assertThat(ClassLoader.getSystemClassLoader().loadClass(
            "org.apache.hadoop.gateway.jersey.JerseyServiceDeploymentContributorBase"), notNullValue());
    assertThat(ClassLoader.getSystemClassLoader().loadClass("org.apache.hadoop.gateway.TestJerseyService"),
            notNullValue());

    String username = "guest";
    String password = "guest-password";
    String serviceUrl = clusterUrl + "/test-jersey-service/test-jersey-resource-path";
    given()
            //.log().all()
            .auth().preemptive().basic(username, password).expect()
            //.log().all()
            .statusCode(HttpStatus.SC_OK).contentType("text/plain").body(is("test-jersey-resource-response"))
            .when().get(serviceUrl);
}

From source file:com.freetmp.common.util.ClassUtils.java

public static ClassLoader getDefaultClassLoader() {
    ClassLoader cl = null;/*www .j a v a 2  s .co m*/
    try {
        cl = Thread.currentThread().getContextClassLoader();
    } catch (Throwable ex) {
        // Cannot access thread context ClassLoader - falling back...
    }
    if (cl == null) {
        // No thread context class loader -> use class loader of this class.
        cl = ClassUtils.class.getClassLoader();
        if (cl == null) {
            // getClassLoader() returning null indicates the bootstrap ClassLoader
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (Throwable ex) {
                // Cannot access system ClassLoader - oh well, maybe the caller can live with null...
            }
        }
    }
    return cl;
}

From source file:fi.uta.infim.usaproxyreportgenerator.App.java

private static void setupDataProvider() {
    // A data provider class can be specified on the CLI.
    if (cli.hasOption("dataProvider")) {
        // Look for JAR files in the plugin dir
        File[] jars = PLUGINS_DIR.listFiles((FileFilter) new WildcardFileFilter("*.jar", IOCase.INSENSITIVE));
        URL[] jarUrls = new URL[jars.length];
        for (int i = 0; i < jars.length; ++i) {
            try {
                jarUrls[i] = jars[i].toURI().toURL();
            } catch (MalformedURLException e) {
                // Skip URL if not valid
                continue;
            }//from  www .j a v a2 s .c om
        }

        ClassLoader loader = URLClassLoader.newInstance(jarUrls, ClassLoader.getSystemClassLoader());
        String className = cli.getOptionValue("dataProvider");

        // Try to load the named class using a class loader. Fall back to
        // default if this fails.
        try {
            @SuppressWarnings("unchecked")
            Class<? extends DataProvider> cliOptionClass = (Class<? extends DataProvider>) Class
                    .forName(className, true, loader);
            if (!DataProvider.class.isAssignableFrom(cliOptionClass)) {
                throw new ClassCastException(cliOptionClass.getCanonicalName());
            }
            dataProviderClass = cliOptionClass;
        } catch (ClassNotFoundException e) {
            System.out.flush();
            System.err.println("Specified data provider class not found: " + e.getMessage());
            System.err.println("Falling back to default provider.");
        } catch (ClassCastException e) {
            System.out.flush();
            System.err.println("Specified data provider class is invalid: " + e.getMessage());
            System.err.println("Falling back to default provider.");
        }
        System.err.flush();
    }
}

From source file:org.tros.torgo.ControllerBase.java

/**
 * Initialize the window. This is called here from run() and not the
 * constructor so that the Service Provider doesn't load up all of the
 * necessary resources when the application loads.
 *///  w ww  .  j a v a  2s. c  om
private void initSwing() {
    this.torgoPanel = createConsole((Controller) this);
    this.torgoCanvas = createCanvas(torgoPanel);

    //init the GUI w/ the components...
    Container contentPane = window.getContentPane();
    JToolBar tb = createToolBar();
    if (tb != null) {
        contentPane.add(tb, BorderLayout.NORTH);
    }

    final java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(NamedWindow.class);
    if (torgoCanvas != null) {
        final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, torgoCanvas.getComponent(),
                torgoPanel.getComponent());
        int dividerLocation = prefs.getInt(this.getClass().getName() + "divider-location",
                window.getWidth() - 300);
        splitPane.setDividerLocation(dividerLocation);
        splitPane.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent pce) {
                prefs.putInt(this.getClass().getName() + "divider-location", splitPane.getDividerLocation());
            }
        });

        contentPane.add(splitPane);
    } else {
        contentPane.add(torgoPanel.getComponent());
    }

    JMenuBar mb = createMenuBar();
    if (mb == null) {
        mb = new TorgoMenuBar(window, this);
    }
    window.setJMenuBar(mb);
    JMenu helpMenu = new JMenu("Help");
    JMenuItem aboutMenu = new JMenuItem("About Torgo");
    try {
        java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader()
                .getResources(ABOUT_MENU_TORGO_ICON);
        ImageIcon ico = new ImageIcon(resources.nextElement());
        aboutMenu.setIcon(ico);
    } catch (IOException ex) {
        Logger.getLogger(ControllerBase.class.getName()).log(Level.SEVERE, null, ex);
    }

    aboutMenu.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            AboutWindow aw = new AboutWindow();
            aw.setVisible(true);
        }
    });
    helpMenu.add(aboutMenu);

    JMenu vizMenu = new JMenu("Visualization");
    for (String name : TorgoToolkit.getVisualizers()) {
        JCheckBoxMenuItem item = new JCheckBoxMenuItem(name);
        viz.add(item);
        vizMenu.add(item);
    }
    if (vizMenu.getItemCount() > 0) {
        mb.add(vizMenu);
    }

    mb.add(helpMenu);
    window.setJMenuBar(mb);

    window.addWindowListener(new WindowListener() {

        @Override
        public void windowOpened(WindowEvent e) {
        }

        /**
         * We only care if the window is closing so we can kill the
         * interpreter thread.
         *
         * @param e
         */
        @Override
        public void windowClosing(WindowEvent e) {
            stopInterpreter();
        }

        @Override
        public void windowClosed(WindowEvent e) {
        }

        @Override
        public void windowIconified(WindowEvent e) {
        }

        @Override
        public void windowDeiconified(WindowEvent e) {
        }

        @Override
        public void windowActivated(WindowEvent e) {
        }

        @Override
        public void windowDeactivated(WindowEvent e) {
        }
    });
}

From source file:mobac.mapsources.loader.MapPackManager.java

public void loadMapPack(File mapPackFile, MapSourcesManager mapSourcesManager)
        throws CertificateException, IOException, MapSourceCreateException {
    // testMapPack(mapPackFile);
    URLClassLoader urlCl;//from ww  w .  ja  v a  2s  . c  o m
    URL url = mapPackFile.toURI().toURL();
    urlCl = new MapPackClassLoader(url, ClassLoader.getSystemClassLoader());
    InputStream manifestIn = urlCl.getResourceAsStream("META-INF/MANIFEST.MF");
    String rev = null;
    if (manifestIn != null) {
        Manifest mf = new Manifest(manifestIn);
        rev = mf.getMainAttributes().getValue("MapPackRevision");
        manifestIn.close();
        if (rev != null) {
            if ("exported".equals(rev)) {
                rev = ProgramInfo.getRevisionStr();
            } else {
                rev = Integer.toString(Utilities.parseSVNRevision(rev));
            }
        }
        mf = null;
    }
    MapSourceLoaderInfo loaderInfo = new MapSourceLoaderInfo(LoaderType.MAPPACK, mapPackFile, rev);
    final Iterator<MapSource> iterator = ServiceLoader.load(MapSource.class, urlCl).iterator();

    while (iterator.hasNext()) {
        try {
            MapSource ms = iterator.next();
            ms.setLoaderInfo(loaderInfo);
            mapSourcesManager.addMapSource(ms);
            log.trace("Loaded map source: " + ms.toString() + " (name: " + ms.getName() + ")");
        } catch (Error e) {
            urlCl = null;
            throw new MapSourceCreateException("Failed to load a map sources from map pack: "
                    + mapPackFile.getName() + " " + e.getMessage(), e);
        }
    }
}

From source file:eu.stratosphere.myriad.driver.MyriadDriverFrontend.java

public static String getClasspathString() {
    StringBuffer classpath = new StringBuffer();
    ClassLoader applicationClassLoader = MyriadDriverFrontend.class.getClassLoader();
    if (applicationClassLoader == null) {
        applicationClassLoader = ClassLoader.getSystemClassLoader();
    }//from w  w w  .ja  v a 2  s . c  o  m
    URL[] urls = ((URLClassLoader) applicationClassLoader).getURLs();
    for (int i = 0; i < urls.length; i++) {
        classpath.append(urls[i].getFile()).append("\r\n");
    }

    return classpath.toString();
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Loads up a ZIP file that's contained in the classpath.
 * @param path path of ZIP resource//from  w  w  w . j  a v a  2 s . co m
 * @return contents of files within the ZIP
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null} elements
 * @throws IllegalArgumentException if {@code path} cannot be found, or if zipPaths contains duplicates
 */
public static Map<String, byte[]> readZipFromResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);

    Map<String, byte[]> ret = new LinkedHashMap<>();

    try (InputStream is = url.openStream(); ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) {
        ZipArchiveEntry entry;
        while ((entry = zais.getNextZipEntry()) != null) {
            ret.put(entry.getName(), IOUtils.toByteArray(zais));
        }
    }

    return ret;
}

From source file:com.quinsoft.zeidon.standardoe.JavaObjectEngine.java

/**
 * @param logger/*  ww  w .  j a  v  a2s.co m*/
 */
private static String getClassPath(ZeidonLogger logger) {
    try {
        StringBuilder classpath = new StringBuilder();
        ClassLoader classLoader = classpath.getClass().getClassLoader();
        if (classLoader == null)
            classLoader = ClassLoader.getSystemClassLoader();

        URL[] urls = ((URLClassLoader) classLoader).getURLs();
        for (URL url : urls)
            classpath.append(url.getFile()).append("\n");

        return classpath.toString();
    } catch (Exception e) {
        if (logger != null)
            logger.error("Error trying to log classpath", e, (Object[]) null);

        return "<Error retrieving classpath>";
    }
}