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.apache.cassandra.config.YamlConfigurationLoader.java

/**
 * Inspect the classpath to find storage configuration file
 *///from w  w w. jav a 2s  .  com
private static URL getStorageConfigURL() throws ConfigurationException {
    String configUrl = System.getProperty("cassandra.config");
    if (configUrl == null)
        configUrl = DEFAULT_CONFIGURATION;

    URL url;
    try {
        url = new URL(configUrl);
        url.openStream().close(); // catches well-formed but bogus URLs
    } catch (Exception e) {
        ClassLoader loader = DatabaseDescriptor.class.getClassLoader();
        url = loader.getResource(configUrl);
        if (url == null) {
            String required = "file:" + File.separator + File.separator;
            if (!configUrl.startsWith(required))
                throw new ConfigurationException(String.format(
                        "Expecting URI in variable: [cassandra.config]. Found[%s]. Please prefix the file with [%s%s] for local "
                                + "files and [%s<server>%s] for remote files. If you are executing this from an external tool, it needs "
                                + "to set Config.setClientMode(true) to avoid loading configuration.",
                        configUrl, required, File.separator, required, File.separator));
            throw new ConfigurationException(
                    "Cannot locate " + configUrl + ".  If this is a local file, please confirm you've provided "
                            + required + File.separator + " as a URI prefix.");
        }
    }

    logger.info("Configuration location: {}", url);

    return url;
}

From source file:io.lightlink.utils.ClasspathScanUtils.java

public static File getFileFromResource(String rootPackage, String resource) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String resourceName = rootPackage.replace('.', '/') + resource;
    URL url = classLoader.getResource(resourceName);
    if (url == null)
        throw new IllegalArgumentException("Cannot find :" + resourceName + "   " + resource);
    return new File(URLDecoder.decode(url.getPath()));
}

From source file:com.vangent.hieos.services.xds.bridge.utils.JUnitHelper.java

/**
 * Method description// w  ww  .j a v a 2  s  .c  o m
 *
 *
 * @param file
 *
 * @return
 *
 * @throws Exception
 */
public static OMElement fileToOMElement(String file) throws Exception {

    ClassLoader cl = JUnitHelper.class.getClassLoader();
    URL testfile = cl.getResource(file);

    assertNotNull(String.format("[%s] does not exist.", file), testfile);

    OMElement request = XMLParser.fileToOM(new File(testfile.getFile()));

    assertNotNull(request);

    logger.debug(DebugUtils.toPrettyString(request));

    return request;
}

From source file:edu.harvard.i2b2.fhir.Utils.java

public static String getFilePath(String fileName) {

    String result = "";

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    result = classLoader.getResource(fileName).getPath();

    return result;

}

From source file:org.jboss.as.test.integration.security.loginmodules.usersroles.UsersRolesLoginModuleTestCase1.java

protected static void createSecurityDomains(final ModelControllerClient client) throws Exception {
    List<ModelNode> updates = new ArrayList<ModelNode>();
    ModelNode op = new ModelNode();

    String securityDomain = "users-roles-login-module";
    op.get(OP).set(ADD);//from   w  w w.j a v  a  2  s .com
    op.get(OP_ADDR).add(SUBSYSTEM, "security");
    op.get(OP_ADDR).add(SECURITY_DOMAIN, securityDomain);
    updates.add(op);

    op = new ModelNode();
    op.get(OP).set(ADD);
    op.get(OP_ADDR).add(SUBSYSTEM, "security");
    op.get(OP_ADDR).add(SECURITY_DOMAIN, securityDomain);
    op.get(OP_ADDR).add(Constants.AUTHENTICATION, Constants.CLASSIC);

    ModelNode loginModule = op.get(Constants.LOGIN_MODULES).add();
    loginModule.get(ModelDescriptionConstants.CODE).set(UsersRolesLoginModule.class.getName());
    loginModule.get(FLAG).set("required");
    op.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();

    URL usersProp = tccl.getResource("users-roles-login-module.war/users.properties");
    URL rolesProp = tccl.getResource("users-roles-login-module.war/roles.properties");
    ModelNode moduleOptions = loginModule.get("module-options");
    moduleOptions.get("usersProperties").set(usersProp.getFile());
    moduleOptions.get("rolesProperties").set(rolesProp.getFile());
    moduleOptions.get("unauthenticatedIdentity").set(ANNONYMOUS_USER_NAME);

    updates.add(op);
    applyUpdates(updates, client);

}

