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.springframework.data.hadoop.mapreduce.ExecutionUtils.java

/**
 * Utility method used before invoking custom code for preventing custom classloader, set as the Thread
 * context class-loader, to leak (typically through JDK classes).
 *//*from w  w  w .j  a v a  2  s.c  o  m*/
static void preventJreTcclLeaks() {
    if (log.isDebugEnabled()) {
        log.debug("Preventing JRE TCCL leaks");
    }

    // get the root CL to be used instead
    ClassLoader sysLoader = ClassLoader.getSystemClassLoader();

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        // set the sysCL as the TCCL
        Thread.currentThread().setContextClassLoader(sysLoader);

        //
        // Handle security
        //

        // Policy holds the TCCL as static
        ClassUtils.resolveClassName("javax.security.auth.Policy", sysLoader);
        // since the class init may be lazy, call the method directly
        Policy.getPolicy();
        // Configuration holds the TCCL as static
        // call method with minimal side-effects (since just doing class loading doesn't seem to trigger the static init)
        try {
            javax.security.auth.login.Configuration.getInstance(null, null, (String) null);
        } catch (Exception ex) {
            // ignore
        }
        // seems to cause side-effects/exceptions
        // javax.security.auth.login.Configuration.getConfiguration();
        java.security.Security.getProviders();

        // load the JDBC drivers (used by Hive and co)
        DriverManager.getDrivers();
        // Initialize
        // sun.awt.AppContext.getAppContext()
        ImageIO.getCacheDirectory();

    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
}

From source file:org.mypsycho.util.PropertiesLoader.java

