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.avego.oauth.migration.OauthDataMigrator.java

/**
 * This creates a OauthDataMigrator using the give params, it automatically
 * creates a deserialisation class loader used to deserialize existing oauth data and creates a migration dao using
 * the given parameters/*www. j  av a2s. c  o m*/
 * @param params The parameters used to create the migration dao
 * @throws FileNotFoundException If the oldlib dir was not found relative to the current dir or in currentdir/target/oldlib
 * @throws DaoCreationException If the oauth migration dao could not be created from the given parameters
 */
public OauthDataMigrator(Map<String, Object> params) throws FileNotFoundException, DaoCreationException {
    this.dao = OauthMigrationDaoFactory.newInstance(params);
    // find where to source the old jars from
    File oldLibDir = new File("oldlib");
    if (!oldLibDir.exists()) {
        oldLibDir = new File("target/oldlib");
    }
    if (!oldLibDir.exists()) {
        throw new FileNotFoundException(
                "Could not find the lib dir either in the current dir or in target dir");
    }

    // the system class loader includes jars on the class path, however this also would include
    // the new versions of the spring classes which we do not want, so we use the
    // Parent of the system class loader which is the ext class loader/ e..g includes bootstrap java classes
    this.deserialisationClassLoader = ClassLoaderUtils.createClassLoaderWithJars(oldLibDir.getAbsolutePath(),
            ClassLoader.getSystemClassLoader().getParent());
    if (params != null) {
        Boolean val = (Boolean) params.get(REMOVE_REFRESH_TOKENS_PARAM);
        if (val != null) {
            this.removeRefreshTokens = val.booleanValue();
        }
        val = (Boolean) params.get(SERIALIZE_NEW_TOKEN_VALUES_PARAM);
        if (val != null) {
            this.serializeNewTokenValues = val.booleanValue();
        }
    }
}

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

@Test
@Ignore// ww  w  .j  a va2s .  c o  m
public void testModifiedClass() throws Exception {

    FileObject testDir = vfs.resolveFile(folder1.getRoot().toURI().toString());
    FileObject[] dirContents = testDir.getChildren();

    AccumuloReloadingVFSClassLoader arvcl = new AccumuloReloadingVFSClassLoader(folderPath, vfs,
            new ReloadingClassLoader() {
                @Override
                public ClassLoader getClassLoader() {
                    return ClassLoader.getSystemClassLoader();
                }
            }, 1000, true);

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

    ClassLoader loader1 = arvcl.getClassLoader();
    Class<?> clazz1 = loader1.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);

    // java does aggressive caching of jar files. When using java code to read jar files that are created in the same second, it will only see the first jar
    // file
    Thread.sleep(1000);

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

    // Update the class
    FileUtils.copyURLToFile(this.getClass().getResource("/HelloWorld2.jar"), folder1.newFile("HelloWorld.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("Hallo Welt", o2.toString());

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

    Class<?> clazz3 = loader1.loadClass("test.HelloWorld");
    Object o3 = clazz3.newInstance();
    Assert.assertEquals("Hello World!", o3.toString());

    arvcl.close();
}

From source file:com.twosigma.beaker.groovy.evaluator.GroovyEvaluator.java

protected ClassLoader newClassLoader() throws MalformedURLException {
    loader = new DynamicClassLoaderSimple(ClassLoader.getSystemClassLoader());
    loader.addJars(classPath);//from www .  j  a v  a 2  s.c  o  m
    loader.addDynamicDir(outDir);
    return loader;
}

From source file:org.apache.tez.client.TestTezClientUtils.java

/**
 * /*w  w  w. java2  s  .  co  m*/
 * @throws Exception
 */
@Test(timeout = 5000)
public void validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnored() throws Exception {
    URL[] cp = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
    StringBuffer buffer = new StringBuffer();
    for (URL url : cp) {
        buffer.append(url.toExternalForm());
        buffer.append(",");
    }
    TezConfiguration conf = new TezConfiguration();
    conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString());
    conf.setBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, true);
    Credentials credentials = new Credentials();
    Map<String, LocalResource> localizedMap = new HashMap<String, LocalResource>();
    Assert.assertFalse(TezClientUtils.setupTezJarsLocalResources(conf, credentials, localizedMap));
    assertTrue(localizedMap.isEmpty());
}

From source file:org.apache.spark.tez.utils.HadoopUtils.java

/**
 * //from  ww w  . j a  va2 s.c om
 */
