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:org.jamwiki.utils.WikiLogger.java

/**
 *
 *//*from  ww  w .  j a va2 s .com*/
private static File loadProperties() throws Exception {
    ClassLoader loader = ClassUtils.getDefaultClassLoader();
    URL url = loader.getResource(LOG_PROPERTIES_FILENAME);
    if (url == null) {
        throw new Exception("Log initialization file " + LOG_PROPERTIES_FILENAME + " could not be found");
    }
    File propertyFile = new File(URLDecoder.decode(url.getFile(), "UTF-8"));
    if (!propertyFile.exists()) {
        throw new Exception("Log initialization file " + LOG_PROPERTIES_FILENAME + " could not be found");
    }
    return propertyFile;
}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

public static CloseableHttpClient securedClient(String alias) {
    try {/*from   w w w  .  j  a  va 2  s  .  co  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client_cert_auth");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ConnectionSocketFactory sslssf = new SSLConnectionSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> sr = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslssf).build();
        HttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sr);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();

        return httpClient;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.siphyc.utils.Utilities.java

public static URL getResource(String resource) {
    URL url;//from w  w w .  ja  v a  2  s .c  o m

    //Try with the Thread Context Loader. 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        url = classLoader.getResource(resource);
        if (url != null) {
            return url;
        }
    }
    //Last ditch attempt. Get the resource from the classpath.
    return ClassLoader.getSystemResource(resource);
}

From source file:com.gravspace.core.HttpServer.java

public static void start(String[] args) throws Exception {

    int port = 8082;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }//from   ww  w  .  j av a  2 s .c  o  m

    ActorSystem system = ActorSystem.create("Application-System");
    Properties config = new Properties();
    config.load(HttpServer.class.getResourceAsStream("/megapode.conf"));
    ActorRef master = system.actorOf(Props.create(CoordinatingActor.class, config), "Coordinator");

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpHandler(system, master));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    RequestListenerThread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();

    t.join();
}

From source file:net.sf.ehcache.config.ConfigurationFactory.java

/**
 * Configures a bean from an XML file in the classpath.
 *//*from w  w w .  j av a  2s  . co m*/
public static Configuration parseConfiguration() throws CacheException {
    ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
    URL url = null;
    if (standardClassloader != null) {
        url = standardClassloader.getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE);
    }
    if (url == null) {
        url = ConfigurationFactory.class.getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE);
    }
    if (url != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Configuring ehcache from ehcache.xml found in the classpath: " + url);
        }
    } else {
        url = ConfigurationFactory.class.getResource(FAILSAFE_CLASSPATH_CONFIGURATION_FILE);
        if (LOG.isWarnEnabled()) {
            LOG.warn("No configuration found. Configuring ehcache from ehcache-failsafe.xml "
                    + " found in the classpath: " + url);
        }
    }
    return parseConfiguration(url);
}

From source file:org.ajax4jsf.util.ServicesUtils.java

/**
 * @param loader/*from   ww w. j a va 2 s.  c  om*/
 * @param name
 * @return
 * @throws ClassNotFoundException
 */
public static Class<?> loadServiceClass(ClassLoader loader, String name) throws ClassNotFoundException {
    Class<?> serviceClass;
    try {
        String resource = "META-INF/services/" + name;
        InputStream in = URLToStreamHelper.urlToStreamSafe(loader.getResource(resource));
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String serviceClassName = reader.readLine();
        reader.close();
        serviceClass = loadClass(loader, serviceClassName);
        if (log.isDebugEnabled()) {
            log.debug("Class for service " + name + " set to " + serviceClassName);
        }
    } catch (Exception e) {
        serviceClass = loadClass(loader, name);
        if (log.isDebugEnabled()) {
            log.debug("Service class set to default implementation " + name);
        }
    }
    return serviceClass;
}

From source file:org.apache.abdera2.common.Discover.java

public static URL locateResource(String id, ClassLoader loader, Class<?> callingClass) {
    URL url = loader.getResource(id);
    if (url == null && id.startsWith("/"))
        url = loader.getResource(id.substring(1));
    if (url == null)
        url = locateResource(id, Discover.class.getClassLoader(), callingClass);
    if (url == null && callingClass != null)
        url = locateResource(id, callingClass.getClassLoader(), null);
    if (url == null)
        url = callingClass.getResource(id);
    if ((url == null) && id.startsWith("/"))
        url = callingClass.getResource(id.substring(1));
    return url;// w ww.  j  a  va2  s. c om
}

From source file:io.fabric8.camel.tooling.util.CamelNamespaces.java

private static URL tryLoadClass(ClassLoader classLoader, String name) {
    try {//from   w  w w .  j av  a 2  s.  com
        return classLoader.getResource(name);
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

/**
 * Load a given resource. <p/> This method will try to load the resource
 * using the following methods (in order):
 * <ul>//from w  w  w .j av a  2s . co  m
 * <li>From Thread.currentThread().getContextClassLoader()
 * <li>From ClassLoaderUtil.class.getClassLoader()
 * <li>callingClass.getClassLoader()
 * </ul>
 * 
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 */
public static URL getResource(String resourceName, Class callingClass) {
    URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
    if (url == null && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        url = Thread.currentThread().getContextClassLoader().getResource(resourceName.substring(1));
    }

    ClassLoader cluClassloader = Main.class.getClassLoader();
    if (cluClassloader == null) {
        cluClassloader = ClassLoader.getSystemClassLoader();
    }
    if (url == null) {
        url = cluClassloader.getResource(resourceName);
    }
    if (url == null && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        url = cluClassloader.getResource(resourceName.substring(1));
    }

    if (url == null) {
        ClassLoader cl = callingClass.getClassLoader();

        if (cl != null) {
            url = cl.getResource(resourceName);
        }
    }

    if (url == null) {
        url = callingClass.getResource(resourceName);
    }

    if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
        return getResource('/' + resourceName, callingClass);
    }

    return url;
}

From source file:com.agimatec.validation.jsr303.xml.ValidationParser.java

static Schema getSchema(String xsd) {
    ClassLoader loader = PrivilegedActions.getClassLoader(ValidationParser.class);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = loader.getResource(xsd);
    try {//from   w w w.  j a va  2 s .c  om
        return sf.newSchema(schemaUrl);
    } catch (SAXException e) {
        log.warn("Unable to parse schema: " + xsd, e);
        return null;
    }
}