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:net.volcore.wtvcache.WTVCache.java

/** should be called once in the beginning, sets up all the required logging. */
protected static void initializeLogging() {
    // Initialize logging
    String name = "wtvcache-log4j.properties";
    URL log4jfile = ClassLoader.getSystemClassLoader().getResource(name);
    if (log4jfile == null)
        throw new Error("Could not find " + name + "!");
    org.apache.log4j.PropertyConfigurator.configure(log4jfile);
}

From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

@Override
protected void startUp() throws Exception {

    sparkHConf = new Configuration(hConf);

    // Create a classloader that have the context/system classloader as parent and the program classloader as child
    final ClassLoader classLoader = new CombineClassLoader(
            Objects.firstNonNull(Thread.currentThread().getContextClassLoader(),
                    ClassLoader.getSystemClassLoader()),
            ImmutableList.of(context.getProgram().getClassLoader()));

    sparkHConf.setClassLoader(classLoader);

    // additional spark job initialization at run-time
    beforeSubmit();/*from  w  w w  .  j  a  v  a 2  s .co  m*/

    try {
        Location programJarCopy = copyProgramJar(programJarLocation, context);
        try {
            // We remember tx, so that we can re-use it in Spark tasks
            Transaction tx = txClient.startLong();
            try {
                SparkContextConfig.set(sparkHConf, context, cConf, tx, programJarCopy);
                Location dependencyJar = buildDependencyJar(context, SparkContextConfig.getHConf());
                try {
                    sparkSubmitArgs = prepareSparkSubmitArgs(sparkSpecification, sparkHConf, programJarCopy,
                            dependencyJar);
                    LOG.info("Submitting Spark program: {} with arguments {}", context,
                            Arrays.toString(sparkSubmitArgs));
                    this.transaction = tx;
                    this.cleanupTask = createCleanupTask(dependencyJar, programJarCopy);
                } catch (Throwable t) {
                    Locations.deleteQuietly(dependencyJar);
                    throw Throwables.propagate(t);
                }
            } catch (Throwable t) {
                Transactions.invalidateQuietly(txClient, tx);
                throw Throwables.propagate(t);
            }
        } catch (Throwable t) {
            Locations.deleteQuietly(programJarCopy);
            throw Throwables.propagate(t);
        }
    } catch (Throwable t) {
        LOG.error("Exception while preparing for submitting Spark Job: {}", context, t);
        throw Throwables.propagate(t);
    }
}

From source file:com.tc.config.schema.setup.StandardXMLFileConfigurationCreator.java

@Override
public void createConfiguration() throws ConfigurationSetupException {
    this.createConfiguration(ClassLoader.getSystemClassLoader());
}

From source file:com.jkoolcloud.tnt4j.streams.utils.ZorkaAttach.java

/**
 * Loads required classpath entries to running JVM.
 * //from w  w w . ja v  a  2s  . c  om
 * @param classPathEntriesURL
 *            classpath entries URLs to attach to JVM
 * @throws Exception
 *             if exception occurs while extending system class loader's classpath
 */
private static void extendClasspath(URL... classPathEntriesURL) throws Exception {
    URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    for (URL classPathEntryURL : classPathEntriesURL) {
        try {
            method.invoke(classLoader, classPathEntryURL);
        } catch (Exception e) {
            LOGGER.log(OpLevel.ERROR, StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME,
                    "ZorkaAttach.could.not.load"), classPathEntryURL, e);
        }
    }
}

From source file:com.epam.gepard.examples.gherkin.jbehave.FeatureFileFromJiraTicket.java

@Override
protected String getStoryPath() {
    Environment e = getTestClassExecutionData().getEnvironment();
    HtmlRunReporter htmlRunReporter = getTestClassExecutionData().getHtmlRunReporter();
    String fieldValue;//from w w  w .j a  v  a2s  .  c  om
    String featureFilename;
    try {
        //get feature info
        fieldValue = jiraSiteHandler.getTicketFieldValue(this, jiraTicket, "description");
        int startPos = fieldValue.indexOf("Feature:");
        int endPos = fieldValue.lastIndexOf("{noformat}");
        if (startPos < 0 || endPos <= 0) {
            throw new SimpleGepardException("Cannot identify feature part in ticket: " + jiraTicket);
        }
        fieldValue = fieldValue.substring(startPos, endPos);
        //save it to file
        String featureFullFilename = htmlRunReporter.formatPathName(new java.io.File(".").getCanonicalPath())
                + "/" + e.getProperty(Environment.GEPARD_HTML_RESULT_PATH) + "/"
                + getTestClassExecutionData().getHtmlRunReporter().getTestURL() + "." + jiraTicket + ".feature";
        featureFilename = featureFullFilename.substring(featureFullFilename.lastIndexOf("/") + 1);
        String featurePath = featureFullFilename.substring(0, featureFullFilename.lastIndexOf("/"));
        File file = new File(featureFullFilename);
        File path = new File(featurePath);
        fileUtil.writeToFile(fieldValue, file);
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(ClassLoader.getSystemClassLoader(), new Object[] { path.toURI().toURL() });
    } catch (JSONException | IOException ex) {
        throw new SimpleGepardException("Connect to JIRA failed.", ex);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        throw new SimpleGepardException("Transferring Feature info to JBehave failed.", ex);
    }
    return featureFilename;
}

