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:nl.b3p.catalog.arcgis.ArcObjectsLinker.java

public static void link(String arcObjectsHome) throws Exception {

    if (arcObjectsHome == null) {
        for (String s : homeEnvVars) {
            arcObjectsHome = System.getenv(s);
            if (arcObjectsHome != null) {
                log.info("Using environment variable " + s + " to find ArcObjects");
                break;
            }//from w w  w.j  av  a 2s.co  m
        }
    }
    if (arcObjectsHome == null) {
        throw new Exception("Could not find ArcObjects home in environment variables " + homeEnvVars + ". "
                + (System.getProperty("os.name").toLowerCase().indexOf("win") > -1
                        ? "ArcGIS Engine Runtime or ArcGIS Desktop must be installed"
                        : "ArcGIS Engine Runtime must be installed"));
    }

    // The directory can be set to a JAR itself, the directory arcobjects.jar
    // is in, or (as in the environment variables) the path with "java/lib" 
    // subdirectories with arcobjects.jar in it (some reports ArcGIS Server
    // 10.1 not having these java/lib subdirs).

    File jarFile = null;

    if (arcObjectsHome.endsWith(".jar")) {
        jarFile = new File(arcObjectsHome);
        if (jarFile.exists()) {
            log.info(String.format("Using full path to ArcObjects JAR file: %s", jarFile.getAbsolutePath()));
        } else {
            jarFile = null;
        }
    }

    if (jarFile == null) {
        String jarPath = arcObjectsHome + File.separator + "arcobjects.jar";
        jarFile = new File(jarPath);

        if (jarFile.exists()) {
            log.info(String.format("Using arcobjects.jar found in directory: %s", jarFile.getAbsolutePath()));
        } else {
            jarFile = null;
        }
    }

    if (jarFile == null) {
        String jarPath = arcObjectsHome + File.separator + "java" + File.separator + "lib" + File.separator
                + "arcobjects.jar";
        jarFile = new File(jarPath);

        if (!jarFile.exists()) {
            throw new Exception(
                    "Error: could not find arcobjects.jar at path \"" + jarFile.getAbsolutePath() + "\"");
        } else {
            log.info(String.format("Using ArcObjects home \"%s\"", arcObjectsHome));
        }
    }

    // Deze hack is afkomstig van ESRI voorbeelden...

    // Helps load classes and resources from a search path of URLs
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { jarFile.toURI().toURL() });
    } catch (Throwable throwable) {
        throw new Exception("Could not add arcobjects.jar to system classloader", throwable);
    }
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloReloadingVFSClassLoaderTest.java

@Test
public void testReloading() throws Exception {
    FileObject testDir = vfs.resolveFile(folder1.getRoot().toURI().toString());
    FileObject[] dirContents = testDir.getChildren();

    AccumuloReloadingVFSClassLoader arvcl = new AccumuloReloadingVFSClassLoader(folderPath, vfs,
            new ReloadingClassLoader() {
                @Override//  w ww.j av  a 2 s  . c  o  m
                public ClassLoader getClassLoader() {
                    return ClassLoader.getSystemClassLoader();
                }
            }, 1000, true);

    FileObject[] files = ((VFSClassLoader) arvcl.getClassLoader()).getFileObjects();
    Assert.assertArrayEquals(createFileSystems(dirContents), files);

    Class<?> clazz1 = arvcl.getClassLoader().loadClass("test.HelloWorld");
    Object o1 = clazz1.newInstance();
    Assert.assertEquals("Hello World!", o1.toString());

    // Check that the class is the same before the update
    Class<?> clazz1_5 = arvcl.getClassLoader().loadClass("test.HelloWorld");
    Assert.assertEquals(clazz1, clazz1_5);

    assertTrue(new File(folder1.getRoot(), "HelloWorld.jar").delete());

    // VFS-487 significantly wait to avoid failure
    Thread.sleep(7000);

    // Update the class
    FileUtils.copyURLToFile(this.getClass().getResource("/HelloWorld.jar"), folder1.newFile("HelloWorld2.jar"));

    // Wait for the monitor to notice
    // VFS-487 significantly wait to avoid failure
    Thread.sleep(7000);

    Class<?> clazz2 = arvcl.getClassLoader().loadClass("test.HelloWorld");
    Object o2 = clazz2.newInstance();
    Assert.assertEquals("Hello World!", o2.toString());

    // This is false because they are loaded by a different classloader
    Assert.assertFalse(clazz1.equals(clazz2));
    Assert.assertFalse(o1.equals(o2));

    arvcl.close();
}

From source file:org.ireland.jnetty.loader.WebAppClassLoader.java

/**
 * Constructor.//from   w  w  w . j av a  2 s  . c  om
 */
public WebAppClassLoader(ClassLoader parent) throws IOException {
    super(new URL[] {},
            parent != null ? parent
                    : (Thread.currentThread().getContextClassLoader() != null
                            ? Thread.currentThread().getContextClassLoader()
                            : (WebAppClassLoader.class.getClassLoader() != null
                                    ? WebAppClassLoader.class.getClassLoader()
                                    : ClassLoader.getSystemClassLoader())));

    _parent = getParent();

    if (_parent == null)
        throw new IllegalArgumentException("no parent classloader!");
}

From source file:org.apache.james.mailets.TemporaryFilesystemModule.java

