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:net.sf.ufsc.ServiceLoader.java

/**
 * Creates a new service loader for the given service type, using the
 * extension class loader.//w w  w  .  j  a  v a  2s  . c om
 *
 * <p> This convenience method simply locates the extension class loader,
 * call it <tt><i>extClassLoader</i></tt>, and then returns
 *
 * <blockquote><pre>
 * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote>
 *
 * <p> If the extension class loader cannot be found then the system class
 * loader is used; if there is no system class loader then the bootstrap
 * class loader is used.
 *
 * <p> This method is intended for use when only installed providers are
 * desired.  The resulting service will only find and load providers that
 * have been installed into the current Java virtual machine; providers on
 * the application's class path will be ignored.
 *
 * @param  service
 *         The interface or abstract class representing the service
 *
 * @return A new service loader
 */
public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    ClassLoader prev = null;
    while (cl != null) {
        prev = cl;
        cl = cl.getParent();
    }
    return ServiceLoader.load(service, prev);
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Sample file content: FLURRY_API_KEY=YKN7M4TDXRKXH97PX565
 * Each Flurry API Key corresponds to an Application on Flurry site.  It is absolutely 
  * necessary that the Flurry API Key-value from user's device is correct in order to log to the Flurry application.
  * /*www.jav a  2 s . c o  m*/
  * No validation on the API key allows creation of a new Flurry application by client at any time
  * The API key is communicated to the user group who would put the API key name-value pair into 
  * properties file specified by variable flurryFileName below.
  * 
  * If no key-value is found, the default API key is used below.  Default is intended for users of
  * ATT Developer Program.
 */
private void setFlurryApiKey() {
    if (DEBUG) {
        Log.d(TAG, "entered setFlurryApiKey");
    }
    final String flurryFileName = ARODataCollector.ARO_TRACE_ROOTDIR + ARODataCollector.FLURRY_API_KEY_REL_PATH;

    InputStream flurryFileReaderStream = null;
    try {
        final ClassLoader loader = ClassLoader.getSystemClassLoader();

        flurryFileReaderStream = loader.getResourceAsStream(flurryFileName);

        Properties prop = new Properties();
        try {
            if (flurryFileReaderStream != null) {
                prop.load(flurryFileReaderStream);
                mApp.app_flurry_api_key = prop.containsKey(ARODataCollector.FLURRY_API_KEY_NAME)
                        && !prop.getProperty(ARODataCollector.FLURRY_API_KEY_NAME)
                                .equals(AROCollectorUtils.EMPTY_STRING)
                                        ? prop.getProperty(ARODataCollector.FLURRY_API_KEY_NAME).trim()
                                        : mApp.app_flurry_api_key;
                if (DEBUG) {
                    Log.d(TAG, "flurry Property String: " + prop.toString());
                    Log.d(TAG, "flurry app_flurry_api_key: " + mApp.app_flurry_api_key);
                }
            } else {
                if (DEBUG) {
                    Log.d(TAG, "flurryFileReader stream is null.  Using default: " + mApp.app_flurry_api_key);
                }
            }
        } catch (IOException e) {
            Log.d(TAG, e.getClass().getName() + " thrown trying to load file ");
        }
    } finally {
        try {
            if (flurryFileReaderStream != null) {
                flurryFileReaderStream.close();
            }
        } catch (IOException e) {
            //log and exit method-nothing else to do.
            if (DEBUG) {
                Log.d(TAG,
                        "setFlurryApiKey method reached catch in finally method, trying to close flurryFileReader");
            }
        }
        Log.d(TAG, "exiting setFlurryApiKey");
    }
}

From source file:net.sf.jabref.gui.openoffice.OpenOfficePanel.java

private static void addURL(List<URL> jarList) throws IOException {
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;
    try {/*ww w  . j av  a2 s  .com*/
        Method method = sysclass.getDeclaredMethod("addURL", CLASS_PARAMETERS);
        method.setAccessible(true);
        for (URL anU : jarList) {
            method.invoke(sysloader, anU);
        }
    } catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        LOGGER.error("Could not add URL to system classloader", e);
        throw new IOException("Error, could not add URL to system classloader", e);

    }
}

From source file:tvbrowser.core.PluginLoader.java