From source file:es.tekniker.framework.ktek.commons.config.ConfigFile.java

protected static void setFilePath(String defaultFilePath) throws IOException {
    ConfigFile.filePath = defaultFilePath;
    log.debug("Loading properties for file " + filePath);

    ClassLoader loader = ConfigFile.class.getClassLoader();
    if (loader == null)
        loader = ClassLoader.getSystemClassLoader();

    java.net.URL url = loader.getResource(filePath);
    props.load(url.openStream());// w w w . j a v a  2s  . c  om
    log.debug("Properties loaded");
}

From source file:org.apache.flink.test.checkpointing.utils.SavepointMigrationTestBase.java

protected static String getResourceFilename(String filename) {
    ClassLoader cl = SavepointMigrationTestBase.class.getClassLoader();
    URL resource = cl.getResource(filename);
    if (resource == null) {
        throw new NullPointerException("Missing snapshot resource.");
    }/*from  ww w  .j  a  v  a2 s .co m*/
    return resource.getFile();
}

From source file:com.netspective.commons.lang.ResourceLoader.java

/**
 * This method will search for <code>resource</code> in different
 * places. The search order is as follows:
 * <p/>/*from   w w w .java 2s  . co  m*/
 * <ol>
 * <li>Search for <code>resource</code> using the thread context
 * class loader. If that fails, search for <code>resource</code> using
 * the class loader that loaded this class.
 * <li>Try one last time with <code>ClassLoader.getSystemResource(resource)</code>.
 * </ol>
 */
public static URL getResource(String resource) {
    ClassLoader classLoader = null;
    URL url = null;

    try {
        classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader != null) {
            url = classLoader.getResource(resource);
            if (url != null)
                return url;
        }

        // We could not find resource. Lets try with the classloader that loaded this class.
        classLoader = ResourceLoader.class.getClassLoader();
        if (classLoader != null) {
            url = classLoader.getResource(resource);
            if (url != null)
                return url;
        }
    } catch (Throwable t) {
        log.warn("Caught Exception while in ResourceLoader.getResource.", t);
    }

    // Last ditch attempt: get the resource from the class path. It
    // may be the case that clazz was loaded by the Extentsion class
    // loader which the parent of the system class loader. Hence the
    // code below.
    return ClassLoader.getSystemResource(resource);
}

From source file:org.stem.ClusterManagerDaemon.java

static URL getConfigUrl() {
    String configPath = System.getProperty(STEM_CONFIG_PROPERTY);
    if (null == configPath)
        configPath = DEFAULT_CONFIG;/*from   ww w  .  j  a va  2  s.  c  o m*/

    URL url;

    try {
        File file = new File(configPath);
        url = file.toURI().toURL();
        url.openStream().close();
    } catch (Exception e) {
        ClassLoader loader = ClusterManagerDaemon.class.getClassLoader();
        url = loader.getResource(configPath);
        if (null == url)
            throw new RuntimeException("Cannot load " + configPath + ". Ensure \"" + STEM_CONFIG_PROPERTY
                    + "\" system property is set correctly.");
    }

    return url;
}

From source file:org.jboss.as.test.integration.security.loginmodules.usersroles.UsersRolesLoginModuleTestCase1.java

/**
 * Base method to create a {@link org.jboss.shrinkwrap.api.spec.WebArchive}
 *
 * @param name         Name of the war file
 * @param servletClass a class that is the servlet
 * @param webxml       {@link java.net.URL} to the web.xml. This can be null
 * @return//  ww  w  .  ja  va 2 s  .c  om
 */
public static WebArchive create(String name, Class<?> servletClass, URL webxml) {
    WebArchive war = ShrinkWrap.create(WebArchive.class, name);
    war.addClass(servletClass);

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();

    war.addAsWebInfResource(tccl.getResource("users-roles-login-module.war/jboss-web.xml"), "jboss-web.xml");
    war.addClass(UsersRolesLoginModule.class);
    war.addClass(UnsecuredEJB.class);
    war.addClass(UnsecuredEJBImpl.class);

    if (webxml != null) {
        war.setWebXML(webxml);
    }

    OutputStream os = new OutputStream() {
        StringBuilder builder = new StringBuilder();

        @Override
        public void write(int b) throws IOException {
            builder.append((char) b);
        }

        public String toString() {
            return builder.toString();
        }
    };

    war.writeTo(os, Formatters.VERBOSE);

    return war;
}