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.eucalyptus.ws.handlers.WalrusRESTBinding.java

@Override
public Object bind(final MappingHttpRequest httpRequest) throws Exception {
    String servicePath = httpRequest.getServicePath();
    Map bindingArguments = new HashMap();
    final String operationName = getOperation(httpRequest, bindingArguments);
    if (operationName == null)
        throw new InvalidOperationException("Could not determine operation name for " + servicePath);

    Map<String, String> params = httpRequest.getParameters();

    OMElement msg;/*from ww w .j  ava2 s  .  c o m*/

    GroovyObject groovyMsg;
    Map<String, String> fieldMap;
    Class targetType;
    try {
        //:: try to create the target class :://
        targetType = ClassLoader.getSystemClassLoader()
                .loadClass("edu.ucsb.eucalyptus.msgs.".concat(operationName).concat("Type"));
        if (!GroovyObject.class.isAssignableFrom(targetType)) {
            throw new Exception();
        }
        //:: get the map of parameters to fields :://
        fieldMap = this.buildFieldMap(targetType);
        //:: get an instance of the message :://
        groovyMsg = (GroovyObject) targetType.newInstance();
    } catch (Exception e) {
        throw new BindingException("Failed to construct message of type " + operationName);
    }

    addLogData((BaseMessage) groovyMsg, bindingArguments);

    //TODO: Refactor this to be more general
    List<String> failedMappings = populateObject(groovyMsg, fieldMap, params);
    populateObjectFromBindingMap(groovyMsg, fieldMap, httpRequest, bindingArguments);

    User user = Contexts.lookup(httpRequest.getCorrelationId()).getUser();
    setRequiredParams(groovyMsg, user);

    if (!failedMappings.isEmpty() || !params.isEmpty()) {
        StringBuilder errMsg = new StringBuilder("Failed to bind the following fields:\n");
        for (String f : failedMappings)
            errMsg.append(f).append('\n');
        for (Map.Entry<String, String> f : params.entrySet())
            errMsg.append(f.getKey()).append(" = ").append(f.getValue()).append('\n');
        throw new BindingException(errMsg.toString());
    }

    LOG.info(groovyMsg.toString());
    try {
        Binding binding = BindingManager
                .getBinding(BindingManager.sanitizeNamespace("http://msgs.eucalyptus.com"));
        msg = binding.toOM(groovyMsg);
    } catch (RuntimeException e) {
        throw new BindingException("Failed to build a valid message: " + e.getMessage());
    }

    return groovyMsg;

}

From source file:com.eucalyptus.objectstorage.pipeline.WalrusRESTBinding.java

@Override
public Object bind(final MappingHttpRequest httpRequest) throws Exception {
    String servicePath = httpRequest.getServicePath();
    Map bindingArguments = new HashMap();
    final String operationName = getOperation(httpRequest, bindingArguments);
    if (operationName == null)
        throw new InvalidOperationException("Could not determine operation name for " + servicePath);

    Map<String, String> params = httpRequest.getParameters();

    OMElement msg;/*ww  w . j a v a2  s  .c  o m*/

    GroovyObject groovyMsg;
    Map<String, String> fieldMap;
    Class targetType;
    try {
        //:: try to create the target class :://
        targetType = ClassLoader.getSystemClassLoader()
                .loadClass("com.eucalyptus.objectstorage.msgs.".concat(operationName).concat("Type"));
        if (!GroovyObject.class.isAssignableFrom(targetType)) {
            throw new Exception();
        }
        //:: get the map of parameters to fields :://
        fieldMap = this.buildFieldMap(targetType);
        //:: get an instance of the message :://
        groovyMsg = (GroovyObject) targetType.newInstance();
    } catch (Exception e) {
        throw new BindingException("Failed to construct message of type " + operationName);
    }

    addLogData((BaseMessage) groovyMsg, bindingArguments);

    //TODO: Refactor this to be more general
    List<String> failedMappings = populateObject(groovyMsg, fieldMap, params);
    populateObjectFromBindingMap(groovyMsg, fieldMap, httpRequest, bindingArguments);

    User user = Contexts.lookup(httpRequest.getCorrelationId()).getUser();
    setRequiredParams(groovyMsg, user);

    if (!params.isEmpty()) {
        //ignore params that are not consumed, EUCA-4840
        params.clear();
    }

    if (!failedMappings.isEmpty()) {
        StringBuilder errMsg = new StringBuilder("Failed to bind the following fields:\n");
        for (String f : failedMappings)
            errMsg.append(f).append('\n');
        for (Map.Entry<String, String> f : params.entrySet())
            errMsg.append(f.getKey()).append(" = ").append(f.getValue()).append('\n');
        throw new BindingException(errMsg.toString());
    }

    LOG.debug(groovyMsg.toString());
    try {
        Binding binding = BindingManager.getDefaultBinding();
        msg = binding.toOM(groovyMsg);
    } catch (RuntimeException e) {
        throw new BindingException("Failed to build a valid message: " + e.getMessage());
    }

    return groovyMsg;

}