private Object loadJavaPlugin(File jarFile) throws TvBrowserException {
    Object plugin = null;//  www . j  av  a2s.com

    // Create a class loader for the plugin
    ClassLoader classLoader;
    ClassLoader classLoader2 = null;

    try {
        URL[] urls = new URL[] { jarFile.toURI().toURL() };
        classLoader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());

        try {
            if (!new File(PLUGIN_DIRECTORY).equals(jarFile.getParentFile())
                    && new File(PLUGIN_DIRECTORY, jarFile.getName()).isFile()) {
                urls = new URL[] { new File(PLUGIN_DIRECTORY, jarFile.getName()).toURI().toURL() };
                classLoader2 = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
            }
        } catch (MalformedURLException exc) {
        }
    } catch (MalformedURLException exc) {
        throw new TvBrowserException(getClass(), "error.1", "Loading Jar file of a plugin failed: {0}.",
                jarFile.getAbsolutePath(), exc);
    }

    // Get the plugin name
    String pluginName = jarFile.getName();
    if (pluginName.endsWith(".jar")) {
        pluginName = pluginName.substring(0, pluginName.length() - 4);
    }

    boolean isBlockedDataService = false;

    // Create a plugin instance
    try {
        Class pluginClass = classLoader.loadClass(pluginName.toLowerCase() + "." + pluginName);
        Method getVersion = pluginClass.getMethod("getVersion", new Class[0]);
        Version version1 = null;
        try {
            version1 = (Version) getVersion.invoke(pluginClass, new Object[0]);
        } catch (Exception e) {
        }
        if (version1 == null || version1.toString().equals("0.0.0.0")) {
            mLog.warning("Did not load plugin " + pluginName + ", version is too old.");
            return null;
        }

        if (pluginClass.getSuperclass().equals(devplugin.AbstractTvDataService.class) || classLoader2 != null) {
            getVersion = pluginClass.getMethod("getVersion", new Class[0]);
            version1 = (Version) getVersion.invoke(pluginClass, new Object[0]);

            if (pluginClass.getSuperclass().equals(devplugin.AbstractTvDataService.class)) {
                isBlockedDataService = Settings.propBlockedPluginArray
                        .isBlocked(pluginName.toLowerCase() + "." + pluginName, version1);
            }
        }

        if (classLoader2 != null) {
            try {
                Class pluginClass2 = classLoader2.loadClass(pluginName.toLowerCase() + "." + pluginName);
                Method getVersion2 = pluginClass2.getMethod("getVersion", new Class[0]);

                Version version2 = (Version) getVersion2.invoke(pluginClass2, new Object[0]);

                if (version2.compareTo(version1) > 0) {
                    return null;
                }
            } catch (Throwable t) {
            }
        }

        try {
            Method preInstancing = pluginClass.getMethod("preInstancing", new Class[0]);
            preInstancing.invoke(pluginClass, new Object[0]);
        } catch (Throwable ti) {
        }

        if (!isBlockedDataService) {
            plugin = pluginClass.newInstance();
        }
    } catch (Throwable thr) {
        throw new TvBrowserException(getClass(), "error.2", "Could not load plugin {0}.",
                jarFile.getAbsolutePath(), thr);
    }

    return plugin;
}

From source file:geva.Main.AbstractRun.java

/**
 * Read the default properties. Replace or add properties from the command line.
 * If the file is not found on the file system class loading from the jar is tried
 * @param args arguments// w  w  w .  j a  v  a  2  s.com
 */
@SuppressWarnings({ "IOResourceOpenedButNotSafelyClosed" })
protected void readProperties(String[] args) {
    ClassLoader loader;
    InputStream in;
    try {
        this.properties = new Properties();
        File f = new File(this.propertiesFilePath);
        if (!f.exists()) { // try classloading
            loader = ClassLoader.getSystemClassLoader();
            in = loader.getResourceAsStream(this.propertiesFilePath);
            this.properties.load(in);
            logger.info("Loading properties from ClassLoader and: " + this.propertiesFilePath);
        } else {
            FileInputStream is = new FileInputStream(f);
            this.properties.load(is);
            logger.info("Loading properties from file system: " + this.propertiesFilePath);
        }
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                if (args[i].startsWith("-") && args.length > (i + 1)
                        && !args[i].equals(Constants.VERSION_FLAG)) {
                    this.properties.setProperty(args[i].substring(1), args[i + 1]);
                    i++;
                }
            }
        }
        for (Enumeration e = properties.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            logger.info(key + "=" + properties.getProperty(key, "Not defined"));
        }
    } catch (IOException e) {
        loader = ClassLoader.getSystemClassLoader();
        in = loader.getResourceAsStream(this.propertiesFilePath);
        try {
            this.properties.load(in);
        } catch (Exception ex) {
            System.err.println("Properties reading output caught:" + ex);
        }
        System.err.println(MessageFormat.format("Using default: {0} Bad:{1} Could not load:{2}",
                this.propertiesFilePath, this.propertiesFilePath, e));
    } catch (Exception e) {
        System.err
                .println("Could not commandline argument:" + e + " properties path:" + this.propertiesFilePath);
    }
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java