private void copyResource(Path resourcesFolder, String resourceName) {
    try (OutputStream outputStream = new FileOutputStream(resourcesFolder.resolve(resourceName).toFile())) {
        IOUtils.copy(ClassLoader.getSystemClassLoader().getResource(resourceName).openStream(), outputStream);
    } catch (IOException e) {
        Throwables.propagate(e);//w  w  w  .  j  a  v  a 2  s.c om
    }
}

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

/**
 * Tests the {@link CastorJAXBContextFactory#createContext(String, ClassLoader, java.util.Map)}
 * method when contextPath is empty.// w  w  w . j a v a2s . c o  m
 * <p/>
 * {@link IllegalArgumentException} is expected.
 *
 * @throws Exception
 *             if any error occurs during test
 */
@Test(expected = IllegalArgumentException.class)
public void testCreateContextContextPathEmpty() throws Exception {

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

From source file:org.apache.hadoop.hbase.ClassFinder.java

/**
 * Finds the classes in a package and nested packages.
 * @param packageName package names/* ww w  .  j av a 2 s. co m*/
 * @param proceedOnExceptions whether to ignore exceptions encountered for
 *        individual jars/files/classes, and proceed looking for others.
 */
public Set<Class<?>> findClasses(String packageName, boolean proceedOnExceptions)
        throws ClassNotFoundException, IOException, LinkageError {
    final String path = packageName.replace('.', '/');
    final Pattern jarResourceRe = Pattern.compile("^file:(.+\\.jar)!/" + path + "$");

    Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(path);
    List<File> dirs = new ArrayList<File>();
    List<String> jars = new ArrayList<String>();

    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        String resourcePath = resource.getFile();
        Matcher matcher = jarResourceRe.matcher(resourcePath);
        boolean isJar = matcher.find();
        resourcePath = isJar ? matcher.group(1) : resourcePath;
        if (null == this.resourcePathFilter || this.resourcePathFilter.isCandidatePath(resourcePath, isJar)) {
            LOG.debug("Will look for classes in " + resourcePath);
            if (isJar) {
                jars.add(resourcePath);
            } else {
                dirs.add(new File(resourcePath));
            }
        }
    }

    Set<Class<?>> classes = new HashSet<Class<?>>();
    for (File directory : dirs) {
        classes.addAll(findClassesFromFiles(directory, packageName, proceedOnExceptions));
    }
    for (String jarFileName : jars) {
        classes.addAll(findClassesFromJar(jarFileName, packageName, proceedOnExceptions));
    }
    return classes;
}

From source file:org.obm.sync.push.client.SSLContextFactoryTest.java

@Test
public void testCorrectSSLContextFactoryCall() {
    InputStream pkcs12Stream = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_pwd_toto.p12");
    char[] pkcs12Password = "toto".toCharArray();

    SSLContext sslContext = SSLContextFactory.create(pkcs12Stream, pkcs12Password);

    assertThat(sslContext).isNotNull();/*w  w  w .ja  va 2  s. c  om*/
}

From source file:gov.nih.nci.cacis.sa.mirthconnect.SemanticAdapter.java

private String getCaCISRequestxml(final CaCISRequest parameter) {

    return AccessController.doPrivileged(new PrivilegedAction<String>() {

        public String run() {
            try {
                final CaCISURLClassLoader cl = new CaCISURLClassLoader(customLibDir,
                        ClassLoader.getSystemClassLoader());
                final Class jmClass = Class.forName("gov.nih.nci.cacis.sa.mirthconnect.JAXBMarshaller", true,
                        cl);//from   w  ww .  j a  v a 2 s. c  o m
                final Method m = jmClass.getMethod("marshal", Object.class);
                return (String) m.invoke(jmClass.newInstance(), parameter);
                // CHECKSTYLE:OFF
            } catch (Exception ex) {
                // CHECKSTYLE:ON
                LOG.error("Error marshalling CaCISRequest!", ex);
                return null;
            }
        }
    });

}

From source file:org.obm.provisioning.ldap.client.EmbeddedLdapModule.java

private String createOpenDJTemporaryEnvironment() throws IOException {
    File tmpFolder = mainTemporaryFolder();
    String tmpFolderPath = tmpFolder.getAbsolutePath() + "/";

    File resourcesFolder = new File(ClassLoader.getSystemClassLoader().getResource(OPENDJ_FOLDER).getPath());
    FileUtils.copyDirectory(resourcesFolder, tmpFolder);
    mkFolder(tmpFolderPath, "locks");
    mkFolder(tmpFolderPath, "logs");

    return tmpFolderPath;
}

From source file:org.apache.drill.jdbc.ITTestShadedJar.java

@Test
public void executeJdbcAllQuery() throws Exception {

    // print class path for debugging
    System.out.println("java.class.path:");
    System.out.println(System.getProperty("java.class.path"));

    final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);/* w w  w .j  av  a2  s .c om*/
    method.invoke(loader, getJdbcUrl());

    Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
    try {
        Driver driver = (Driver) clazz.newInstance();
        try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) {
            String path = Paths.get("").toAbsolutePath().toString() + "/src/test/resources/types.json";
            printQuery(c, "select * from dfs.`" + path + "`");
        }
    } catch (Exception ex) {
        throw ex;
    }

}