From source file:model.settings.ReadSettings.java

/**
 * Set up paint as program in OSX./*from   w  w  w  .  j a  v  a 2 s .c  o  m*/
 */
private static void installOSX() {

    try {

        final String name = "paint";
        final String app_name = "Paint.app";
        /*
         * STEP 1:   Create files and folders for the info.plist
         */
        final String filePath = "/Applications/" + app_name + "/Contents/";
        final String fileName = "Info.plist";
        final String fileContent = "" + "<dict>\n" + "    <key>CFBundleTypeExtensions</key>\n" + "    <array>\n"
                + "        <string>jpeg</string>\n" + "        <string>png</string>\n"
                + "        <string>gif</string>\n" + "        <string>pic</string>\n" + "    </array>\n"
                + "</dict>";

        FileWriter fw;
        // create necessary directories
        File p = new File(filePath);
        p.mkdirs();

        //TODO: this is just a debug parameter
        boolean installed = new File(filePath + fileName).exists();
        if (!installed) {

            // Create info.plist
            fw = new FileWriter(filePath + fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileContent);
            bw.flush();
            bw.close();
            fw.close();
        }

        /*
         * STEP 2:   Create (executable) file which is called if the 
         *          application is run.
         */
        final String app_folder_path = filePath + "MacOS/";
        final String app_file_path = app_folder_path + name;
        new File(app_folder_path).mkdirs();
        String orig_jar_file = "";
        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";

        final String jar_file_path = app_file_path + ".jar";
        final String content = "#!/bin/bash\n" + "echo $1\n" + "echo $2\n" + "echo $3\n" + "java -jar "
                + jar_file_path + " $@$0$1";

        // Create application file
        FileWriter fw2 = new FileWriter(app_file_path);
        BufferedWriter bw_2 = new BufferedWriter(fw2);
        bw_2.write(content);
        bw_2.flush();
        bw_2.close();
        fw2.close();

        // Make the file executable

        final String command0 = "chmod a+x " + app_file_path;
        String ret = Util.executeCommandLinux(command0);

        /*
         * Step 3:   Copy .jar file to the destination.
         */

        final String command1 = "cp " + orig_jar_file + " " + jar_file_path;
        String ret1 = Util.executeCommandLinux(command1);

        if (!installed) {

            final String command2 = "/System/Library/Frameworks/CoreServices.framework/Versions/"
                    + "A/Frameworks/LaunchServices.framework/Versions/A/Support/"
                    + "lsregister -f /Applications/" + app_name + "/";
            String ret2 = Util.executeCommandLinux(command2);

            final String command3 = "killall Finder";
            String ret3 = Util.executeCommandLinux(command3);

            String s = "Operation log:\n";
            System.out.println(s);
            System.out.println(ret + "\n" + ret1 + "\n" + ret2 + "\n" + ret3);

        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Search all {@link URLClassLoader} URLs for jar file references and add them to the
 * given set of resources in the form of pointers to the root of the jar file content.
 * @param classLoader the ClassLoader to search (including its ancestors)
 * @param result the set of resources to add jar roots to
 * @since 4.1.1/*ww w.  j a  v  a2 s. co  m*/
 */
protected void addAllClassLoaderJarRoots(@Nullable ClassLoader classLoader, Set<Resource> result) {
    if (classLoader instanceof URLClassLoader) {
        try {
            for (URL url : ((URLClassLoader) classLoader).getURLs()) {
                try {
                    UrlResource jarResource = new UrlResource(
                            ResourceUtils.JAR_URL_PREFIX + url + ResourceUtils.JAR_URL_SEPARATOR);
                    if (jarResource.exists()) {
                        result.add(jarResource);
                    }
                } catch (MalformedURLException ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Cannot search for matching files underneath [" + url
                                + "] because it cannot be converted to a valid 'jar:' URL: " + ex.getMessage());
                    }
                }
            }
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot introspect jar files since ClassLoader [" + classLoader
                        + "] does not support 'getURLs()': " + ex);
            }
        }
    }

    if (classLoader == ClassLoader.getSystemClassLoader()) {
        // "java.class.path" manifest evaluation...
        addClassPathManifestEntries(result);
    }

    if (classLoader != null) {
        try {
            // Hierarchy traversal...
            addAllClassLoaderJarRoots(classLoader.getParent(), result);
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot introspect jar files in parent ClassLoader since [" + classLoader
                        + "] does not support 'getParent()': " + ex);
            }
        }
    }
}

