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.axiom.util.stax.dialect.StAXDialectDetector.java

/**
 * Get the URL corresponding to the root folder of the classpath entry from which a given
 * resource is loaded. This URL can be used to load other resources from the same classpath
 * entry (JAR file or directory)./* ww w . ja  v  a2 s  .  c  o m*/
 * 
 * @return the root URL or <code>null</code> if the resource can't be found or if it is not
 *         possible to determine the root URL
 */
private static URL getRootUrlForResource(ClassLoader classLoader, String resource) {
    if (classLoader == null) {
        // A null class loader means the bootstrap class loader. In this case we use the
        // system class loader. This is safe since we can assume that the system class
        // loader uses parent first as delegation policy.
        classLoader = ClassLoader.getSystemClassLoader();
    }
    URL url = classLoader.getResource(resource);
    if (url == null) {
        return null;
    }
    String file = url.getFile();
    if (file.endsWith(resource)) {
        try {
            return new URL(url.getProtocol(), url.getHost(), url.getPort(),
                    file.substring(0, file.length() - resource.length()));
        } catch (MalformedURLException ex) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.ajax4jsf.resource.InternetResourceBuilder.java

/**
 * Get ( or create if nessesary ) instance of builder for current
 * loader. check content of file/*from  www. j a  v  a2s . c o m*/
 * META-INF/services/org.ajax4jsf.resource.InternetResourceBuilder
 * for name of class to instantiate, othrthise create
 * {@link ResourceBuilderImpl} instance.
 * 
 * @return current builder instance.
 */
public static InternetResourceBuilder getInstance() {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InternetResourceBuilder instance = (InternetResourceBuilder) instances.get(loader);
    if (null == instance) {
        try {
            // Default service implementation
            String serviceClassName = "org.ajax4jsf.resource.ResourceBuilderImpl";
            String resource = "META-INF/services/" + InternetResourceBuilder.class.getName();
            InputStream in = URLToStreamHelper.urlToStreamSafe(loader.getResource(resource));
            if (null != in) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                serviceClassName = reader.readLine();
                reader.close();
                in.close();
            }
            Class<?> builderClass = loader.loadClass(serviceClassName);
            instance = (InternetResourceBuilder) builderClass.newInstance();
            if (log.isDebugEnabled()) {
                log.debug("Create instance of InternetBuilder from class " + serviceClassName);
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.error("Can't create instance of InternetBuilder service", e);
                throw new FacesException("Error on create instance of InternetBuilder service", e);
            }
            // TODO - detect default instance.
            // instance = new ResourceBuilderImpl();
        }
        instances.put(loader, instance);
    }
    if (log.isDebugEnabled()) {
        log.debug("Return instance of internet resource builder " + instance.toString());
    }
    return instance;
}

From source file:com.feilong.core.lang.ClassLoaderUtil.java

/**
 * ???,?????????.// www  .j  a v  a 2s.c om
 * 
 * <h3>?:</h3>
 * <blockquote>
 * <ol>
 * <li> <code>resourceName</code>  ? "/" ,?,  ClassLoader???? ?, ??
 * <code>org.springframework.core.io.ClassPathResource#ClassPathResource(String, ClassLoader)</code></li>
 * <li>"",classes </li>
 * </ol>
 * </blockquote>
 *
 * @param classLoader
 *            the class loader
 * @param resourceName
 *            the resource name
 * @return  <code>classLoader</code> null, {@link NullPointerException}<br>
 *          <code>resourceName</code> null, {@link NullPointerException}<br>
 *         ??,????, null
 * @since 1.2.1
 */
private static URL getResource(ClassLoader classLoader, String resourceName) {
    Validate.notNull(classLoader, "classLoader can't be null!");
    Validate.notNull(resourceName, "resourceName can't be null!");

    boolean startsWithSlash = resourceName.startsWith("/");
    String usePath = startsWithSlash ? StringUtil.substring(resourceName, 1) : resourceName;
    URL result = classLoader.getResource(usePath);

    LOGGER.info("search resource:[\"{}\"] in [{}],result:[{}]", resourceName, classLoader, result);
    return result;
}

From source file:eu.stratosphere.nephele.io.compression.CompressionLoader.java

/**
 * Returns the path to the native libraries or <code>null</code> if an error occurred.
 * /*from   w  ww.  j  a  va  2  s  .c o m*/
 * @param libraryClass
 *        the name of this compression library's wrapper class including full package name
 * @return the path to the native libraries or <code>null</code> if an error occurred
 */
private static String getNativeLibraryPath(final String libraryClass) {

    final ClassLoader cl = ClassLoader.getSystemClassLoader();
    if (cl == null) {
        LOG.error("Cannot find system class loader");
        return null;
    }

    final String classLocation = libraryClass.replace('.', '/') + ".class";
    if (LOG.isDebugEnabled()) {
        LOG.debug("Class location is " + classLocation);
    }

    final URL location = cl.getResource(classLocation);
    if (location == null) {
        LOG.error("Cannot determine location of CompressionLoader class");
        return null;
    }

    final String locationString = location.toString();
    if (locationString.contains(".jar!")) { // Class if inside of a deployed jar file

        // Create and return path to native library cache
        final String pathName = GlobalConfiguration
                .getString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY,
                        ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH)
                .split(File.pathSeparator)[0] + File.separator + NATIVELIBRARYCACHENAME;

        final File path = new File(pathName);
        if (!path.exists()) {
            if (!path.mkdir()) {
                LOG.error("Cannot create directory for native library cache.");
                return null;
            }
        }

        return pathName;

    } else {

        String result = "";

        int pos = locationString.indexOf(classLocation);
        if (pos < 0) {
            LOG.error("Cannot find extract native path from class location");
            return null;
        }

        result = locationString.substring(0, pos) + "META-INF/lib";

        // Strip the file:/ scheme, it confuses the class loader
        if (result.startsWith("file:")) {
            result = result.substring(5);
        }

        return result;
    }
}

