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.apache.ambari.server.api.services.AmbariMetaInfoTest.java

@Test
public void testMetaInfoFileFilter() throws Exception {
    String buildDir = tmpFolder.getRoot().getAbsolutePath();
    File stackRoot = new File("src/test/resources/stacks");
    File version = new File("src/test/resources/version");
    if (System.getProperty("os.name").contains("Windows")) {
        stackRoot = new File(ClassLoader.getSystemClassLoader().getResource("stacks").getPath());
        version = new File(new File(ClassLoader.getSystemClassLoader().getResource("").getPath()).getParent(),
                "version");
    }//from  ww w  . j  av  a  2  s . com
    File stackRootTmp = new File(buildDir + "/ambari-metaInfo");
    stackRootTmp.mkdir();
    FileUtils.copyDirectory(stackRoot, stackRootTmp);
    AmbariMetaInfo ambariMetaInfo = createAmbariMetaInfo(stackRootTmp, version, true);
    //todo
    //ambariMetaInfo.injector = injector;
    File f1, f2, f3;
    f1 = new File(stackRootTmp.getAbsolutePath() + "/001.svn");
    f1.createNewFile();
    f2 = new File(stackRootTmp.getAbsolutePath() + "/abcd.svn/001.svn");
    f2.mkdirs();
    f2.createNewFile();
    f3 = new File(stackRootTmp.getAbsolutePath() + "/.svn");
    if (!f3.exists()) {
        f3.createNewFile();
    }
    ambariMetaInfo.init();
    // Tests the stack is loaded as expected
    getServices();
    getComponentsByService();
    // Check .svn is not part of the stack but abcd.svn is
    Assert.assertNotNull(ambariMetaInfo.getStack("abcd.svn", "001.svn"));

    Assert.assertFalse(ambariMetaInfo.isSupportedStack(".svn", ""));
    Assert.assertFalse(ambariMetaInfo.isSupportedStack(".svn", ""));
}