private static boolean generateConfigJarFromHadoopConfDir(FileSystem fs, String applicationName,
        List<Path> provisionedPaths, List<File> generatedJars) {
    boolean generated = false;
    String hadoopConfDir = System.getenv().get("HADOOP_CONF_DIR");
    if (hadoopConfDir != null && hadoopConfDir.trim().length() > 0) {
        String jarFileName = ClassPathUtils.generateJarFileName("conf_");
        File confDir = new File(hadoopConfDir.trim());
        File jarFile = doGenerateJar(confDir, jarFileName, generatedJars, "configuration (HADOOP_CONF_DIR)");
        String destinationFilePath = applicationName + "/" + jarFile.getName();
        Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath);
        provisioinResourceToFs(fs, new Path(jarFile.getAbsolutePath()), provisionedPath);
        provisionedPaths.add(provisionedPath);
        generated = true;
    }

    String tezConfDir = System.getenv().get("TEZ_CONF_DIR");
    if (tezConfDir != null && tezConfDir.trim().length() > 0) {
        String jarFileName = ClassPathUtils.generateJarFileName("conf_tez");
        File confDir = new File(tezConfDir.trim());
        File jarFile = doGenerateJar(confDir, jarFileName, generatedJars, "configuration (TEZ_CONF_DIR)");

        try {
            URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
            Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            m.setAccessible(true);
            m.invoke(cl, jarFile.toURI().toURL());
        } catch (Exception e) {
            e.printStackTrace();
        }

        String destinationFilePath = applicationName + "/" + jarFile.getName();
        Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath);
        provisioinResourceToFs(fs, new Path(jarFile.getAbsolutePath()), provisionedPath);
        provisionedPaths.add(provisionedPath);
        generated = true;
    }
    return generated;
}

From source file:org.seqdoop.hadoop_bam.TestVCFOutputFormat.java

private VCFHeader readHeader() throws IOException {
    String header_file = ClassLoader.getSystemClassLoader().getResource("test.vcf").getFile();
    VCFHeader header = VCFHeaderReader.readHeaderFrom(new SeekableFileStream(new File(header_file)));
    return header;
}

From source file:org.apache.cayenne.wocompat.EOModelHelper.java

/**
 * Performs Objective C data types conversion to Java types.
 * //from w ww  .j  a va2s . co  m
 * @since 1.1
 * @return String representation for Java type corresponding to String
 *         representation of Objective C type.
 */
public String javaTypeForEOModelerType(String valueClassName, String valueType) {
    if (valueClassName == null) {
        return null;
    }

    if (valueClassName.equals("NSString")) {
        return String.class.getName();
    }

    if (valueClassName.equals("NSNumber")) {
        Class numericClass = numericAttributeClass(valueType);
        return (numericClass != null) ? numericClass.getName() : Number.class.getName();
    }

    if (valueClassName.equals("NSCalendarDate"))
        return "java.sql.Timestamp";

    if (valueClassName.equals("NSDecimalNumber")) {
        Class numericClass = numericAttributeClass(valueType);
        return (numericClass != null) ? numericClass.getName() : BigDecimal.class.getName();
    }

    if (valueClassName.equals("NSData"))
        return "byte[]";

    // don't know what the class is mapped to...
    // do some minimum sanity check and use as is
    try {
        return Class.forName(valueClassName).getName();
    } catch (ClassNotFoundException aClassNotFoundException) {
        try {
            return Class.forName("java.lang." + valueClassName).getName();
        } catch (ClassNotFoundException anotherClassNotFoundException) {
            try {
                return Class.forName("java.util." + valueClassName).getName();
            } catch (ClassNotFoundException yetAnotherClassNotFoundException) {
                try {
                    return ClassLoader.getSystemClassLoader().loadClass(valueClassName).getName();
                } catch (ClassNotFoundException e) {
                    // likely a custom class
                    return valueClassName;
                }
            }
        }
    }
}

From source file:org.apache.ambari.server.api.services.AmbariMetaInfoTest.java

@Before
public void before() throws Exception {
    File stacks = new File("src/test/resources/stacks");
    File version = new File("src/test/resources/version");
    if (System.getProperty("os.name").contains("Windows")) {
        stacks = new File(ClassLoader.getSystemClassLoader().getResource("stacks").getPath());
        version = new File(new File(ClassLoader.getSystemClassLoader().getResource("").getPath()).getParent(),
                "version");
    }//from ww  w.ja  v a  2 s.c  om
    metaInfo = createAmbariMetaInfo(stacks, version, true);
}

From source file:org.apache.pulsar.functions.runtime.JavaInstanceMain.java

