Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

In this page you can find the example usage for java.lang ClassLoader getResource.

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:fxts.stations.util.preferences.PreferencesManager.java

/**
 * Parses xml file to load contents.// www  .  j a  v a  2s  . co m
 *
 * @param aUrl url to xml-file
 */
private void parseXML(String aUrl) {
    XmlParser parser = new XmlParser();
    ClassLoader classLoader = getClass().getClassLoader();
    URL url = classLoader.getResource(aUrl);
    if (url == null) {
        mLogger.debug("Xml-file by url = \"" + aUrl + "\" not found!");
        return;
    }
    try {
        InputStream istream = url.openStream();
        parser.parse(new InputStreamReader(istream));
    } catch (Exception e) {
        mLogger.debug("Not parsed xml-file with contents by url = " + aUrl, e);
    }
}

From source file:de.uni.bremen.monty.moco.ast.ASTBuilderTest.java

private String getFileContent(String fileName) throws URISyntaxException, IOException {
    Class<CompileTestProgramsTest> aClass = CompileTestProgramsTest.class;
    ClassLoader classLoader = aClass.getClassLoader();
    File file = new File(classLoader.getResource(fileName).toURI());
    return FileUtils.readFileToString(file);
}

From source file:jp.aegif.nemaki.util.impl.PropertyManagerImpl.java

/**
 * Override is not supported for update/*  ww  w.  ja v a 2s.c  om*/
 */
@Override
public void removeValue(String key, String value) {
    String currentVal = config.getProperty(key);
    String[] currentVals = currentVal.split(",");
    List<String> valList = new ArrayList<String>();
    Collections.addAll(valList, currentVals);

    boolean success = valList.remove(value);
    if (success) {
        String newVal = StringUtils.join(valList.toArray(), ",");
        config.setProperty(key, newVal);

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL url = classLoader.getResource(propertiesFile);
        try {
            config.store(new FileOutputStream(new File(url.toURI())), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.sf.ehcache.hibernate.EhCacheProvider.java

private URL loadResource(String configurationResourceName) {
    ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
    URL url = null;/*from  w  w  w .  j a  va  2 s  .  co m*/
    if (standardClassloader != null) {
        url = standardClassloader.getResource(configurationResourceName);
    }
    if (url == null) {
        url = this.getClass().getResource(configurationResourceName);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating EhCacheProvider from a specified resource: " + configurationResourceName
                + " Resolved to URL: " + url);
    }
    if (url == null) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("A configurationResourceName was set to " + configurationResourceName
                    + " but the resource could not be loaded from the classpath."
                    + "Ehcache will configure itself using defaults.");
        }
    }
    return url;
}

From source file:com.asual.lesscss.LessEngine.java

public LessEngine(LessOptions options, ResourceLoader loader) {
    this.options = options;
    this.loader = loader;
    try {//from  w  w w. j av  a  2 s  .  co m
        logger.debug("Initializing LESS Engine.");
        ClassLoader classLoader = getClass().getClassLoader();
        URL less = options.getLess();
        URL env = classLoader.getResource("META-INF/env.js");
        URL engine = classLoader.getResource("META-INF/engine.js");
        URL cssmin = classLoader.getResource("META-INF/cssmin.js");
        Context cx = Context.enter();
        logger.debug("Using implementation version: " + cx.getImplementationVersion());
        cx.setOptimizationLevel(9);
        Global global = new Global();
        global.init(cx);
        scope = cx.initStandardObjects(global);
        cx.evaluateReader(scope, new InputStreamReader(env.openConnection().getInputStream()), env.getFile(), 1,
                null);
        Scriptable lessEnv = (Scriptable) scope.get("lessenv", scope);
        lessEnv.put("charset", lessEnv, options.getCharset());
        lessEnv.put("css", lessEnv, options.isCss());
        lessEnv.put("loader", lessEnv, Context.javaToJS(loader, scope));
        cx.evaluateReader(scope, new InputStreamReader(less.openConnection().getInputStream()), less.getFile(),
                1, null);
        cx.evaluateReader(scope, new InputStreamReader(cssmin.openConnection().getInputStream()),
                cssmin.getFile(), 1, null);
        cx.evaluateReader(scope, new InputStreamReader(engine.openConnection().getInputStream()),
                engine.getFile(), 1, null);
        compile = (Function) scope.get("compile", scope);
        Context.exit();
    } catch (Exception e) {
        logger.error("LESS Engine intialization failed.", e);
    }
}

From source file:com.appleframework.core.utils.ClassUtility.java

/** class loaderclass? */
public static String locateClass(String className, ClassLoader loader) {
    className = assertNotNull(trimToNull(className), "className");
    if (loader == null) {
        loader = Thread.currentThread().getContextClassLoader();
    }// w  w w.  ja  v  a 2 s  .c o m
    String classFile = className.replace('.', '/') + ".class";
    URL locationURL = loader.getResource(classFile);
    String location = null;
    if (locationURL != null) {
        location = locationURL.toExternalForm();

        if (location.endsWith(classFile)) {
            location = location.substring(0, location.length() - classFile.length());
        }
        location = location.replaceAll("^(jar|zip):|!/$", EMPTY_STRING);
    }
    return location;
}

From source file:org.toobsframework.biz.scriptmanager.ScriptServiceImpl.java

private Script loadScript(String scriptName, Context ctx) throws ScriptException {
    Date initStart = new Date();
    ;/*from  w  w w. j  a va2 s  .  com*/

    if (registry.containsKey(scriptName) && !doReload) {
        return (Script) registry.get(scriptName);
    }
    Script script = null;

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL configFileURL = classLoader.getResource("script/" + scriptName + ".js");

    // If the file exists, read it.
    if (null != configFileURL) {
        try {
            InputStreamReader reader = new InputStreamReader(configFileURL.openStream());
            script = ctx.compileReader(reader, scriptName, 1, null);
        } catch (IOException e) {
            throw new ScriptException("Can't load script:" + scriptName);
        }
    }

    this.registry.put(scriptName, script);

    if (log.isDebugEnabled()) {
        Date initEnd = new Date();
        log.debug("Script [" + scriptName + "] - Compile Time: " + (initEnd.getTime() - initStart.getTime()));
    }
    return script;

}

From source file:com.mgmtp.perfload.core.client.web.config.HttpClientManagerModule.java

/**
 * If the property {@code ssl.trust.all} equals {@code true}, a {@link TrustAllManager} is
 * installed, i. e. all certificates are trusted, and host name verification is turned off.
 * Otherwise, {@link LtSSLSocketFactory} is registered for HTTPS, if either a key store, a trust
 * store or both are configured using the following properties:</p>
 * <p>/*from w  w w.ja  v  a 2  s .  c  om*/
 * <ul>
 * <li>{@code javax.net.ssl.keyStore}</li>
 * <li>{@code javax.net.ssl.keyStorePassword}</li>
 * <li>{@code javax.net.ssl.keyStoreType}</li>
 * <li>{@code javax.net.ssl.trustStore}</li>
 * <li>{@code javax.net.ssl.trustStorePassword}</li>
 * <li>{@code javax.net.ssl.trustStoreType}</li>
 * </ul>
 * </p>
 * <p>
 * {@code javax.net.ssl.trustStore} and {@code javax.net.ssl.keyStore} must point to resources
 * on the classpath.
 * </p>
 * 
 * @param properties
 *            the properties
 * @return the {@link SchemeRegistry} the SchemeRegistry used for the HttpClient's
 *         {@link ClientConnectionManager} registered for HTTPS
 */
@Provides
@Singleton
protected SchemeRegistry provideSchemeRegistry(final PropertiesMap properties) {
    SchemeRegistry registry = SchemeRegistryFactory.createDefault();

    if (properties.getBoolean(SSL_TRUST_ALL)) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new TrustAllManager() }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, new AllowAllHostnameVerifier());
            registry.register(new Scheme("https", 443, ssf));
        } catch (GeneralSecurityException ex) {
            Throwables.propagate(ex);
        }
    } else {
        String keyStore = trimToNull(properties.get(KEY_STORE));
        String trustStore = trimToNull(properties.get(TRUST_STORE));

        if (keyStore != null || trustStore != null) {
            String keyStorePassword = trimToNull(properties.get(KEY_STORE_PASSWORD));
            String keyStoreType = trimToNull(properties.get(KEY_STORE_TYPE));

            String trustStorePassword = trimToNull(properties.get(TRUST_STORE_PASSWORD));
            String trustStoreType = trimToNull(properties.get(TRUST_STORE_TYPE));

            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            URL keyStoreUrl = keyStore != null ? loader.getResource(keyStore) : null;
            URL trustStoreUrl = trustStore != null ? loader.getResource(trustStore) : null;

            LayeredSchemeSocketFactory socketFactory = new LtSSLSocketFactory(keyStoreUrl, keyStorePassword,
                    keyStoreType, trustStoreUrl, trustStorePassword, trustStoreType);

            registry.register(new Scheme(HTTPS, 443, socketFactory));
        }
    }
    return registry;
}