From source file:com.eucalyptus.walrus.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 MethodNotAllowedException("Could not determine operation name for " + servicePath);

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

    OMElement msg;// w  w w. ja  va  2  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.walrus.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);

    final Context context = Contexts.lookup(httpRequest.getCorrelationId());
    setRequiredParams(groovyMsg, context);

    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.trace(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:goal.tools.PlatformManager.java

/**
 * Creates a new file and inserts a corresponding template into the file for
 * a given extension. Overwrites already existing file.
 *
 * @param newFile//from ww w.  j a  v a  2  s .  c  o  m
 *            The file to be created.
 * @param extension
 *            The {@link Extension} the file to be created should have. The
 *            extension is also used to select and apply the corresponding
 *            template to insert initial content in the file.
 *
 * @return The newly created or emptied file (CHECK which is just the same
 *         file as given as first param?).
 * @throws IOException
 *             If an I/O error occurs.
 */
public static File createfile(File newFile, Extension extension) throws IOException {
    /**
     * do not use f.createNewFile() because that does not overwrite existing
     * files.
     */

    // make sure the folder to write the file to exists.
    newFile.getParentFile().mkdirs();

    // Copy template if we have an extension.
    if (extension != null) {
        try (FileOutputStream outFile = new FileOutputStream(newFile)) {
            String templatename = "template" //$NON-NLS-1$
                    + extension.toString().toLowerCase();
            try (InputStream template = ClassLoader.getSystemClassLoader()
                    .getResourceAsStream("goal/tools/SimpleIDE/files/" + templatename)) { //$NON-NLS-1$
                if (template != null) {
                    IOUtils.copy(template, outFile);
                }
            }
        }
    }

    return newFile;
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

private void loadOpenIDProviders(ServletContext context) {
    Set<String> providers = new HashSet<String>();
    Properties providerProps = new Properties();

    InputStream is = getClass().getClassLoader().getResourceAsStream("openid-providers.properties");
    if (is == null) {
        LOG.info("couldn't find openid providers, using system class-loader");
        is = ClassLoader.getSystemClassLoader().getResourceAsStream("openid-properties.properties");
    }//from w w w  .ja  v  a 2  s. c o  m
    if (is != null) {
        try {
            providerProps.load(is);
        } catch (IOException e) {
            LOG.error("Could not load openid-providers.properties", e);
            blockingErrorKeys.put("errors.init.openidprovidersloading", null);
            return;
        }
    } else {
        LOG.error("Could not find openid-providers.properties");
        blockingErrorKeys.put("errors.init.openidproviders", null);
        return;
    }

    for (Object key : providerProps.keySet()) {
        String keyString = (String) key;
        if (!keyString.endsWith(".alias")) {
            providers.add(keyString);
            LOG.info("Added " + keyString);
        }
    }

    SessionMethods.setOpenIdProviders(context, providers);
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Invoke the main method on the given class, using the specified args, with a classloader including all jars in the
 * specified libdir//from   w w  w . jav a  2 s . c  om
 *
 * @param CLASSNAME class to invoke
 * @param args      arguments to pass to main method
 * @param libdir    dir containing required jar files
 *
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 * @throws MalformedURLException
 */
public void invokeMain(final String CLASSNAME, final String[] args, final File libdir)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException,
        MalformedURLException {
    final ClassLoaderUtil clload = new ClassLoaderUtil(libdir);
    // load the class
    final ClassLoader loader = clload.getClassLoader(ClassLoader.getSystemClassLoader());

    final Class cls = Class.forName(CLASSNAME, true, loader);
    // invokde the main method via reflection
    final Method mainMethod = ClassLoaderUtil.findMain(cls);

    Thread.currentThread().setContextClassLoader(loader);
    DEBUG("Start server with " + CLASSNAME + ".main(" + Arrays.toString(args) + ")");
    mainMethod.invoke(null, new Object[] { args });
}

From source file:tvbrowser.core.PluginLoader.java

private void getBaseInfoOfPlugins(File[] plugins, ArrayList<PluginBaseInfo> availablePlugins) {
    for (File plugin : plugins) {
        URL[] urls;/*from  ww  w  . j  a  va 2s .  co  m*/

        // Get the plugin name
        String pluginName = plugin.getName();
        pluginName = pluginName.substring(0, pluginName.length() - 4);
        Class pluginClass = null;

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

            pluginClass = classLoader.loadClass(pluginName.toLowerCase() + "." + pluginName);
            Method getVersion = pluginClass.getMethod("getVersion", new Class[0]);

            try {
                Version version = (Version) getVersion.invoke(pluginClass, new Object[0]);

                PluginBaseInfo baseInfo = new PluginBaseInfo("java." + pluginClass.getName(), version);

                if (!availablePlugins.contains(baseInfo)) {
                    availablePlugins.add(baseInfo);
                }
            } catch (Exception e) {
            }

        } catch (Throwable t) {
            urls = null;
            pluginClass = null;
            System.gc();

            PluginBaseInfo baseInfo = new PluginBaseInfo("java." + pluginName.toLowerCase() + "." + pluginName,
                    new Version(0, 0));

            if (!availablePlugins.contains(baseInfo)) {
                availablePlugins.add(baseInfo);
            }

            mLog.info("Could not load base info for plugin file '" + plugin.getAbsolutePath()
                    + "'. Use default version instead.");
        }
    }
}

From source file:ar.edu.taco.TacoMain.java

/**
 * /* ww  w  .  ja v  a 2 s . co  m*/
 * @param configFile
 * @param overridingProperties
 *            Properties that overrides properties file's values
 */

public TacoAnalysisResult run(String configFile, Properties overridingProperties)
        throws IllegalArgumentException {

    AlloyTyping varsEncodingValueOfArithmeticOperationsInObjectInvariants = new AlloyTyping();
    List<AlloyFormula> predsEncodingValueOfArithmeticOperationsInObjectInvariants = new ArrayList<AlloyFormula>();

    if (configFile == null) {
        throw new IllegalArgumentException("Config file not found, please verify option -cf");
    }

    List<JCompilationUnitType> compilation_units = null;
    String classToCheck = null;
    String methodToCheck = null;

    // Start configurator
    JDynAlloyConfig.reset();
    JDynAlloyConfig.buildConfig(configFile, overridingProperties);

    List<JDynAlloyModule> jdynalloy_modules = new ArrayList<JDynAlloyModule>();
    SimpleJmlToJDynAlloyContext simpleJmlToJDynAlloyContext;
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.JMLPARSER_ENABLED,
            TacoConfigurator.JMLPARSER_ENABLED_DEFAULT)) {
        // JAVA PARSING
        String sourceRootDir = TacoConfigurator.getInstance()
                .getString(TacoConfigurator.JMLPARSER_SOURCE_PATH_STR);

        if (TacoConfigurator.getInstance().getString(TacoConfigurator.CLASS_TO_CHECK_FIELD) == null) {
            throw new TacoException(
                    "Config key 'CLASS_TO_CHECK_FIELD' is mandatory. Please check your config file or add the -c parameter");
        }
        List<String> files = new ArrayList<String>(Arrays.asList(JDynAlloyConfig.getInstance().getClasses()));

        classToCheck = TacoConfigurator.getInstance().getString(TacoConfigurator.CLASS_TO_CHECK_FIELD);
        String[] splitName = classToCheck.split("_");
        classToCheck = "";
        for (int idx = 0; idx < splitName.length - 2; idx++) {
            classToCheck += splitName[idx] + "_";
        }

        if (splitName.length >= 2)
            classToCheck += splitName[splitName.length - 2] + "Instrumented_";
        classToCheck += splitName[splitName.length - 1];

        if (!files.contains(classToCheck)) {
            files.add(classToCheck);
        }

        List<String> processedFileNames = new ArrayList<String>();
        for (String file : files) {
            String begin = file.substring(0, file.lastIndexOf('.'));
            String end = file.substring(file.lastIndexOf('.'), file.length());
            processedFileNames.add(begin + "Instrumented" + end);
        }

        files = processedFileNames;

        JmlParser.getInstance().initialize(sourceRootDir,
                System.getProperty("user.dir") + System.getProperty("file.separator") + "bin" /* Unused */,
                files);
        compilation_units = JmlParser.getInstance().getCompilationUnits();
        // END JAVA PARSING

        // SIMPLIFICATION
        JmlStage aJavaCodeSimplifier = new JmlStage(compilation_units);
        aJavaCodeSimplifier.execute();
        JmlToSimpleJmlContext jmlToSimpleJmlContext = aJavaCodeSimplifier.getJmlToSimpleJmlContext();
        List<JCompilationUnitType> simplified_compilation_units = aJavaCodeSimplifier
                .get_simplified_compilation_units();
        // END SIMPLIFICATION

        // JAVA TO JDYNALLOY TRANSLATION
        SimpleJmlStage aJavaToDynJAlloyTranslator = new SimpleJmlStage(simplified_compilation_units);
        aJavaToDynJAlloyTranslator.execute();
        // END JAVA TO JDYNALLOY TRANSLATION
        simpleJmlToJDynAlloyContext = aJavaToDynJAlloyTranslator.getSimpleJmlToJDynAlloyContext();
        varsEncodingValueOfArithmeticOperationsInObjectInvariants = aJavaToDynJAlloyTranslator
                .getVarsEncodingValueOfArithmeticOperationsInInvariants();
        predsEncodingValueOfArithmeticOperationsInObjectInvariants = aJavaToDynJAlloyTranslator
                .getPredsEncodingValueOfArithmeticOperationsInInvariants();

        // JFSL TO JDYNALLOY TRANSLATION
        JfslStage aJfslToDynJAlloyTranslator = new JfslStage(simplified_compilation_units,
                aJavaToDynJAlloyTranslator.getModules(), jmlToSimpleJmlContext, simpleJmlToJDynAlloyContext);
        aJfslToDynJAlloyTranslator.execute();
        /**/ aJfslToDynJAlloyTranslator = null;
        // END JFSL TO JDYNALLOY TRANSLATION

        // PRINT JDYNALLOY
        JDynAlloyPrinterStage printerStage = new JDynAlloyPrinterStage(aJavaToDynJAlloyTranslator.getModules());
        printerStage.execute();
        /**/ printerStage = null;
        // END PRINT JDYNALLOY

        jdynalloy_modules.addAll(aJavaToDynJAlloyTranslator.getModules());

    } else {
        simpleJmlToJDynAlloyContext = null;
    }

    // JDYNALLOY BUILT-IN MODULES
    PrecompiledModules precompiledModules = new PrecompiledModules();
    precompiledModules.execute();
    jdynalloy_modules.addAll(precompiledModules.getModules());
    // END JDYNALLOY BUILT-IN MODULES

    // JDYNALLOY STATIC FIELDS CLASS
    JDynAlloyModule staticFieldsModule = precompiledModules.generateStaticFieldsModule();
    jdynalloy_modules.add(staticFieldsModule);
    /**/ staticFieldsModule = null;
    // END JDYNALLOY STATIC FIELDS CLASS

    // JDYNALLOY PARSING
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.JDYNALLOY_PARSER_ENABLED,
            TacoConfigurator.JDYNALLOY_PARSER_ENABLED_DEFAULT)) {
        log.info("****** START: Parsing JDynAlloy files ****** ");
        JDynAlloyParsingStage jDynAlloyParser = new JDynAlloyParsingStage(jdynalloy_modules);
        jDynAlloyParser.execute();
        jdynalloy_modules.addAll(jDynAlloyParser.getParsedModules());
        /**/ jDynAlloyParser = null;
        log.info("****** END: Parsing JDynAlloy files ****** ");
    } else {
        log.info(
                "****** INFO: Parsing JDynAlloy is disabled (hint enablet it using 'jdynalloy.parser.enabled') ****** ");
    }
    // END JDYNALLOY PARSING

    // JDYNALLOY TO DYNALLOY TRANSLATION
    JDynAlloyStage dynJAlloyToDynAlloyTranslator = new JDynAlloyStage(jdynalloy_modules);
    /**/ jdynalloy_modules = null;
    dynJAlloyToDynAlloyTranslator.execute();
    // BEGIN JDYNALLOY TO DYNALLOY TRANSLATION

    AlloyAnalysisResult alloy_analysis_result = null;
    DynalloyStage dynalloyToAlloy = null;

    // DYNALLOY TO ALLOY TRANSLATION
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.DYNALLOY_TO_ALLOY_ENABLE)) {

        dynalloyToAlloy = new DynalloyStage(dynJAlloyToDynAlloyTranslator.getOutputFileNames());
        dynalloyToAlloy.setSourceJDynAlloy(dynJAlloyToDynAlloyTranslator.getPrunedModules());
        /**/ dynJAlloyToDynAlloyTranslator = null;
        dynalloyToAlloy.execute();
        // DYNALLOY TO ALLOY TRANSLATION

        log.info("****** Transformation process finished ****** ");

        if (TacoConfigurator.getInstance().getNoVerify() == false) {
            // Starts dynalloy to alloy tranlation and alloy verification

            AlloyStage alloy_stage = new AlloyStage(dynalloyToAlloy.get_alloy_filename());
            /**/ dynalloyToAlloy = null;

            alloy_stage.execute();

            alloy_analysis_result = alloy_stage.get_analysis_result();
            /**/ alloy_stage = null;
        }
    }

    TacoAnalysisResult tacoAnalysisResult = new TacoAnalysisResult(alloy_analysis_result);

    String junitFile = null;

    if (TacoConfigurator.getInstance().getGenerateUnitTestCase()
            || TacoConfigurator.getInstance().getAttemptToCorrectBug()) {
        // Begin JUNIT Generation Stage
        methodToCheck = overridingProperties.getProperty(TacoConfigurator.METHOD_TO_CHECK_FIELD);

        SnapshotStage snapshotStage = new SnapshotStage(compilation_units, tacoAnalysisResult, classToCheck,
                methodToCheck);
        snapshotStage.execute();

        RecoveredInformation recoveredInformation = snapshotStage.getRecoveredInformation();
        recoveredInformation.setFileNameSuffix(StrykerStage.fileSuffix);
        JUnitStage jUnitStage = new JUnitStage(recoveredInformation);
        jUnitStage.execute();
        junitFile = jUnitStage.getJunitFileName();
        //         StrykerStage.fileSuffix++;
        // End JUNIT Generation Stage
    } else {
        log.info("****** JUnit with counterexample values will not be generated. ******* ");
        if (!TacoConfigurator.getInstance().getGenerateUnitTestCase()) {
            log.info("****** generateUnitTestCase=false ******* ");
        }

    }

    if (TacoConfigurator.getInstance().getBuildJavaTrace()) {
        if (tacoAnalysisResult.get_alloy_analysis_result().isSAT()) {
            log.info("****** START: Java Trace Generation ****** ");
            DynAlloyCompiler compiler = dynalloyToAlloy.getDynAlloyCompiler();
            JavaTraceStage javaTraceStage = new JavaTraceStage(compiler.getSpecContext(), alloy_analysis_result,
                    false);
            javaTraceStage.execute();
            //            DynAlloySolution dynAlloySolution = javaTraceStage.getDynAlloySolution();
            //            List<TraceStep> trace = dynAlloySolution.getTrace();

            log.info("****** FINISH: Java Trace Generation ****** ");
        }
    } else {
        log.info("****** Java Trace will not be generated. ******* ");
        log.info("****** generateJavaTrace=false ******* ");
    }

    if (TacoConfigurator.getInstance().getAttemptToCorrectBug()) {
        if (tacoAnalysisResult.get_alloy_analysis_result().isSAT() && tacoAnalysisResult
                .get_alloy_analysis_result().getAlloy_solution().getOriginalCommand().startsWith("Check")) {
            log.info("****** START: Stryker ****** ");
            methodToCheck = overridingProperties.getProperty(TacoConfigurator.METHOD_TO_CHECK_FIELD);
            String sourceRootDir = TacoConfigurator.getInstance()
                    .getString(TacoConfigurator.JMLPARSER_SOURCE_PATH_STR);
            StrykerStage strykerStage = new StrykerStage(compilation_units, sourceRootDir, classToCheck,
                    methodToCheck, configFile, overridingProperties,
                    TacoConfigurator.getInstance().getMaxStrykerMethodsForFile());
            StrykerStage.junitInputs = new Class<?>[50];

            try {
                String currentJunit = null;

                String tempFilename = junitFile.substring(0,
                        junitFile.lastIndexOf(FILE_SEP) + 1) /*+ FILE_SEP*/;
                String packageToWrite = "ar.edu.output.junit";
                String fileClasspath = tempFilename.substring(0, tempFilename
                        .lastIndexOf(new String("ar.edu.generated.junit").replaceAll("\\.", FILE_SEP)));
                fileClasspath = fileClasspath.replaceFirst("generated", "output");
                //               String currentClasspath = System.getProperty("java.class.path")+PATH_SEP+fileClasspath/*+PATH_SEP+System.getProperty("user.dir")+FILE_SEP+"generated"*/;
                currentJunit = editTestFileToCompile(junitFile, classToCheck, packageToWrite, methodToCheck);

                File[] file1 = new File[] { new File(currentJunit) };
                JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
                StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
                Iterable<? extends JavaFileObject> compilationUnit1 = fileManager
                        .getJavaFileObjectsFromFiles(Arrays.asList(file1));
                javaCompiler.getTask(null, fileManager, null, null, null, compilationUnit1).call();
                fileManager.close();
                javaCompiler = null;
                file1 = null;
                fileManager = null;

                ///*mfrias*/      int compilationResult =   javaCompiler.run(null, null, null /*new NullOutputStream()*/, new String[]{"-classpath", currentClasspath, currentJunit});
                ///**/            javaCompiler = null;
                //               if(compilationResult == 0) {
                log.warn("junit counterexample compilation succeded");
                ClassLoader cl = ClassLoader.getSystemClassLoader();
                @SuppressWarnings("resource")
                ClassLoader cl2 = new URLClassLoader(new URL[] { new File(fileClasspath).toURI().toURL() }, cl);
                //                  ClassLoaderTools.addFile(fileClasspath);
                Class<?> clazz = cl2.loadClass(packageToWrite + "." + obtainClassNameFromFileName(junitFile));
                //                  Method[] meth = clazz.getMethods();
                //                  log.info("preparing to add a class containing a test input to the pool... "+packageToWrite+"."+MuJavaController.obtainClassNameFromFileName(junitFile));
                //                  Result result = null;
                //                  final Object oToRun = clazz.newInstance();
                StrykerStage.junitInputs[StrykerStage.indexToLastJUnitInput] = clazz;
                StrykerStage.indexToLastJUnitInput++;
                cl = null;
                cl2 = null;

                //               
                //               } else {
                //                  log.warn("compilation failed");
                //               }
                //                     File originalFile = new File(tempFilename);
                //                     originalFile.delete();

            } catch (ClassNotFoundException e) {
                //                     e.printStackTrace();
            } catch (IOException e) {
                //                     e.printStackTrace();
            } catch (IllegalArgumentException e) {
                //                     e.printStackTrace();
            } catch (Exception e) {
                //                     e.printStackTrace();
            }

            strykerStage.execute();

            log.info("****** FINISH: Stryker ****** ");
        }
    } else {
        log.info("****** BugFix will not be generated. ******* ");
        log.info("****** attemptToCorrectBug=false ******* ");
    }

    return tacoAnalysisResult;
}