public void start() throws Exception {
    InstanceConfig instanceConfig = new InstanceConfig();
    instanceConfig.setFunctionId(functionId);
    instanceConfig.setFunctionVersion(functionVersion);
    instanceConfig.setInstanceId(instanceId);
    instanceConfig.setMaxBufferedTuples(maxBufferedTuples);
    instanceConfig.setClusterName(clusterName);
    FunctionDetails.Builder functionDetailsBuilder = FunctionDetails.newBuilder();
    if (functionDetailsJsonString.charAt(0) == '\'') {
        functionDetailsJsonString = functionDetailsJsonString.substring(1);
    }/*from   w  ww. ja  v  a2  s. c  o  m*/
    if (functionDetailsJsonString.charAt(functionDetailsJsonString.length() - 1) == '\'') {
        functionDetailsJsonString = functionDetailsJsonString.substring(0,
                functionDetailsJsonString.length() - 1);
    }
    JsonFormat.parser().merge(functionDetailsJsonString, functionDetailsBuilder);
    FunctionDetails functionDetails = functionDetailsBuilder.build();
    instanceConfig.setFunctionDetails(functionDetails);
    instanceConfig.setPort(port);

    Map<String, String> secretsProviderConfigMap = null;
    if (!StringUtils.isEmpty(secretsProviderConfig)) {
        if (secretsProviderConfig.charAt(0) == '\'') {
            secretsProviderConfig = secretsProviderConfig.substring(1);
        }
        if (secretsProviderConfig.charAt(secretsProviderConfig.length() - 1) == '\'') {
            secretsProviderConfig = secretsProviderConfig.substring(0, secretsProviderConfig.length() - 1);
        }
        Type type = new TypeToken<Map<String, String>>() {
        }.getType();
        secretsProviderConfigMap = new Gson().fromJson(secretsProviderConfig, type);
    }

    if (StringUtils.isEmpty(secretsProviderClassName)) {
        secretsProviderClassName = ClearTextSecretsProvider.class.getName();
    }

    SecretsProvider secretsProvider;
    try {
        secretsProvider = (SecretsProvider) Reflections.createInstance(secretsProviderClassName,
                ClassLoader.getSystemClassLoader());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    secretsProvider.init(secretsProviderConfigMap);

    // Collector Registry for prometheus metrics
    CollectorRegistry collectorRegistry = new CollectorRegistry();

    containerFactory = new ThreadRuntimeFactory("LocalRunnerThreadGroup", pulsarServiceUrl,
            stateStorageServiceUrl,
            AuthenticationConfig.builder().clientAuthenticationPlugin(clientAuthenticationPlugin)
                    .clientAuthenticationParameters(clientAuthenticationParameters).useTls(isTrue(useTls))
                    .tlsAllowInsecureConnection(isTrue(tlsAllowInsecureConnection))
                    .tlsHostnameVerificationEnable(isTrue(tlsHostNameVerificationEnabled))
                    .tlsTrustCertsFilePath(tlsTrustCertFilePath).build(),
            secretsProvider, collectorRegistry);
    runtimeSpawner = new RuntimeSpawner(instanceConfig, jarFile, null, // we really dont use this in thread container
            containerFactory, expectedHealthCheckInterval * 1000);

    server = ServerBuilder.forPort(port).addService(new InstanceControlImpl(runtimeSpawner)).build().start();
    log.info("JaveInstance Server started, listening on " + port);
    java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            try {
                close();
            } catch (Exception ex) {
                System.err.println(ex);
            }
        }
    });

    log.info("Starting runtimeSpawner");
    runtimeSpawner.start();

    // starting metrics server
    log.info("Starting metrics server on port {}", metrics_port);
    metricsServer = new HTTPServer(new InetSocketAddress(metrics_port), collectorRegistry, true);

    if (expectedHealthCheckInterval > 0) {
        healthCheckTimer = InstanceCache.getInstanceCache().getScheduledExecutorService()
                .scheduleAtFixedRate(() -> {
                    try {
                        if (System.currentTimeMillis() - lastHealthCheckTs > 3 * expectedHealthCheckInterval
                                * 1000) {
                            log.info(
                                    "Haven't received health check from spawner in a while. Stopping instance...");
                            close();
                        }
                    } catch (Exception e) {
                        log.error("Error occurred when checking for latest health check", e);
                    }
                }, expectedHealthCheckInterval * 1000, expectedHealthCheckInterval * 1000,
                        TimeUnit.MILLISECONDS);
    }

    runtimeSpawner.join();
    log.info("RuntimeSpawner quit, shutting down JavaInstance");
    close();
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Loads up a resource from the classpath as a byte array.
 * @param path path of resource//from ww  w  .  ja v a 2 s.  c o m
 * @return contents of resource
 * @throws IOException if any IO error occurs
 * @throws IllegalArgumentException if {@code path} cannot be found
 */
public static byte[] getResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);
    try (InputStream in = url.openStream()) {
        return IOUtils.toByteArray(in);
    }
}