From source file:com.haulmont.cuba.uberjar.ServerRunner.java

protected URL getJettyConfUrl() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {/*from w  ww.  j a  v  a 2  s  . c  om*/
        return classLoader.getResource("jetty.xml");
    } catch (Exception e) {
        System.out.println("Error while found jetty.xml");
        return null;
    }
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.TimelineMetricConfiguration.java

public void initialize() throws URISyntaxException, MalformedURLException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = getClass().getClassLoader();
    }//from  w  w w .  j av a 2 s. co  m
    URL hbaseResUrl = classLoader.getResource(HBASE_SITE_CONFIGURATION_FILE);
    URL amsResUrl = classLoader.getResource(METRICS_SITE_CONFIGURATION_FILE);
    LOG.info("Found hbase site configuration: " + hbaseResUrl);
    LOG.info("Found metric service configuration: " + amsResUrl);

    if (hbaseResUrl == null) {
        throw new IllegalStateException(
                "Unable to initialize the metrics " + "subsystem. No hbase-site present in the classpath.");
    }

    if (amsResUrl == null) {
        throw new IllegalStateException(
                "Unable to initialize the metrics " + "subsystem. No ams-site present in the classpath.");
    }

    hbaseConf = new Configuration(true);
    hbaseConf.addResource(hbaseResUrl.toURI().toURL());
    metricsConf = new Configuration(true);
    metricsConf.addResource(amsResUrl.toURI().toURL());
    isInitialized = true;
}