private ClassLoader getClassLoader(Class<?> type) {
    ClassLoader loader = type.getClassLoader();
    return (loader != null) ? loader : ClassLoader.getSystemClassLoader();
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.standalone.ServerDetector.java

private static Boolean _detect(String className) {
    try {/*  w w  w .  j  ava 2 s  .c  o  m*/
        ClassLoader.getSystemClassLoader().loadClass(className);

        return Boolean.TRUE;
    } catch (ClassNotFoundException cnfe) {
        ServerDetector sd = _instance;

        Class<?> c = sd.getClass();

        if (c.getResource(className) != null) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

public void init(String[] args, ClassLoader wrapperClassLoader) {
    /*/*w ww . j a v a2  s.  c o  m*/
     * System.out.println(Scheduler.class.getClassLoader());
     * System.out.println(Configuration.class.getClassLoader());
     * System.out.flush(); try { Thread.sleep(10000); } catch
     * (InterruptedException e1) { // TODO Auto-generated catch block
     * e1.printStackTrace(); }
     */
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(wrapperClassLoader);
    instance = this;
    String outFile = System.getProperty("wrapper.teeName");
    String outPath = System.getProperty("wrapper.tmpPath");
    String vStr = System.getProperty("wrapper.console.visible");
    boolean visible = vStr != null && vStr.equals("true");
    if (outFile != null) {
        teeSystemStreams(outFile, outPath, visible);
    }
    logJavaInfo(args);

    String preScript = System.getProperty("wrapper.app.pre.script");
    if (preScript != null & !"".equals(preScript)) {
        Logger logger = new MyLogger();
        logger.addHandler(new ConsoleHandler());
        Script script = ScriptFactory.createScript(preScript, "", null, new String[0], null);
        if (script != null)
            script.execute();
    }

    YajswConfigurationImpl config = new YajswConfigurationImpl();
    //config.setDebug(false);
    config.init();

    try {
        _overrideStdErr = config.getBoolean("wrapper.java.dump.override", false);
    } catch (Exception ex) {
        System.out.println("Error getting wrapper.java.dump.override " + ex.getMessage());
    }
    String mainClassName = config.getString("wrapper.java.app.mainclass");
    String jarName = config.getString("wrapper.java.app.jar");
    String groovyScript = config.getString("wrapper.groovy");
    if (mainClassName == null && jarName == null && groovyScript == null)
        mainClassName = config.getString("wrapper.app.parameter.1");
    if (jarName == null && mainClassName == null && groovyScript == null) {
        System.out.println("missing main class name or jar file or groovy file. please check configuration");
        return;
    }
    if (jarName != null) {
        mainMethod = loadJar(jarName);
    } else if (mainClassName != null)
        try {
            Class cls = ClassLoader.getSystemClassLoader().loadClass(mainClassName);// Class.forName(mainClassName,
            // currentContext);
            mainMethod = cls.getDeclaredMethod("main", new Class[] { String[].class });
        } catch (Exception e) {
            System.out.println("error finding main method in class: " + mainClassName + " : " + e.getMessage());
            // log.throwing(WrapperMain.class.getName(), "main", e);
            e.printStackTrace();
            return;
        }
    else
        _groovyScript = groovyScript;

    String stopConfig = config.getString("wrapper.stop.conf");
    if (stopConfig != null) {
        File f = new File(stopConfig);
        _externalStop = true;
    }
    System.out.println("external stop " + _externalStop);

    exitOnMainTerminate = config.getInt("wrapper.exit_on_main_terminate", DEFAULT_EXIT_ON_MAIN_TERMINATE);

    exitOnException = config.getInt("wrapper.exit_on_main_exception", DEFAULT_EXIT_ON_MAIN_EXCEPTION);

    mainMethodArgs = getAppParam((Configuration) config);
    setConfiguration((Configuration) config);
    if (_config.getBoolean("wrapper.java.jmx", false))
        registerMBean(config);

    String control = _config.getString("wrapper.control", DEFAULT_CONTROL);
    if ("TIGHT".equals(control) || "APPLICATION".equals(control))
        _haltAppOnWrapper = true;

    Thread.currentThread().setContextClassLoader(currentClassLoader);

    setKey(_config.getString("wrapper.key"));
    // setDebug(true);
    setPort(_config.getInt("wrapper.port"));
    setPingInterval(_config.getInt("wrapper.ping.interval", Constants.DEFAULT_PING_INTERVAL));

    _startupTimeout = _config.getInt("wrapper.startup.timeout", DEFAULT_STARTUP_TIMEOUT) * 1000;
    _debug = _config.getBoolean("wrapper.debug", false);
}

From source file:Which4J.java

/**
 * Search the specified classloader for the given classname.
 * /*from  www  .jav a  2s .  com*/
 * @param classname the fully qualified name of the class to search for
 * @param loader the classloader to search
 * @return the source location of the resource, or null if it wasn't found
 */
public static String which(String classname, ClassLoader loader) {

    if (isArrayType(classname)) {
        classname = getElementType(classname);
    }

    if (isPrimitiveOrVoid(classname)) {
        return "'" + classname + "' primitive";
    }

    String classnameAsResource = classname.replace('.', '/') + ".class";

    if (loader == null) {
        // some VM's return null from getClassLoader to indicate that
        // the class was loaded by the bootstrap class loader
        loader = ClassLoader.getSystemClassLoader();
    }
    URL it = loader.getResource(classnameAsResource);
    if (it != null) {
        return it.toString();
    } else {
        return null;
    }
}

From source file:com.ibm.team.build.internal.hjplugin.RTCFacadeFactory.java

private static RTCFacadeWrapper newFacade(String fullClassName, File toolkitFile, PrintStream debugLog)
        throws Exception {

    if (!toolkitFile.exists()) {
        throw new IllegalArgumentException(
                Messages.RTCFacadeFactory_toolkit_not_found(toolkitFile.getAbsolutePath()));
    }//from w  w  w  .ja  v a  2s.com
    if (!toolkitFile.isDirectory()) {
        throw new IllegalArgumentException(
                Messages.RTCFacadeFactory_toolkit_path_not_directory(toolkitFile.getAbsolutePath()));
    }

    RTCFacadeWrapper result = new RTCFacadeWrapper();

    URL[] toolkitURLs = getToolkitJarURLs(toolkitFile, debugLog);

    Class<?> originalClass = RTCFacadeFactory.class;
    ClassLoader originalClassLoader = originalClass.getClassLoader();
    debug(debugLog, "Original class loader: " + originalClassLoader); //$NON-NLS-1$

    // Get the jar for the hjplugin-rtc jar.
    URL[] combinedURLs;
    URL hjplugin_rtcJar = getFacadeJarURL(debugLog);
    if (hjplugin_rtcJar != null) {
        combinedURLs = new URL[toolkitURLs.length + 1];
        combinedURLs[0] = hjplugin_rtcJar;
        System.arraycopy(toolkitURLs, 0, combinedURLs, 1, toolkitURLs.length);
    } else {
        combinedURLs = toolkitURLs;
    }
    debug(debugLog, "System class loader " + ClassLoader.getSystemClassLoader()); //$NON-NLS-1$

    // We want the parent class loader to exclude the class loader which would normally
    // load classes from the hjplugin-rtc jar (because that class loader doesn't include
    // the toolkit jars).
    ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();

    // Normally the system class loader and the original class loader are different.
    // However in the case of running the tests within our build, the system class loader
    // is the original class loader with our single jar (and not its dependencies from the
    // toolkit) which results in ClassNotFound for classes we depend on (i.e. IProgressMonitor).
    // So use the parent in this case.
    if (parentClassLoader == originalClassLoader) {
        debug(debugLog, "System class loader and original are the same. Using parent " //$NON-NLS-1$
                + originalClassLoader.getParent());
        parentClassLoader = originalClassLoader.getParent();
    }
    if (Boolean.parseBoolean(System.getProperty(DISABLE_RTC_FACADE_CLASS_LOADER_PROPERTY, "false"))) { //$NON-NLS-1$
        debug(debugLog, "RTCFacadeClassLoader disabled, using URLClassLoader"); //$NON-NLS-1$
        result.newClassLoader = new URLClassLoader(combinedURLs, parentClassLoader);
    } else {
        result.newClassLoader = new RTCFacadeClassLoader(combinedURLs, parentClassLoader);
    }

    debug(debugLog, "new classloader: " + result.newClassLoader); //$NON-NLS-1$

    Class<?> facadeClass = result.newClassLoader.loadClass(fullClassName);
    debug(debugLog, "facadeClass: " + facadeClass); //$NON-NLS-1$
    debug(debugLog, "facadeClass classloader: " + facadeClass.getClassLoader()); //$NON-NLS-1$

    // using the new class loader get the facade instance
    // then revert immediately back to the original class loader
    ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(result.newClassLoader);
    try {
        result.facade = facadeClass.newInstance();
    } finally {
        Thread.currentThread().setContextClassLoader(originalContextClassLoader);
    }

    debug(debugLog, "facade: " + result.facade); //$NON-NLS-1$
    return result;
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;//from  ww  w.  j  ava 2  s .  co  m

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:com.eucalyptus.bootstrap.BootstrapClassLoader.java

private BootstrapClassLoader(URL[] urls) throws MalformedURLException {
    super(urls, ClassLoader.getSystemClassLoader());
    List<String> fpaths = Lists.newArrayList();
    for (URL path : Loader.getClassPaths()) {
        LOG.debug(path);//from www .  j  a  v  a2  s  .co m
        if ("file".equals(path.getProtocol())) {
            fpaths.add(path.getPath());
        }
    }
    // set paths to be used for loading referenced classes
    String[] dirs = (String[]) fpaths.toArray(new String[0]);
    ClassCache.setPaths(dirs);
    ClassFile.setPaths(dirs);
    ClasspathUrlExtender.setClassLoader(ClassFile.getClassLoader());
    // reset static information accumulation for binding
    BoundClass.reset();
    MungedClass.reset();
    BindingDefinition.reset();
}

From source file:org.ploin.pmf.impl.MailReader.java

/**
 * //from   ww w. ja  v  a  2 s.c  o m
 * @param fileName the name of the file
 * @return
 */
private String getFilename(final String fileName) {
    log.debug("getFilename: " + fileName);
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null)
        loader = ClassLoader.getSystemClassLoader();
    URL url = loader.getResource(fileName);
    if (url != null) {
        return url.getPath().replaceAll("%20", " "); // workaround for Windows homedir.
    } else {
        return null;
    }
}

From source file:org.apache.ranger.policyengine.CommandLineParser.java

public static URL getInputFileURL(final String name) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> getResourceFileURL(" + name + ")");
    }/*from ww  w  .j  a  v a2 s .c  o m*/
    URL ret = null;
    InputStream in = null;

    if (StringUtils.isNotBlank(name)) {

        File f = new File(name);

        if (f.exists() && f.isFile() && f.canRead()) {
            try {

                in = new FileInputStream(f);
                ret = f.toURI().toURL();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("URL:" + ret);
                }

            } catch (FileNotFoundException exception) {
                LOG.error("Error processing input file:" + name + " or no privilege for reading file " + name,
                        exception);
            } catch (MalformedURLException malformedException) {
                LOG.error("Error processing input file:" + name + " cannot be converted to URL " + name,
                        malformedException);
            }
        } else {

            URL fileURL = CommandLineParser.class.getResource(name);
            if (fileURL == null) {
                if (!name.startsWith("/")) {
                    fileURL = CommandLineParser.class.getResource("/" + name);
                }
            }

            if (fileURL == null) {
                fileURL = ClassLoader.getSystemClassLoader().getResource(name);
                if (fileURL == null) {
                    if (!name.startsWith("/")) {
                        fileURL = ClassLoader.getSystemClassLoader().getResource("/" + name);
                    }
                }
            }

            if (fileURL != null) {
                try {
                    in = fileURL.openStream();
                    ret = fileURL;
                } catch (Exception exception) {
                    LOG.error(name + " cannot be opened:", exception);
                }
            } else {
                LOG.warn("Error processing input file: URL not found for " + name
                        + " or no privilege for reading file " + name);
            }
        }
    }
    if (in != null) {
        try {
            in.close();
        } catch (Exception e) {
            // Ignore
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== getResourceFileURL(" + name + ", URL=" + ret + ")");
    }
    return ret;
}