private UrlSet buildUrlSet() throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(classLoaderInterface, this.fileProtocols);

    //excluding the urls found by the parent class loader is desired, but fails in JBoss (all urls are removed)
    if (excludeParentClassLoader) {
        //exclude parent of classloaders
        ClassLoaderInterface parent = classLoaderInterface.getParent();
        //if reload is enabled, we need to step up one level, otherwise the UrlSet will be empty
        //this happens because the parent of the realoding class loader is the web app classloader
        if (parent != null && isReloadEnabled())
            parent = parent.getParent();

        if (parent != null)
            urlSet = urlSet.exclude(parent);

        try {/*from  w w  w .j  a  v  a 2  s . co m*/
            // This may fail in some sandboxes, ie GAE
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            urlSet = urlSet.exclude(new ClassLoaderInterfaceDelegate(systemClassLoader.getParent()));

        } catch (SecurityException e) {
            if (LOG.isWarnEnabled())
                LOG.warn(
                        "Could not get the system classloader due to security constraints, there may be improper urls left to scan");
        }
    }

    //try to find classes dirs inside war files
    urlSet = urlSet.includeClassesUrl(classLoaderInterface);

    urlSet = urlSet.excludeJavaExtDirs();
    urlSet = urlSet.excludeJavaEndorsedDirs();
    try {
        urlSet = urlSet.excludeJavaHome();
    } catch (NullPointerException e) {
        // This happens in GAE since the sandbox contains no java.home directory
        if (LOG.isWarnEnabled())
            LOG.warn("Could not exclude JAVA_HOME, is this a sandbox jvm?");
    }
    urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
    urlSet = urlSet.exclude(".*/JavaVM.framework/.*");

    if (includeJars == null) {
        urlSet = urlSet.exclude(".*?\\.jar(!/|/)?");
    } else {
        Set<URL> includeUrls = new HashSet<URL>();
        boolean[] patternUsed = new boolean[includeJars.length];
        for (int i = 0; i < includeJars.length; i++) {
            try {
                String includeJar = includeJars[i];
                FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(includeJar));
                includeUrls.add(resource.getURL());
                patternUsed[i] = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (LOG.isWarnEnabled()) {
            for (int i = 0; i < patternUsed.length; i++) {
                if (!patternUsed[i]) {
                    LOG.warn("The includeJars pattern [#0] did not match any jars in the classpath",
                            includeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:org.apache.struts2.convention.PackageBasedActionConfigBuilder.java

private UrlSet buildUrlSet(List<URL> resourceUrls) throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(resourceUrls);
    urlSet = urlSet.include(new UrlSet(classLoaderInterface, this.fileProtocols));

    //excluding the urls found by the parent class loader is desired, but fails in JBoss (all urls are removed)
    if (excludeParentClassLoader) {
        //exclude parent of classloaders
        ClassLoaderInterface parent = classLoaderInterface.getParent();
        //if reload is enabled, we need to step up one level, otherwise the UrlSet will be empty
        //this happens because the parent of the realoding class loader is the web app classloader
        if (parent != null && isReloadEnabled())
            parent = parent.getParent();

        if (parent != null)
            urlSet = urlSet.exclude(parent);

        try {/*from www  . j  a  v  a2 s . c  om*/
            // This may fail in some sandboxes, ie GAE
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            urlSet = urlSet.exclude(new ClassLoaderInterfaceDelegate(systemClassLoader.getParent()));

        } catch (SecurityException e) {
            if (LOG.isWarnEnabled())
                LOG.warn(
                        "Could not get the system classloader due to security constraints, there may be improper urls left to scan");
        }
    }

    //try to find classes dirs inside war files
    urlSet = urlSet.includeClassesUrl(classLoaderInterface, new UrlSet.FileProtocolNormalizer() {
        public URL normalizeToFileProtocol(URL url) {
            return fileManager.normalizeToFileProtocol(url);
        }
    });

    urlSet = urlSet.excludeJavaExtDirs();
    urlSet = urlSet.excludeJavaEndorsedDirs();
    try {
        urlSet = urlSet.excludeJavaHome();
    } catch (NullPointerException e) {
        // This happens in GAE since the sandbox contains no java.home directory
        if (LOG.isWarnEnabled())
            LOG.warn("Could not exclude JAVA_HOME, is this a sandbox jvm?");
    }
    urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
    urlSet = urlSet.exclude(".*/JavaVM.framework/.*");

    if (includeJars == null) {
        urlSet = urlSet.exclude(".*?\\.jar(!/|/)?");
    } else {
        //jar urls regexes were specified
        List<URL> rawIncludedUrls = urlSet.getUrls();
        Set<URL> includeUrls = new HashSet<URL>();
        boolean[] patternUsed = new boolean[includeJars.length];

        for (URL url : rawIncludedUrls) {
            if (fileProtocols.contains(url.getProtocol())) {
                //it is a jar file, make sure it macthes at least a url regex
                for (int i = 0; i < includeJars.length; i++) {
                    String includeJar = includeJars[i];
                    if (Pattern.matches(includeJar, url.toExternalForm())) {
                        includeUrls.add(url);
                        patternUsed[i] = true;
                        break;
                    }
                }
            } else {
                //it is not a jar
                includeUrls.add(url);
            }
        }

        if (LOG.isWarnEnabled()) {
            for (int i = 0; i < patternUsed.length; i++) {
                if (!patternUsed[i]) {
                    LOG.warn("The includeJars pattern [#0] did not match any jars in the classpath",
                            includeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:org.springframework.beans.BeanUtils.java

/**
 * Find a JavaBeans PropertyEditor following the 'Editor' suffix convention
 * (e.g. "mypackage.MyDomainClass" -> "mypackage.MyDomainClassEditor").
 * <p>Compatible to the standard JavaBeans convention as implemented by
 * {@link java.beans.PropertyEditorManager} but isolated from the latter's
 * registered default editors for primitive types.
 * @param targetType the type to find an editor for
 * @return the corresponding editor, or {@code null} if none found
 *///w  ww  .ja  v a 2 s.co  m
@Nullable
public static PropertyEditor findEditorByConvention(@Nullable Class<?> targetType) {
    if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) {
        return null;
    }
    ClassLoader cl = targetType.getClassLoader();
    if (cl == null) {
        try {
            cl = ClassLoader.getSystemClassLoader();
            if (cl == null) {
                return null;
            }
        } catch (Throwable ex) {
            // e.g. AccessControlException on Google App Engine
            if (logger.isDebugEnabled()) {
                logger.debug("Could not access system ClassLoader: " + ex);
            }
            return null;
        }
    }
    String editorName = targetType.getName() + "Editor";
    try {
        Class<?> editorClass = cl.loadClass(editorName);
        if (!PropertyEditor.class.isAssignableFrom(editorClass)) {
            if (logger.isWarnEnabled()) {
                logger.warn("Editor class [" + editorName
                        + "] does not implement [java.beans.PropertyEditor] interface");
            }
            unknownEditorTypes.add(targetType);
            return null;
        }
        return (PropertyEditor) instantiateClass(editorClass);
    } catch (ClassNotFoundException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("No property editor [" + editorName + "] found for type " + targetType.getName()
                    + " according to 'Editor' suffix convention");
        }
        unknownEditorTypes.add(targetType);
        return null;
    }
}

From source file:alpine.Config.java

/**
 * Extends the runtime classpath to include the files or directories specified.
 * @param files one or more File objects representing a single JAR file or a directory containing JARs.
 * @since 1.0.0/*  w  w w .  j  a  v a2 s.c  o  m*/
 */
public void expandClasspath(File... files) {
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> urlClass = URLClassLoader.class;
    for (File file : files) {
        LOGGER.info("Expanding classpath to include: " + file.getAbsolutePath());
        URI fileUri = file.toURI();
        try {
            Method method = urlClass.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(urlClassLoader, fileUri.toURL());
        } catch (MalformedURLException | NoSuchMethodException | IllegalAccessException
                | InvocationTargetException e) {
            LOGGER.error("Error expanding classpath", e);
        }
    }
}

From source file:org.kepler.Kepler.java

/** Show the splash screen and start the kepler GUI. */
private static void _showSplash() {
    try {/*from ww w.  java 2 s . c  om*/

        ConfigurationProperty commonProperty = ConfigurationManager.getInstance()
                .getProperty(ConfigurationManager.getModule("common"));
        ConfigurationProperty splashscreenProp = commonProperty.getProperty("splash.image");
        String splashname = splashscreenProp.getValue();

        final URL splashURL = ClassLoader.getSystemClassLoader().getResource(splashname);

        SplashWindow.splash(splashURL);

    } catch (Exception ex) {
        System.err.println("Failed to find splash screen image." + "Ignoring, use the Java coffee cup");
        ex.printStackTrace();
    }
}