From source file:org.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java

@Deployment(name = "form-auth.war", testable = false)
public static WebArchive deployment() {
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    String resourcesLocation = "org/jboss/as/test/integration/web/formauth/resources/";

    WebArchive war = ShrinkWrap.create(WebArchive.class, "form-auth.war");
    war.setWebXML(tccl.getResource(resourcesLocation + "web.xml"));
    war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");

    war.addClass(SecureServlet.class);
    war.addClass(SecuredPostServlet.class);
    war.addClass(LogoutServlet.class);

    war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "unsecure_form.html"), "unsecure_form.html");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "restricted/errors.jsp"),
            "restricted/errors.jsp");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "restricted/error.html"),
            "restricted/error.html");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "restricted/login.html"),
            "restricted/login.html");

    log.info(war.toString(true));/*  w w w.  ja va 2s .c o m*/
    return war;
}

From source file:net.xy.jcms.controller.configurations.parser.UsecaseParser.java

/**
 * this method checks if a included fragment is associated with dependend
 * configurations destinguished from filename. this is done for one level.
 * /*from   www .jav  a 2s  . c  om*/
 * @param config
 * @param loader
 * @return list of additional configs
 * @throws IOException
 *             in case of loading an resource failed
 */
private static Collection<? extends Configuration<?>> loadFragmentDependencies(
        final TemplateConfiguration config, final ClassLoader loader) throws IOException {
    final List<Configuration<?>> configs = new ArrayList<Configuration<?>>();
    for (final Entry<String, String> e : config.getSources().entrySet()) {
        for (final Entry<ConfigurationType, String> resConf : CONFIG_POSTFIXES.entrySet()) {
            final URL url = loader.getResource(e.getValue().trim() + resConf.getValue().trim());
            if (url != null) {
                configs.add(Configuration.initByStream(resConf.getKey(), JCmsHelper.loadResource(url, loader),
                        loader, e.getKey()));
            }
        }
    }
    return configs;
}

From source file:com.depas.utils.FileUtils.java