From source file:org.owasp.esapi.reference.DefaultSecurityConfiguration.java

/**
 * Used to load ESAPI.properties from a variety of different classpath locations.
 *
 * @param fileName The properties file filename.
 *//*from w  ww  .j a v  a  2 s  .co  m*/
private Properties loadConfigurationFromClasspath(String fileName) throws IllegalArgumentException {
    Properties result = null;
    InputStream in = null;

    ClassLoader[] loaders = new ClassLoader[] { Thread.currentThread().getContextClassLoader(),
            ClassLoader.getSystemClassLoader(), getClass().getClassLoader() };
    String[] classLoaderNames = { "current thread context class loader", "system class loader",
            "class loader for DefaultSecurityConfiguration class" };

    ClassLoader currentLoader = null;
    for (int i = 0; i < loaders.length; i++) {
        if (loaders[i] != null) {
            currentLoader = loaders[i];
            try {
                // try root
                String currentClasspathSearchLocation = "/ (root)";
                in = loaders[i].getResourceAsStream(fileName);

                // try resourceDirectory folder
                if (in == null) {
                    currentClasspathSearchLocation = resourceDirectory + "/";
                    in = currentLoader.getResourceAsStream(resourceDirectory + "/" + fileName);
                }

                // try .esapi folder. Look here first for backward compatibility.
                if (in == null) {
                    currentClasspathSearchLocation = ".esapi/";
                    in = currentLoader.getResourceAsStream(".esapi/" + fileName);
                }

                // try esapi folder (new directory)
                if (in == null) {
                    currentClasspathSearchLocation = "esapi/";
                    in = currentLoader.getResourceAsStream("esapi/" + fileName);
                }

                // try resources folder
                if (in == null) {
                    currentClasspathSearchLocation = "src/main/resources/";
                    in = currentLoader.getResourceAsStream("src/main/resources/" + fileName);
                }

                // now load the properties
                if (in != null) {
                    result = new Properties();
                    result.load(in); // Can throw IOException
                    logSpecial("SUCCESSFULLY LOADED " + fileName + " via the CLASSPATH from '"
                            + currentClasspathSearchLocation + "' using " + classLoaderNames[i] + "!");
                    break; // Outta here since we've found and loaded it.
                }
            } catch (Exception e) {
                result = null;

            } finally {
                try {
                    in.close();
                } catch (Exception e) {
                }
            }
        }
    }

    if (result == null) {
        // CHECKME: This is odd...why not ConfigurationException?
        throw new IllegalArgumentException("Failed to load " + resourceFile + " as a classloader resource.");
    }

    return result;
}

