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.clustercontrol.plugin.ClassUtils.java

/**
 * ??URLCLASSPATH??<br/>//  w  w w . j ava2s  . co m
 * @param ?URL
 * @throws IOException
 */
public static void addURL(URL u) throws IOException {
    URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

    for (URL url : sysLoader.getURLs()) {
        if (url.toString().equals(u.toString())) {
            log.info("URL " + u + " is already in CLASSPATH");
            return;
        }
    }

    Class<URLClassLoader> sysClass = URLClassLoader.class;
    try {
        Method method = sysClass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { u });
    } catch (Throwable t) {
        log.warn(t.getMessage(), t);
        throw new IOException("could not add URL " + u + " to CLASSPATH");
    }
}

From source file:org.roda.core.util.ClassLoaderUtility.java

/**
 * Add URL to CLASSPATH//from w ww .ja  va  2  s  .  c o  m
 * 
 * @param url
 *          {@link URL}
 * @throws IOException
 *           IOException
 */
public static void addURL(URL url) throws IOException {

    URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL urls[] = sysLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {

        if (StringUtils.equalsIgnoreCase(urls[i].toString(), url.toString())) {
            LOGGER.debug("URL {} is already in the CLASSPATH", url);
            return;
        }
    }

    try {
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", PARAMETERS);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { url });
    } catch (Throwable t) {
        throw new IOException("Error, could not add URL to system classloader", t);
    }
}

From source file:org.metamorfosis.model.project.InternalClassPath.java

/**
 * Agrega una url al classloader interno
 * @see RuntimeClassPath//from  ww w  . ja v a 2 s. c o m
 * @param url
 * @throws ProjectException No se puede agregar el recurso al classpath interno
 */
protected static void addURL(URL url) throws ProjectException {
    try {
        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<?> clazz = URLClassLoader.class;

        Method method = clazz.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(classLoader, new Object[] { url });
    } catch (Exception ex) {
        throw new ProjectException("No se puede agregar recurso " + "'" + url + "' al classpath interno", ex);
    }
}

From source file:org.commoncrawl.util.TLDNamesCollection.java

private static void initialize() {
    synchronized (TLDNamesCollection.class) {
        if (tldToSecondaryNameMap == null) {

            try {

                ImmutableMultimap.Builder<String, String> builder = new ImmutableMultimap.Builder<String, String>();

                InputStream inputStream = ClassLoader.getSystemClassLoader()
                        .getResourceAsStream("effective_tld_list.txt");

                try {

                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(inputStream, Charset.forName("UTF-8")));

                    String line = null;

                    while ((line = reader.readLine()) != null) {
                        if (!line.startsWith("//")) {
                            if (line.length() != 0) {
                                int indexOfDot = line.lastIndexOf(".");
                                if (indexOfDot == -1) {
                                    builder.put(line.trim(), "");
                                } else {
                                    String leftSide = line.substring(0, indexOfDot).trim();
                                    String rightSide = line.substring(indexOfDot + 1).trim();
                                    builder.put(rightSide, leftSide);
                                }/*from   w ww .  ja v  a2 s .  c o m*/
                            }
                        }
                    }

                    tldToSecondaryNameMap = builder.build();
                } finally {
                    inputStream.close();
                }
            } catch (IOException e) {
                LOG.error(CCStringUtils.stringifyException(e));
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:com.germinus.easyconf.ClasspathUtil.java

/**
 * Return the Class object of the specified class name by searching the
 * current classpath and the system classpath.
 *
 * @param name the name of the class/* w  ww . j a v a2 s  . co  m*/
 *
 * @return the <code>Class</code> instance
 */
public static Class locateClass(String name) throws ClassNotFoundException {
    Class foundClass = null;
    if (foundClass == null) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            foundClass = loader.loadClass(name);
            log.debug("Class loaded from the context classpath (" + name + ")");
        } catch (ClassNotFoundException ignore) {
        }
    }

    if (foundClass == null) {
        try {
            foundClass = ClassLoader.getSystemClassLoader().loadClass(name);
            log.debug("Class loaded from the system classpath (" + name + ")");
        } catch (ClassNotFoundException ignore) {
        }
    }
    if (foundClass == null) {
        throw new ClassNotFoundException(
                "Class " + name + " was not found " + "in context classpath nor system classpath");
    }
    return foundClass;
}

From source file:SecuritySupport.java

static ClassLoader getSystemClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (SecurityException ex) {
            }//from w  w w . j  av  a2 s. c o  m
            return cl;
        }
    });
}