public static URL getURLFromClasspath(final String fileName) {
    String resName = null;//from   w w  w.j  a v  a 2 s.  c  o m
    try {
        resName = URLDecoder.decode(fileName, "UTF-8");
    } catch (Exception e) {
    }

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return cl.getResource(resName);
}

From source file:com.depas.utils.FileUtils.java

/**
 * Returns content of resource that exists on classpath
 *//*from w w w . j a va  2s.c  o m*/
public static String getTextFromResource(String resourceName) throws IOException {

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl.getResource(resourceName) == null) {
        throw new FileNotFoundException(
                "The resource " + resourceName + " could not be found on the current classpath.");
    }

    StringBuffer buf = new StringBuffer();
    BufferedInputStream bis = null;
    try {
        InputStream is = cl.getResourceAsStream(resourceName);
        bis = new BufferedInputStream(is);

        int i;
        while ((i = bis.read()) != -1) {
            buf.append((char) i);
        }
    } finally {
        try {
            bis.close();
        } catch (Exception ex) {
        }
    }

    return buf.toString();

}

From source file:com.depas.utils.FileUtils.java

public static Properties getProperties(String filePath) throws IOException {
    InputStream inStream = null;/*from w w w  .  j  a  v a2  s .  c  o  m*/
    try {
        String decodedFilePath = URLDecoder.decode(filePath, "UTF-8");
        //          inStream=new FileInputStream(decodedFilePath);

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl.getResource(decodedFilePath) == null) {
            throw new FileNotFoundException(
                    "Ignite was unable to find the resource [" + decodedFilePath + "].");
        }

        inStream = cl.getResourceAsStream(decodedFilePath);

        Properties properties = new Properties();
        properties.load(inStream);
        return properties;
    } finally {
        if (inStream != null) {
            try {
                inStream.close();
            } catch (Exception ex) {
                logger.warn("Error closing InputStream [filePath=" + filePath + "]: " + ex);
            }
        }
    }
}

From source file:com.alibaba.jstorm.blobstore.BlobStoreUtils.java

public static void downloadLocalStormCode(Map conf, String topologyId, String masterCodeDir)
        throws IOException, TException {
    // STORM_LOCAL_DIR/supervisor/tmp/(UUID)
    String tmpRoot = StormConfig.supervisorTmpDir(conf) + File.separator + UUID.randomUUID().toString();

    // STORM-LOCAL-DIR/supervisor/stormdist/storm-id
    String stormRoot = StormConfig.supervisor_stormdist_root(conf, topologyId);

    BlobStore blobStore = null;/*  ww w  . jav  a2  s. c o m*/
    try {
        blobStore = BlobStoreUtils.getNimbusBlobStore(conf, masterCodeDir, null);
        FileUtils.forceMkdir(new File(tmpRoot));
        blobStore.readBlobTo(StormConfig.master_stormcode_key(topologyId),
                new FileOutputStream(StormConfig.stormcode_path(tmpRoot)));
        blobStore.readBlobTo(StormConfig.master_stormconf_key(topologyId),
                new FileOutputStream(StormConfig.stormconf_path(tmpRoot)));
    } finally {
        if (blobStore != null)
            blobStore.shutdown();
    }

    File srcDir = new File(tmpRoot);
    File destDir = new File(stormRoot);
    try {
        FileUtils.moveDirectory(srcDir, destDir);
    } catch (FileExistsException e) {
        FileUtils.copyDirectory(srcDir, destDir);
        FileUtils.deleteQuietly(srcDir);
    }

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    String resourcesJar = resourcesJar();
    URL url = classloader.getResource(StormConfig.RESOURCES_SUBDIR);
    String targetDir = stormRoot + '/' + StormConfig.RESOURCES_SUBDIR;
    if (resourcesJar != null) {
        LOG.info("Extracting resources from jar at " + resourcesJar + " to " + targetDir);
        JStormUtils.extractDirFromJar(resourcesJar, StormConfig.RESOURCES_SUBDIR, stormRoot);
    } else if (url != null) {
        LOG.info("Copying resources at " + url.toString() + " to " + targetDir);
        FileUtils.copyDirectory(new File(url.getFile()), (new File(targetDir)));
    }
}