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.ts.db.connector.ConnectorDriverManager.java

static Driver getDriver(String url, String driverClassName, String classpath) throws SQLException {
    assert !StringUtils.isBlank(url);
    final boolean hasClasspath = !StringUtils.isBlank(classpath);
    if (!hasClasspath) {
        for (Driver driver : new ArrayList<Driver>(drivers)) {
            if (driver.acceptsURL(url)) {
                return driver;
            }/*ww w. j  a  va2s  .c  o m*/
        }
    }
    List<File> jars = new ArrayList<File>();
    ClassLoader cl;
    if (hasClasspath) {
        List<URL> urls = new ArrayList<URL>();
        for (String path : classpath.split(pathSeparator)) {
            final File file = new File(path);
            if (isJarFile(file)) {
                jars.add(file);
            }
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    } else {
        jars.addAll(getJarFiles("."));
        jars.addAll(driverFiles);
        List<URL> urls = new ArrayList<URL>();
        for (File file : jars) {
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
    }
    driverFiles.addAll(jars);
    final boolean hasDriverClassName = !StringUtils.isBlank(driverClassName);
    if (hasDriverClassName) {
        try {
            Driver driver = DynamicLoader.newInstance(driverClassName, cl);
            assert driver != null;
            return driver;
        } catch (DynamicLoadingException ex) {
            Throwable cause = (ex.getCause() != ex) ? ex.getCause() : ex;
            SQLException exception = new SQLException(cause.toString());
            exception.initCause(cause);
            throw exception;
        }
    }
    final String jdbcDrivers = System.getProperty("jdbc.drivers");
    if (!StringUtils.isBlank(jdbcDrivers)) {
        for (String jdbcDriver : jdbcDrivers.split(":")) {
            try {
                Driver driver = DynamicLoader.newInstance(jdbcDriver, cl);
                if (driver != null) {
                    if (!hasClasspath) {
                        drivers.add(driver);
                    }
                    return driver;
                }
            } catch (DynamicLoadingException ex) {
                log.warn(ex.toString());
            }
        }
    }
    for (File jar : jars) {
        try {
            Driver driver = getDriver(jar, url, cl);
            if (driver != null) {
                if (!hasClasspath) {
                    drivers.add(driver);
                }
                return driver;
            }
        } catch (IOException ex) {
            log.warn(ex.toString());
        }
    }
    for (String path : System.getProperty("java.class.path", "").split(pathSeparator)) {
        if (isJarFile(path)) {
            Driver driver;
            try {
                driver = getDriver(new File(path), url, cl);
                if (driver != null) {
                    drivers.add(driver);
                    return driver;
                }
            } catch (IOException ex) {
                log.warn(ex.toString());
            }
        }
    }
    throw new SQLException("driver not found");
}

From source file:at.diamonddogs.data.adapter.parcelable.ParcelableAdapterWebRequest.java

/**
 * Required by Parcelable mechanism//w  w w. ja v a2s .c o  m
 * 
 * @param in
 *            the input parcel
 */
public ParcelableAdapterWebRequest(Parcel in) {
    super(in);
    if (dataObject == null) {
        dataObject = new WebRequest();
    }
    dataObject.setProcessorId(in.readInt());
    dataObject.setRequestType((Type) in.readSerializable());
    dataObject.setUrl((URL) in.readSerializable());
    dataObject.setReadTimeout(in.readInt());
    dataObject.setConnectionTimeout(in.readInt());
    dataObject.setFollowRedirects(in.readInt() == 1);

    boolean first = (in.readInt() == 1);
    if (first) {
        ParcelableAdapterTempFile tmp = in.readParcelable(ClassLoader.getSystemClassLoader());
        dataObject.setTmpFile(new Pair<Boolean, TempFile>(first, tmp.getDataObject()));
    }

    dataObject.setHeader(readStringMap(in));
    dataObject.setCacheTime(in.readLong());
    dataObject.setNumberOfRetries(in.readInt());
    dataObject.setRetryInterval(in.readInt());

    dataObject.setCancelled(in.readInt() == 1);
    dataObject.setCheckConnectivity(in.readInt() == 1);
    dataObject.setCheckConnectivityPing(in.readInt() == 1);
    dataObject.setUseOfflineCache(in.readInt() == 1);

}

From source file:com.ifunshow.dbc.util.DBHelper.java

public static URLClassLoader decideDriverLoader(String dbType, String dbVersion) throws MalformedURLException {
    URL[] urls = null;/*from w  w w.  ja va 2s.com*/
    JarUtil ju = new JarUtil(JarUtil.class);
    String jarPath = ju.getJarPath() + File.separator + "jdbcjar" + File.separator;
    System.out.println("jarPath==>" + jarPath);
    if ("oracle".equalsIgnoreCase(StringUtils.trim(dbType))) {
        urls = new URL[1];
        if ("8".equalsIgnoreCase(dbVersion)) {
            urls[0] = new File(jarPath + "oracle_classes12.jar").toURL();
        } else {
            urls[0] = new File(jarPath + "oracle_ojdbc6.jar").toURL();
        }
    } else if ("teradata".equalsIgnoreCase(StringUtils.trim(dbType))) {
        urls = new URL[2];
        urls[0] = new File(jarPath + "teradata_tdgssconfig.jar").toURL();
        urls[1] = new File(jarPath + "teradata_terajdbc4.jar").toURL();
    } else if ("db2".equalsIgnoreCase(StringUtils.trim(dbType))) {
        urls = new URL[2];
        if ("8".equalsIgnoreCase(dbVersion)) {
            urls[0] = new File(jarPath + "db2_db2jcc-v8.jar").toURL();
            urls[1] = new File(jarPath + "db2_db2jcc_license_cu-v8.jar").toURL();
        } else {
            urls[0] = new File(jarPath + "db2_db2jcc-v9.7.jar").toURL();
            urls[1] = new File(jarPath + "db2_db2jcc_license_cu-v9.7.jar").toURL();
        }
    } else if ("mysql".equalsIgnoreCase(StringUtils.trim(dbType))) {
        urls = new URL[1];
        urls[0] = new File(jarPath + "mysql_connector_5.1.15_bin.jar").toURL();
    }
    return new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
}

From source file:org.jsweet.JSweetConfig.java

/**
 * Initialize the classpath to include tools.jar.
 * //w w w. j a va2  s  .  c o  m
 * @param jdkHome
 *            the jdkHome option value (if not set or not found, fall back
 *            to the JAVA_HOME environment variable)
 * @param handler
 *            the transpilation handler that should report an error if
 *            tools.jar is not found (if null uses the default logger)
 */
public static void initClassPath(String jdkHome) {
    try {
        URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        boolean found = false;
        for (URL url : urlClassLoader.getURLs()) {
            if (url.getPath().endsWith("/tools.jar") || url.getPath().endsWith("/Classes/classes.jar")) {
                found = true;
                logger.debug("tools.jar already in classpath");
                break;
            }
        }
        if (!found) {
            logger.debug("adding tools.jar in classpath");
            File toolsLib = null;
            if (!StringUtils.isBlank(jdkHome)) {
                logger.debug("lookup in " + jdkHome);
                toolsLib = new File(jdkHome, "lib/tools.jar");
                if (!toolsLib.exists()) {
                    // we may be pointing to the JDK's jre
                    toolsLib = new File(jdkHome, "../lib/tools.jar");
                }
                // for Mac
                if (!toolsLib.exists()) {
                    toolsLib = new File(jdkHome, "/Classes/classes.jar");
                }
                if (!toolsLib.exists()) {
                    toolsLib = new File(jdkHome, "../Classes/classes.jar");
                }
            }
            if (toolsLib == null || !toolsLib.exists()) {
                logger.debug("lookup in JAVA_HOME=" + System.getenv("JAVA_HOME"));
                toolsLib = new File(System.getenv("JAVA_HOME"), "lib/tools.jar");
                if (!toolsLib.exists()) {
                    // we may be pointing to the JDK's jre
                    toolsLib = new File(System.getenv("JAVA_HOME"), "../lib/tools.jar");
                }
                // for Mac
                if (!toolsLib.exists()) {
                    toolsLib = new File(System.getenv("JAVA_HOME"), "/Classes/classes.jar");
                }
                if (!toolsLib.exists()) {
                    toolsLib = new File(System.getenv("JAVA_HOME"), "../Classes/classes.jar");
                }
            }
            if (!toolsLib.exists()) {
                return;
            }

            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(urlClassLoader, toolsLib.toURI().toURL());
            logger.debug("updated classpath with: " + toolsLib);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

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

public static StackManager createTestStackManager() throws Exception {
    String stack = ClassLoader.getSystemClassLoader().getResource("stacks").getPath();
    return createTestStackManager(stack);
}

From source file:de.tudarmstadt.lt.ltbot.postprocessor.DecesiveValuePerplexityTest.java

private void setupPriorityPostProcessor() throws Exception {
    // declare variables
    File src_dir = new File(ClassLoader.getSystemClassLoader().getResource("testlm").getPath());
    int lm_order = 5;

    // setup test languagemodelserver
    setup_LM_Server(src_dir, lm_order);//  ww  w.  j a v a2  s .  c o  m

    // setup priority post processor
    _prio = new DecesiveValueProducerPerplexity();
    _prio.setRmihost(_host);
    _prio.setRmiport(_rmiport);
    _prio.setServiceID(_serviceId);
    _prio.getTextExtractor().setUtf8Cleaner(new UTF8CleanerExt());
    _prio.setCrawlController(new CrawlController());
    _prio.setSentenceMaker(new SentenceMaker());
    _prio.start();
}

From source file:org.castor.jaxb.CastorJAXBContextFactoryTest.java

/**
 * Tests the {@link CastorJAXBContextFactory#createContext(String, ClassLoader, java.util.Map)}
 * method when contextPath is null./*from  ww  w .j  ava 2  s .c  o  m*/
 * <p/>
 * {@link IllegalArgumentException} is expected.
 *
 * @throws Exception
 *             if any error occurs during test
 */
@Test(expected = IllegalArgumentException.class)
public void testCreateContextContextPathNull1() throws Exception {

    CastorJAXBContextFactory.createContext(null, ClassLoader.getSystemClassLoader(),
            new HashMap<String, Object>());
}

From source file:com.varaneckas.hawkscope.util.IOUtils.java

public static synchronized boolean copyFile(final String in, final String out) {
    try {// w  w  w. ja  v  a  2  s .  co  m
        File outFile = new File(out);
        if (!outFile.exists()) {
            if (!outFile.createNewFile()) {
                return false;
            }
        }
        return copyFile(ClassLoader.getSystemClassLoader().getResourceAsStream(in),
                new FileOutputStream(outFile));
    } catch (final Exception e) {
        log.debug("Failed copying file: " + in + " -> " + out, e);
        return false;
    }
}

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

/**
 * Returns the specified resource by checking the current thread's
 * {@link Thread#getContextClassLoader() context class loader}, then the
 * current ClassLoader (<code>ClassUtils.class.getClassLoader()</code>), then the system/application
 * ClassLoader (<code>ClassLoader.getSystemClassLoader()</code>, in that order, using
 * {@link ClassLoader#getResourceAsStream(String) getResourceAsStream(name)}.
 *
 * @param name the name of the resource to acquire from the classloader(s).
 * @return the InputStream of the resource found, or <code>null</code> if the resource cannot be found from any
 *         of the three mentioned ClassLoaders.
 * @since 0.9/*from   w  ww. jav a  2s.c  om*/
 */
public static InputStream getResourceAsStream(String name) {
    InputStream is = null;
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl != null) {
        is = cl.getResourceAsStream(name);
    }

    if (is == null) {
        if (log.isTraceEnabled()) {
            log.trace("Resource [" + name + "] was not found via the thread context ClassLoader.  Trying the "
                    + "current ClassLoader...");
        }
        cl = ClassUtils.class.getClassLoader();
        is = cl.getResourceAsStream(name);
        if (is == null) {
            if (log.isTraceEnabled()) {
                log.trace("Resource [" + name + "] was not found via the current class loader.  Trying the "
                        + "system/application ClassLoader...");
            }
            cl = ClassLoader.getSystemClassLoader();
            is = cl.getResourceAsStream(name);
            if (is == null && log.isTraceEnabled()) {
                log.trace("Resource [" + name + "] was not found via the thread context, current, or "
                        + "system/application ClassLoaders.  All heuristics have been exhausted.  Returning null.");
            }
        }
    }
    return is;
}

From source file:com.networknt.info.ServerInfoDisabledTest.java

static void addURL(URL url) throws Exception {
    URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class clazz = URLClassLoader.class;
    // Use reflection
    Method method = clazz.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);//from  w  w w.j  av  a 2s  .  co m
    method.invoke(classLoader, url);
}