From source file:com.krawler.esp.utils.PropsLoader.java

public static Properties loadProperties(String name, ClassLoader loader) {
    if (name == null)
        throw new IllegalArgumentException("null input: name");

    if (name.startsWith("/"))
        name = name.substring(1);//  w  w  w  .  j a  v a  2  s . c o  m

    if (name.endsWith(SUFFIX))
        name = name.substring(0, name.length() - SUFFIX.length());

    Properties result = null;

    InputStream in = null;
    try {
        if (loader == null)
            loader = ClassLoader.getSystemClassLoader();

        if (LOAD_AS_RESOURCE_BUNDLE) {
            name = name.replace('/', '.');
            // Throws MissingResourceException on lookup failures:
            final ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault(), loader);

            result = new Properties();
            for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
                final String key = (String) keys.nextElement();
                final String value = rb.getString(key);

                result.put(key, value);
            }
        } else {
            name = name.replace('.', '/');

            if (!name.endsWith(SUFFIX))
                name = name.concat(SUFFIX);

            // Returns null on lookup failures:
            in = loader.getResourceAsStream(name);
            if (in != null) {
                result = new Properties();
                result.load(in); // Can throw IOException
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        result = null;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Throwable ignore) {
                logger.warn(ignore.getMessage(), ignore);
            }
    }

    if (THROW_ON_LOAD_FAILURE && (result == null)) {
        throw new IllegalArgumentException("could not load [" + name + "]" + " as "
                + (LOAD_AS_RESOURCE_BUNDLE ? "a resource bundle" : "a classloader resource"));
    }

    return result;
}

From source file:org.apache.drill.jdbc.ITTestShadedJar.java

private static URL getJdbcUrl() throws MalformedURLException {
    return new URL(String.format("%s../../target/drill-jdbc-all-%s.jar",
            ClassLoader.getSystemClassLoader().getResource("").toString(),
            System.getProperty("project.version")));

}

From source file:org.tequila.model.project.InternalClassPath.java

/**
 * Agrega una url al classloader interno
 * @see RuntimeClassPath/*from   ww w .j  av  a2s.c  om*/
 * @param url
 * @throws ProjectException No se puede agregar el recurso al classpath interno
 */
protected static void addURL(URL url) throws ProjectException {
    log.debug("Agregando el recurso '" + url + "' al classpath interno");

    try {
        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<?> clazz = URLClassLoader.class;

        Method method = clazz.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(classLoader, new Object[] { url });
    } catch (Exception ex) {
        throw new ProjectException("No se puede agregar recurso " + "'" + url + "' al classpath interno", ex);
    }
}

From source file:oz.hadoop.yarn.api.utils.ConfigUtils.java

/**
 * Will dynamically add configuration directory to the classpath.
 * /*w ww. j av a 2  s  .c o  m*/
 * @param configurationDirectoryPath
 */
public static void addToClasspath(File configurationDirectoryPath) {
    Assert.notNull(configurationDirectoryPath, "'configurationDirectoryPath' must not be null");
    Assert.isTrue(configurationDirectoryPath.exists(), "'configurationDirectoryPath' must exist");
    Assert.isTrue(configurationDirectoryPath.isDirectory(), "'configurationDirectoryPath' must be a directory");

    URL configUrl = null;
    try {
        configUrl = new URL("file:" + configurationDirectoryPath.getAbsolutePath() + "/");
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to construct URL for " + configurationDirectoryPath, e);
    }
    URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method addUrlMethod = ReflectionUtils.getMethodAndMakeAccessible(URLClassLoader.class, "addURL", URL.class);
    try {
        addUrlMethod.invoke(cl, configUrl);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to add URL: " + configUrl + " to the classpath", e);
    }
}