From source file:org.apache.ambari.server.stack.StackManagerTest.java

@Test
public void testInheritKerberosDescriptor() throws Exception {
    StackInfo stack = stackManager.getStack("HDP", "2.1.1");
    String stacksFolder = ClassLoader.getSystemClassLoader().getResource("stacks").getPath();
    assertEquals(new File(stacksFolder, "HDP/2.0.8/kerberos.json").getAbsolutePath(),
            stack.getKerberosDescriptorFileLocation());
}

From source file:org.mule.util.ClassUtils.java

public static void addLibrariesToClasspath(List urls)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    ClassLoader sys = ClassLoader.getSystemClassLoader();
    if (!(sys instanceof URLClassLoader)) {
        throw new IllegalArgumentException(
                "PANIC: Mule has been started with an unsupported classloader: " + sys.getClass().getName()
                        + ". " + "Please report this error to user<at>mule<dot>codehaus<dot>org");
    }/*from   ww  w  . j ava 2s .  c o m*/

    // system classloader is in this case the one that launched the application,
    // which is usually something like a JDK-vendor proprietary AppClassLoader
    URLClassLoader sysCl = (URLClassLoader) sys;

    /*
    * IMPORTANT NOTE: The more 'natural' way would be to create a custom
    * URLClassLoader and configure it, but then there's a chicken-and-egg
    * problem, as all classes MuleBootstrap depends on would have been loaded by
    * a parent classloader, and not ours. There's no straightforward way to
    * change this, and is documented in a Sun's classloader guide. The solution
    * would've involved overriding the ClassLoader.findClass() method and
    * modifying the semantics to be child-first, but that way we are calling for
    * trouble. Hacking the primordial classloader is a bit brutal, but works
    * perfectly in case of running from the command-line as a standalone app.
    * All Mule embedding options then delegate the classpath config to the
    * embedder (a developer embedding Mule in the app), thus classloaders are
    * not modified in those scenarios.
    */

    // get a Method ref from the normal class, but invoke on a proprietary parent
    // object,
    // as this method is usually protected in those classloaders
    Class refClass = URLClassLoader.class;
    Method methodAddUrl = refClass.getDeclaredMethod("addURL", new Class[] { URL.class });
    methodAddUrl.setAccessible(true);
    for (Iterator it = urls.iterator(); it.hasNext();) {
        URL url = (URL) it.next();
        methodAddUrl.invoke(sysCl, url);
    }
}