From source file:com.google.code.rees.scope.struts2.StrutsActionProvider.java

private UrlSet buildUrlSet(List<URL> resourceUrls) throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(resourceUrls);
    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 {//  ww w  . ja  v a  2 s.com
            // 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.apache.ignite.cache.store.cassandra.persistence.PersistenceSettings.java

/**
 * Instantiates Class object for particular class
 *
 * @param clazz class name/* ww w.j  a  v a2s .  c  o m*/
 * @return Class object
 */
private Class getClassInstance(String clazz) {
    try {
        return Class.forName(clazz);
    } catch (ClassNotFoundException ignored) {
    }

    try {
        return Class.forName(clazz, true, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException ignored) {
    }

    try {
        return Class.forName(clazz, true, PersistenceSettings.class.getClassLoader());
    } catch (ClassNotFoundException ignored) {
    }

    try {
        return Class.forName(clazz, true, ClassLoader.getSystemClassLoader());
    } catch (ClassNotFoundException ignored) {
    }

    throw new IgniteException("Failed to load class '" + clazz + "' using reflection");
}

From source file:org.wso2.carbon.analytics.data.commons.utils.AnalyticsCommonUtils.java

private static File getFileFromSystemResources(String fileName) {
    File file = null;/*ww  w. j a va2s.  c o  m*/
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    if (classLoader != null) {
        URL url = classLoader.getResource(fileName);
        if (url == null) {
            url = classLoader.getResource(File.separator + fileName);
        }
        try {
            file = new File(url.toURI());
        } catch (URISyntaxException e) {
            // file cannot be loaded
            return null;
        }
    }
    return file;
}

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

@Test
public void testSubmitJobAndWaitForExecutionResult() throws Exception {
    final TestJobExecutionResultHandler testJobExecutionResultHandler = new TestJobExecutionResultHandler(
            new RestHandlerException("should trigger retry", HttpResponseStatus.SERVICE_UNAVAILABLE),
            JobExecutionResultResponseBody.inProgress(),
            JobExecutionResultResponseBody.created(new JobResult.Builder()
                    .applicationStatus(ApplicationStatus.SUCCEEDED).jobId(jobId).netRuntime(Long.MAX_VALUE)
                    .accumulatorResults(Collections.singletonMap("testName",
                            new SerializedValue<>(OptionalFailure.of(1.0))))
                    .build()),/*w ww. j  av  a  2  s . c  o m*/
            JobExecutionResultResponseBody.created(new JobResult.Builder()
                    .applicationStatus(ApplicationStatus.FAILED).jobId(jobId).netRuntime(Long.MAX_VALUE)
                    .serializedThrowable(new SerializedThrowable(new RuntimeException("expected"))).build()));

    // 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 JobExecutionResultHeaders
                    && !firstPollFailed.getAndSet(true);

    try (TestRestServerEndpoint ignored = createRestServerEndpoint(testJobExecutionResultHandler,
            new TestJobSubmitHandler())) {

        JobExecutionResult jobExecutionResult;

        jobExecutionResult = (JobExecutionResult) restClusterClient.submitJob(jobGraph,
                ClassLoader.getSystemClassLoader());
        assertThat(jobExecutionResult.getJobID(), equalTo(jobId));
        assertThat(jobExecutionResult.getNetRuntime(), equalTo(Long.MAX_VALUE));
        assertThat(jobExecutionResult.getAllAccumulatorResults(),
                equalTo(Collections.singletonMap("testName", 1.0)));

        try {
            restClusterClient.submitJob(jobGraph, ClassLoader.getSystemClassLoader());
            fail("Expected exception not thrown.");
        } catch (final ProgramInvocationException e) {
            final Optional<RuntimeException> cause = ExceptionUtils.findThrowable(e, RuntimeException.class);

            assertThat(cause.isPresent(), is(true));
            assertThat(cause.get().getMessage(), equalTo("expected"));
        }
    }
}

From source file:org.wso2.ei.businessprocess.utils.migration.MigrationExecutor.java

private static void addPath(String s) throws Exception {
    File f = new File(s);
    URL u = f.toURL();/*w w w  .  ja v  a 2s . c o m*/
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> urlClass = URLClassLoader.class;
    Method method = urlClass.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(urlClassLoader, u);
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static ClassLoader getClassLoader() {
    ClassLoader classLoader = TargetConstructor.class.getClassLoader();

    if (classLoader == null) {
        classLoader = ClassLoader.getSystemClassLoader();
    }//from ww  w.ja  va  2  s .  c o m

    if (classLoader == null) {
        classLoader = Thread.currentThread().getContextClassLoader();
    }

    if (classLoader == null) {
        throw new RuntimeException("Cannot determine classloader");
    }

    return classLoader;
}