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.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.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  w w  w. j a  v a  2s .c  o  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, 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 (url.toExternalForm().contains(includeJar)) {
                        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:net.sf.jabref.openoffice.OpenOfficePanel.java

private static void addURL(List<URL> jarList) throws IOException {
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;
    try {//from  www  .  j a v  a2 s  .co m
        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");

    }
}

From source file:org.apache.catalina.core.ContainerBase.java

/**
 * Return the parent class loader (if any) for this web application.
 * This call is meaningful only <strong>after</strong> a Loader has
 * been configured./*  w ww . j a v  a 2  s . com*/
 */
public ClassLoader getParentClassLoader() {
    if (parentClassLoader != null)
        return (parentClassLoader);
    if (parent != null) {
        return (parent.getParentClassLoader());
    }
    return (ClassLoader.getSystemClassLoader());

}

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

@Test
public void testTriggerSavepoint() throws Exception {
    final String targetSavepointDirectory = "/tmp";
    final String savepointLocationDefaultDir = "/other/savepoint-0d2fb9-8d5e0106041a";
    final String savepointLocationRequestedDir = targetSavepointDirectory + "/savepoint-0d2fb9-8d5e0106041a";

    final TestSavepointHandlers testSavepointHandlers = new TestSavepointHandlers();
    final TestSavepointHandlers.TestSavepointTriggerHandler triggerHandler = testSavepointHandlers.new TestSavepointTriggerHandler(
            null, targetSavepointDirectory, null, null);
    final TestSavepointHandlers.TestSavepointHandler savepointHandler = testSavepointHandlers.new TestSavepointHandler(
            new SavepointInfo(savepointLocationDefaultDir, null),
            new SavepointInfo(savepointLocationRequestedDir, null),
            new SavepointInfo(null, new SerializedThrowable(new RuntimeException("expected"))),
            new RestHandlerException("not found", HttpResponseStatus.NOT_FOUND));

    // fail first HTTP polling attempt, which should not be a problem because of the retries
    final AtomicBoolean firstPollFailed = new AtomicBoolean();
    failHttpRequest = (messageHeaders, messageParameters,
            requestBody) -> messageHeaders instanceof SavepointStatusHeaders
                    && !firstPollFailed.getAndSet(true);

    try (TestRestServerEndpoint ignored = createRestServerEndpoint(triggerHandler, savepointHandler)) {

        JobID id = new JobID();
        {/*from   w w  w. ja v a 2 s. c o m*/
            CompletableFuture<String> savepointPathFuture = restClusterClient.triggerSavepoint(id, null);
            String savepointPath = savepointPathFuture.get();
            assertEquals(savepointLocationDefaultDir, savepointPath);
        }

        {
            CompletableFuture<String> savepointPathFuture = restClusterClient.triggerSavepoint(id,
                    targetSavepointDirectory);
            String savepointPath = savepointPathFuture.get();
            assertEquals(savepointLocationRequestedDir, savepointPath);
        }

        {
            try {
                restClusterClient.triggerSavepoint(id, null).get();
                fail("Expected exception not thrown.");
            } catch (ExecutionException e) {
                final Throwable cause = e.getCause();
                assertThat(cause, instanceOf(SerializedThrowable.class));
                assertThat(((SerializedThrowable) cause).deserializeError(ClassLoader.getSystemClassLoader())
                        .getMessage(), equalTo("expected"));
            }
        }

        try {
            restClusterClient.triggerSavepoint(new JobID(), null).get();
            fail("Expected exception not thrown.");
        } catch (final ExecutionException e) {
            assertTrue("RestClientException not in causal chain",
                    ExceptionUtils.findThrowable(e, RestClientException.class).isPresent());
        }
    }
}

From source file:org.limewire.util.FileUtils.java

public static File getJarFromClasspath(String markerFile) {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    if (classLoader == null) {
        classLoader = FileUtils.class.getClassLoader();
    }/* w ww  .j  a v  a 2s  . co m*/
    if (classLoader == null) {
        return null;
    }
    return getJarFromClasspath(classLoader, markerFile);
}

From source file:model.settings.ReadSettings.java

/**
 * Set up paint as program in OSX.//  w w w. j  a v a 2 s  .  c om
 */
private static void installLinux() {

    /*
     * setting up "open with" links for paint.
     * Therefore request SUDO rights.
     */
    try {

        final String userHome = System.getProperty("user.home");
        final String localDest = userHome + "/paint.desktop";
        final String finalDest = "/usr/share/applications/paint.desktop";
        Util.exportResource("/res/files/paint.desktop", localDest);

        String passwd = "";

        /*
         * Check whether the execution was successfully (and the password
         * was correct) or the file already exists
         */
        while (!new File(finalDest).exists()) {

            /*
             * Request SUDO privileges.
             */
            passwd = Util.requestSudoRights("mv " + localDest + " " + finalDest);

            if (passwd.equals("")) {
                JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges.");
                return;
            }

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        /*
         * Copy jar file
         */

        /////////////////////////Path for jar file.///////////////////
        // /usr/lib/paint/paint.jar requests sudo rights.
        // because of this, each time an update is done these rights 
        // have to be requested. Thus chose another path:
        // ~/.PaintUni/paint.jar
        // (PROGRAM_LOCATION/paint.jar)

        /*
         * STEP 2:   Create (executable) file which is called if the 
         *          application is run.
         */

        final String dest_jar_file = PROGRAM_LOCATION + "paint.jar";
        final String dest_exec = "/usr/bin/paint";
        String orig_jar_file = URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(),
                "UTF-8");

        // if Eclipse on-the-fly-compiling
        final String eclipseSubstring = "target/classes/";
        if (orig_jar_file.endsWith(eclipseSubstring)) {
            orig_jar_file = orig_jar_file.substring(0, orig_jar_file.length() - eclipseSubstring.length());

        }
        orig_jar_file += "paint.jar";

        /*
         * Step 3:   Copy .jar file to the destination.
         */
        try {
            Files.copy(Paths.get(orig_jar_file), Paths.get(dest_jar_file),
                    java.nio.file.StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException e) {

            final String command1 = "cp " + "\"" + orig_jar_file + "\"" + " " + "\"" + dest_jar_file + "\"";
            String ret1 = Util.executeCommandLinux(command1);
            System.out.println(command1 + "" + ret1);
        }

        final String content = "#!/bin/bash \n" + "java -jar " + dest_jar_file + " $1";

        // rather dirty solution. Creating a temporary file which is copied
        // to another location which requests sudoer rights.
        // If the temporary file already exists, randomly change the name.
        String temporaryLocation = userHome + "/paint_tmp_0123";
        while (new File(temporaryLocation).exists()) {
            temporaryLocation += "" + new Random().nextInt(10);
        }

        PrintWriter writer = new PrintWriter(temporaryLocation, "UTF-8");
        writer.println(content);
        writer.close();

        final String command = "mv " + temporaryLocation + " " + dest_exec;
        Util.execSudoCommand(command, passwd);
        // if the password was not correct / no sudo rights
        if (!new File(dest_exec).exists()) {
            while (!new File(dest_exec).exists()) {

                /*
                 * Request SUDO privileges.
                 */
                passwd = Util.requestSudoRights(command);

                if (passwd.equals("")) {
                    JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges.");
                    return;
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        Util.execSudoCommand("chmod a+x " + dest_exec, passwd);

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:cn.teamlab.wg.framework.struts2.json.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   w  w w . j  ava2s.c  o  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, 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/.*");

    String[] localIncludeJars = cn.teamlab.wg.framework.struts2.json.util.StringUtils.concat(includeJars,
            conventionIncludeJars);

    if (localIncludeJars == 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[localIncludeJars.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 < localIncludeJars.length; i++) {
                    String includeJar = localIncludeJars[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",
                            localIncludeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:es.cenobit.struts2.json.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  av a  2s. 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/.*");

    String[] localIncludeJars = es.cenobit.struts2.json.util.StringUtils.concat(includeJars,
            conventionIncludeJars);

    if (localIncludeJars == 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[localIncludeJars.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 < localIncludeJars.length; i++) {
                    String includeJar = localIncludeJars[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",
                            localIncludeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryGeneratorTest.java

private void addToClasspath(File source, File dest) throws Exception {
    String javaHomeStr = System.getProperty("java.home");
    File jreHome = new File(javaHomeStr);
    File toolsJar = new File(jreHome.getParent(), "lib/tools.jar");
    if (SystemUtils.IS_OS_MAC_OSX) {
        toolsJar = new File(jreHome.getParent(), "Classes/classes.jar");
    }//from ww w .j  a  v a 2s. c  o  m
    if (!toolsJar.exists()) {
        if (javaHomeStr.indexOf("jre") > 0 || javaHomeStr.indexOf("JRE") > 0) {
            if (javaHomeStr.endsWith("/")) {
                javaHomeStr = javaHomeStr + "../";
            } else {
                javaHomeStr = javaHomeStr + "/../";
            }
            jreHome = new File(javaHomeStr);
            toolsJar = new File(jreHome.getParent(), "lib/tools.jar");
        }

    }

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<?> sysclass = URLClassLoader.class;
    Class<?>[] parameters = { URL.class };
    URL u = toolsJar.toURI().toURL();
    Method method = sysclass.getDeclaredMethod("addURL", parameters);
    method.setAccessible(true);
    method.invoke(sysloader, new Object[] { u });
    method.invoke(sysloader, new Object[] { source.toURI().toURL() });
    method.invoke(sysloader, new Object[] { dest.toURI().toURL() });
}

From source file:com.intuit.tank.proxy.ProxyApp.java

private ImageIcon loadImage(String path) {
    URL url = ClassLoader.getSystemClassLoader().getResource(path);
    return new ImageIcon(url);
}