From source file:org.apache.ranger.tagsync.process.TagSyncConfig.java

public static InputStream getFileInputStream(String path) throws FileNotFoundException {

    InputStream ret = null;//  w  w  w  .ja v a2s . co  m

    File f = new File(path);

    if (f.exists() && f.isFile() && f.canRead()) {
        ret = new FileInputStream(f);
    } else {
        ret = TagSyncConfig.class.getResourceAsStream(path);

        if (ret == null) {
            if (!path.startsWith("/")) {
                ret = TagSyncConfig.class.getResourceAsStream("/" + path);
            }
        }

        if (ret == null) {
            ret = ClassLoader.getSystemClassLoader().getResourceAsStream(path);
            if (ret == null) {
                if (!path.startsWith("/")) {
                    ret = ClassLoader.getSystemResourceAsStream("/" + path);
                }
            }
        }
    }

    return ret;
}

From source file:at.ac.tuwien.infosys.jcloudscale.server.JCloudScaleServer.java

@Override
public void close() {
    if (mq != null) {
        mq.close();// w  w w.  j av  a  2s. co m
        mq = null;
    }

    // closing classloaders.
    for (ClassLoader classLoader : cloudObjectToClassloaderMap.values())
        if (classLoader instanceof Closeable && !ClassLoader.getSystemClassLoader().equals(classLoader)) {
            try {
                ((Closeable) classLoader).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    cloudObjectToClassloaderMap.clear();
    runningRequests.clear();
    cloudObjects.clear();

    cleanupTask.close();

}

From source file:org.apache.pulsar.functions.worker.FunctionRuntimeManager.java

public FunctionRuntimeManager(WorkerConfig workerConfig, WorkerService workerService, Namespace dlogNamespace,
        MembershipManager membershipManager, ConnectorsManager connectorsManager,
        FunctionMetaDataManager functionMetaDataManager) throws Exception {
    this.workerConfig = workerConfig;
    this.workerService = workerService;
    this.functionAdmin = workerService.getFunctionAdmin();

    SecretsProviderConfigurator secretsProviderConfigurator;
    if (!StringUtils.isEmpty(workerConfig.getSecretsProviderConfiguratorClassName())) {
        secretsProviderConfigurator = (SecretsProviderConfigurator) Reflections.createInstance(
                workerConfig.getSecretsProviderConfiguratorClassName(), ClassLoader.getSystemClassLoader());
    } else {/*w  w  w  .  j av a2s.  co  m*/
        secretsProviderConfigurator = new DefaultSecretsProviderConfigurator();
    }
    secretsProviderConfigurator.init(workerConfig.getSecretsProviderConfiguratorConfig());

    AuthenticationConfig authConfig = AuthenticationConfig.builder()
            .clientAuthenticationPlugin(workerConfig.getClientAuthenticationPlugin())
            .clientAuthenticationParameters(workerConfig.getClientAuthenticationParameters())
            .tlsTrustCertsFilePath(workerConfig.getTlsTrustCertsFilePath()).useTls(workerConfig.isUseTls())
            .tlsAllowInsecureConnection(workerConfig.isTlsAllowInsecureConnection())
            .tlsHostnameVerificationEnable(workerConfig.isTlsHostnameVerificationEnable()).build();

    if (workerConfig.getThreadContainerFactory() != null) {
        this.runtimeFactory = new ThreadRuntimeFactory(
                workerConfig.getThreadContainerFactory().getThreadGroupName(),
                workerConfig.getPulsarServiceUrl(), workerConfig.getStateStorageServiceUrl(), authConfig,
                new ClearTextSecretsProvider(), null);
    } else if (workerConfig.getProcessContainerFactory() != null) {
        this.runtimeFactory = new ProcessRuntimeFactory(workerConfig.getPulsarServiceUrl(),
                workerConfig.getStateStorageServiceUrl(), authConfig,
                workerConfig.getProcessContainerFactory().getJavaInstanceJarLocation(),
                workerConfig.getProcessContainerFactory().getPythonInstanceLocation(),
                workerConfig.getProcessContainerFactory().getLogDirectory(),
                workerConfig.getProcessContainerFactory().getExtraFunctionDependenciesDir(),
                secretsProviderConfigurator);
    } else if (workerConfig.getKubernetesContainerFactory() != null) {
        this.runtimeFactory = new KubernetesRuntimeFactory(
                workerConfig.getKubernetesContainerFactory().getK8Uri(),
                workerConfig.getKubernetesContainerFactory().getJobNamespace(),
                workerConfig.getKubernetesContainerFactory().getPulsarDockerImageName(),
                workerConfig.getKubernetesContainerFactory().getImagePullPolicy(),
                workerConfig.getKubernetesContainerFactory().getPulsarRootDir(),
                workerConfig.getKubernetesContainerFactory().getSubmittingInsidePod(),
                workerConfig.getKubernetesContainerFactory().getInstallUserCodeDependencies(),
                workerConfig.getKubernetesContainerFactory().getPythonDependencyRepository(),
                workerConfig.getKubernetesContainerFactory().getPythonExtraDependencyRepository(),
                workerConfig.getKubernetesContainerFactory().getExtraFunctionDependenciesDir(),
                workerConfig.getKubernetesContainerFactory().getCustomLabels(),
                workerConfig.getKubernetesContainerFactory().getPercentMemoryPadding(),
                StringUtils.isEmpty(workerConfig.getKubernetesContainerFactory().getPulsarServiceUrl())
                        ? workerConfig.getPulsarServiceUrl()
                        : workerConfig.getKubernetesContainerFactory().getPulsarServiceUrl(),
                StringUtils.isEmpty(workerConfig.getKubernetesContainerFactory().getPulsarAdminUrl())
                        ? workerConfig.getPulsarWebServiceUrl()
                        : workerConfig.getKubernetesContainerFactory().getPulsarAdminUrl(),
                workerConfig.getStateStorageServiceUrl(), authConfig,
                workerConfig.getKubernetesContainerFactory().getExpectedMetricsCollectionInterval() == null ? -1
                        : workerConfig.getKubernetesContainerFactory().getExpectedMetricsCollectionInterval(),
                workerConfig.getKubernetesContainerFactory().getChangeConfigMap(),
                workerConfig.getKubernetesContainerFactory().getChangeConfigMapNamespace(),
                workerConfig.getFunctionInstanceMinResources(), secretsProviderConfigurator);
    } else {
        throw new RuntimeException("Either Thread, Process or Kubernetes Container Factory need to be set");
    }

    this.functionActioner = new FunctionActioner(this.workerConfig, runtimeFactory, dlogNamespace,
            connectorsManager, workerService.getBrokerAdmin());

    this.membershipManager = membershipManager;
    this.functionMetaDataManager = functionMetaDataManager;
}

From source file:org.apache.ambari.server.bootstrap.BootStrapTest.java

@Test
public void testHostFailure() throws Exception {
    Properties properties = new Properties();
    String bootdir = temp.newFolder("bootdir").toString();
    String metadetadir = temp.newFolder("metadetadir").toString();
    String serverVersionFilePath = temp.newFolder("serverVersionFilePath").toString();
    LOG.info("Bootdir is " + bootdir);
    LOG.info("Metadetadir is " + metadetadir);
    LOG.info("ServerVersionFilePath is " + serverVersionFilePath);

    String sharedResourcesDir = "src/test/resources/";
    String serverKSTRDir = "target" + File.separator + "classes";
    if (System.getProperty("os.name").contains("Windows")) {
        sharedResourcesDir = ClassLoader.getSystemClassLoader().getResource("").getPath();
        serverKSTRDir = new File(
                new File(ClassLoader.getSystemClassLoader().getResource("").getPath()).getParent(), "classes")
                        .getPath();//  ww w . java 2  s. c om
    }

    properties.setProperty(Configuration.BOOTSTRAP_DIR, bootdir);
    properties.setProperty(Configuration.BOOTSTRAP_SCRIPT, "echo");
    properties.setProperty(Configuration.SRVR_KSTR_DIR_KEY, serverKSTRDir);
    properties.setProperty(Configuration.METADETA_DIR_PATH, metadetadir);
    properties.setProperty(Configuration.SERVER_VERSION_FILE, serverVersionFilePath);
    properties.setProperty(Configuration.SHARED_RESOURCES_DIR_KEY, sharedResourcesDir);
    Configuration conf = new Configuration(properties);
    AmbariMetaInfo ambariMetaInfo = new AmbariMetaInfo(conf);
    BootStrapImpl impl = new BootStrapImpl(conf, ambariMetaInfo);
    impl.init();
    SshHostInfo info = new SshHostInfo();
    info.setSshKey("xyz");
    ArrayList<String> hosts = new ArrayList<String>();
    hosts.add("host1");
    hosts.add("host2");
    info.setHosts(hosts);
    info.setUser("user");
    info.setUserRunAs("root");
    info.setPassword("passwd");
    BSResponse response = impl.runBootStrap(info);
    long requestId = response.getRequestId();
    LOG.info("Response id from bootstrap " + requestId);
    /* create failed done file for host2 */
    File requestDir = new File(bootdir, Long.toString(requestId));
    /* wait while directory is created */
    int num = 0;
    while (!requestDir.exists() && num < 500) {
        Thread.sleep(100);
        num++;
    }
    if (!requestDir.exists()) {
        LOG.warn("RequestDir does not exists");
    }
    FileUtils.writeStringToFile(new File(requestDir, "host1.done"), "0");
    FileUtils.writeStringToFile(new File(requestDir, "host2.done"), "1");
    /* do a query */
    BootStrapStatus status = impl.getStatus(response.getRequestId());
    LOG.info("Status " + status.getStatus());
    num = 0;
    while ((status.getStatus() == BSStat.RUNNING) && (num < 500)) {
        status = impl.getStatus(response.getRequestId());
        Thread.sleep(100);
        num++;
    }
    LOG.info("Status: log " + status.getLog() + " status=" + status.getStatus());
    /* Note its an echo command so it should echo host1,host2 */
    Assert.assertTrue(status.getLog().contains("host1,host2"));
    Assert.assertEquals(BSStat.ERROR, status.getStatus());
    Assert.assertEquals("DONE", status.getHostsStatus().get(0).getStatus());
    Assert.assertEquals("FAILED", status.getHostsStatus().get(1).getStatus());
}

From source file:Main.java

/**
 * Writes a DOM document to a stream. The precise output format is not
 * guaranteed but this method will attempt to indent it sensibly.
 *
 * <p class="nonnormative"><b>Important</b>: There might be some problems
 * with <code>&lt;![CDATA[ ]]&gt;</code> sections in the DOM tree you pass
 * into this method. Specifically, some CDATA sections my not be written as
 * CDATA section or may be merged with other CDATA section at the same
 * level. Also if plain text nodes are mixed with CDATA sections at the same
 * level all text is likely to end up in one big CDATA section.
 * <br>//from   w  w  w.  java 2 s . co m
 * For nodes that only have one CDATA section this method should work fine.
 * </p>
 *
 * @param doc DOM document to be written
 * @param out data sink
 * @param enc XML-defined encoding name (for example, "UTF-8")
 * @throws IOException if JAXP fails or the stream cannot be written to
 */
public static void write(Document doc, OutputStream out, String enc) throws IOException {
    if (enc == null) {
        throw new NullPointerException(
                "You must set an encoding; use \"UTF-8\" unless you have a good reason not to!"); // NOI18N
    }
    Document doc2 = normalize(doc);
    ClassLoader orig = Thread.currentThread().getContextClassLoader();
    Thread.currentThread()
            .setContextClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // #195921
                @Override
                public ClassLoader run() {
                    return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) {
                        @Override
                        public InputStream getResourceAsStream(String name) {
                            if (name.startsWith("META-INF/services/")) {
                                return new ByteArrayInputStream(new byte[0]); // JAXP #6723276
                            }
                            return super.getResourceAsStream(name);
                        }
                    };
                }
            }));
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc2.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            String sys = dt.getSystemId();
            if (sys != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys);
            }
        }
        t.setOutputProperty(OutputKeys.ENCODING, enc);
        try {
            t.setOutputProperty(ORACLE_IS_STANDALONE, "yes");
        } catch (IllegalArgumentException x) {
            // fine, introduced in JDK 7u4
        }

        // See #123816
        Set<String> cdataQNames = new HashSet<String>();
        collectCDATASections(doc2, cdataQNames);
        if (cdataQNames.size() > 0) {
            StringBuilder cdataSections = new StringBuilder();
            for (String s : cdataQNames) {
                cdataSections.append(s).append(' '); //NOI18N
            }
            t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString());
        }

        Source source = new DOMSource(doc2);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (javax.xml.transform.TransformerException | RuntimeException e) { // catch anything that happens
        throw new IOException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(orig);
    }
}