Example usage for java.lang Class getResourceAsStream

List of usage examples for java.lang Class getResourceAsStream

Introduction

In this page you can find the example usage for java.lang Class getResourceAsStream.

Prototype

@CallerSensitive
public InputStream getResourceAsStream(String name) 

Source Link

Document

Finds a resource with a given name.

Usage

From source file:org.apache.manifoldcf.core.i18n.Messages.java

/** Read a resource as an input stream, given a class, path, locale, and resource key.
*///from w ww.  j a  v a2s.co  m
public static InputStream getResourceAsStream(Class classInstance, String pathName, Locale originalLocale,
        String resourceKey) throws ManifoldCFException {
    Locale locale = originalLocale;
    InputStream is = classInstance.getResourceAsStream(localizeResourceName(pathName, resourceKey, locale));
    if (is == null) {
        complainMissingResource(
                "No resource in path '" + pathName + "' named '" + resourceKey + "' found for locale '"
                        + locale.toString() + "'",
                new Exception("Resource not found"), pathName, locale, resourceKey);
        locale = new Locale(locale.getLanguage());
        is = classInstance.getResourceAsStream(localizeResourceName(pathName, resourceKey, locale));
        if (is == null) {
            complainMissingResource(
                    "No resource in path '" + pathName + "' named '" + resourceKey + "' found for locale '"
                            + locale.toString() + "'",
                    new Exception("Resource not found"), pathName, locale, resourceKey);
            locale = Locale.US;
            is = classInstance.getResourceAsStream(localizeResourceName(pathName, resourceKey, locale));
            if (is == null) {
                complainMissingResource(
                        "No resource in path '" + pathName + "' named '" + resourceKey + "' found for locale '"
                                + locale.toString() + "'",
                        new Exception("Resource not found"), pathName, locale, resourceKey);
                locale = new Locale(locale.getLanguage());
                is = classInstance.getResourceAsStream(localizeResourceName(pathName, resourceKey, locale));
                if (is == null) {
                    complainMissingResource(
                            "No resource in path '" + pathName + "' named '" + resourceKey
                                    + "' found for locale '" + locale.toString() + "'",
                            new Exception("Resource not found"), pathName, locale, resourceKey);
                    is = classInstance.getResourceAsStream(localizeResourceName(pathName, resourceKey, null));
                    if (is == null)
                        throw new ManifoldCFException(
                                "No matching language resource in path '" + pathName + "' named '" + resourceKey
                                        + "' found for locale '" + originalLocale.toString() + "'");
                }
            }
        }
    }
    return is;
}

From source file:org.kuali.kra.infrastructure.TestUtilities.java

License:asdf

public static InputStream loadResource(Class packageClass, String resourceName) {
    return packageClass.getResourceAsStream(resourceName);
}

From source file:com.amazonaws.client.regions.RegionUtils.java

/**
 * Loads a set of region metadata from an XML file stored as a resource of
 * the classloader used to load the given class.
 *
 * @param clazz the class to use as a base for the resource
 * @param name the path to the resource, relative to the given class
 * @return the parsed region metadata/*from   w ww.jav  a  2s .  co m*/
 * @throws IOException if the resource is not found or cannot be parsed
 */
public static RegionMetadata loadMetadataFromResource(final Class<?> clazz, final String name)
        throws IOException {

    InputStream stream = clazz.getResourceAsStream(name);
    if (stream == null) {
        throw new FileNotFoundException("No resource '" + name + "' found.");
    }

    try {
        return loadMetadataFromInputStream(stream);
    } finally {
        stream.close();
    }
}

From source file:org.jcurl.demo.smack.JCurlSmackClient.java

private static Properties loadClassProps(final Class<?> c, Properties p) throws IOException {
    if (p == null)
        p = new Properties();
    final String r = "/" + c.getName().replace('.', '/') + ".properties";
    final InputStream i = c.getResourceAsStream(r);
    if (i == null) {
        System.err.println("Add a file '." + r + "' to the classpath containing the properties:");
        System.err.println("\nacc_uid = foo@foo.org # a jabber account name");
        System.err.println("\nacc_pwd = .. # a jabber account password");
    }/*ww w .j  a v  a 2  s .  c o m*/
    p.load(i);
    return p;
}

From source file:ch.entwine.weblounge.common.impl.util.TemplateUtils.java

/**
 * Loads the resource identified by concatenating the package name from
 * <code>clazz</code> and <code>path</code> from the classpath.
 * // ww w .j av a2 s. c  o  m
 * @param path
 *          the path relative to the package name of <code>clazz</code>
 * @param clazz
 *          the class
 * @return the resource
 */
public static String load(String path, Class<?> clazz) {
    if (path == null)
        throw new IllegalArgumentException("path cannot be null");
    if (clazz == null)
        throw new IllegalArgumentException("clazz cannot be null");
    String pkg = "/" + clazz.getPackage().getName().replace('.', '/');
    InputStream is = clazz.getResourceAsStream(UrlUtils.concat(pkg, path));
    InputStreamReader isr = null;
    StringBuffer buf = new StringBuffer();
    if (is != null) {
        try {
            logger.debug("Loading " + path);
            isr = new InputStreamReader(is, Charset.forName("UTF-8"));
            char[] chars = new char[1024];
            int count = 0;
            while ((count = isr.read(chars)) > 0) {
                for (int i = 0; i < count; i++)
                    buf.append(chars[i]);
            }
            return buf.toString();
        } catch (Throwable t) {
            logger.warn("Error reading " + path + ": " + t.getMessage());
        } finally {
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(is);
        }
        logger.debug("Editor support (javascript) loaded");
    } else {
        logger.error("Repository item not found: " + path);
    }
    return null;
}

From source file:org.fuin.owndeb.commons.DebUtils.java

/**
 * Copies a resource to a file.//  w  w w  . j a  v a  2  s.com
 * 
 * @param clasz
 *            Class to use for getting the resource.
 * @param resource
 *            Path and name of the resource.
 * @param targetFile
 *            Target file to create.
 */
public static void copyResourceToFile(final Class<?> clasz, final String resource, final File targetFile) {
    LOG.info("Copy resource '{}' to file: {}", resource, targetFile);
    try {
        final InputStream in = clasz.getResourceAsStream(resource);
        if (in == null) {
            throw new IllegalArgumentException("Resource not found: " + resource);
        }
        try {
            FileUtils.copyInputStreamToFile(in, targetFile);
        } finally {
            in.close();
        }
    } catch (final IOException ex) {
        throw new RuntimeException("Error while copying resource '" + resource + "' to: " + targetFile, ex);
    }
}

From source file:com.feilong.core.util.PropertiesUtil.java

/**
 * {@link Class#getResourceAsStream(String)}  InputStream,? {@link #getProperties(InputStream)}.
 * /* w  ww . ja v a2 s  .co m*/
 * <h3> <code>propertiesPath</code>:</h3>
 * 
 * <blockquote>
 * ? class {@link PropertiesUtil},? src/main/resources?, messages/feilong-core-message_en_US.properties<br>
 * <p>
 * ? <code>getProperties(PropertiesUtil.class,<b>"/messages/feilong-core-message_en_US.properties"</b>)</code> <br>
 * ??? <b>"/messages/feilong-core-message_en_US.properties"</b>, ???
 * </p>
 * 
 * <p>
 * ? {@link #getPropertiesWithClassLoader(Class, String)} 
 * </p>
 * </blockquote>
 * 
 * @param klass
 *            , klass 
 * @param propertiesPath
 *            the properties path
 * @return  <code>klass</code> null, {@link NullPointerException}<br>
 *          <code>propertiesPath</code> null, {@link NullPointerException}<br>
 *          <code>propertiesPath</code> blank, {@link IllegalArgumentException}<br>
 * @see java.lang.Class#getResourceAsStream(String)
 * @see #getProperties(InputStream)
 * @see #getPropertiesWithClassLoader(Class, String)
 */
public static Properties getProperties(Class<?> klass, String propertiesPath) {
    Validate.notNull(klass, "klass can't be null!");
    Validate.notBlank(propertiesPath, "propertiesPath can't be blank!");
    // klass.getResourceAsStream classLoader.getResourceAsStream
    // ?,???ClassLoader??.
    return getProperties(klass.getResourceAsStream(propertiesPath));
}

From source file:gdt.data.grain.Support.java

/**
 * Copy the icon file from the class path into the target directory. 
 * @param handler the class//  w ww. ja v a2s  .com
 * @param icon$ the name of the icon file.
 *  @param directory$ the icons directory path .
 */
public static void addHandlerIcon(Class<?> handler, String icon$, String directory$) {
    try {

        File iconFile = new File(directory$ + "/" + icon$);
        if (iconFile.exists())
            return;
        iconFile.createNewFile();
        InputStream is = handler.getResourceAsStream(icon$);
        FileOutputStream fos = new FileOutputStream(iconFile);
        byte[] b = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = is.read(b)) != -1) {
            fos.write(b, 0, bytesRead);
        }
        is.close();
        fos.close();
    } catch (Exception e) {
        Logger.getLogger(gdt.data.grain.Support.class.getName()).severe(e.toString());
    }
}

From source file:SwingResourceManager.java

/**
 * Returns an image stored in the file at the specified path relative to the specified class
 * @param clazz Class The class relative to which to find the image
 * @param path String The path to the image file
 * @return Image The image stored in the file at the specified path
 */// w  w  w.ja v a  2 s .c  o  m
public static Image getImage(Class<?> clazz, String path) {
    String key = clazz.getName() + '|' + path;
    Image image = m_ClassImageMap.get(key);
    if (image == null) {
        if ((path.length() > 0) && (path.charAt(0) == '/')) {
            String newPath = path.substring(1, path.length());
            image = getImage(new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(newPath)));
        } else {
            image = getImage(clazz.getResourceAsStream(path));
        }
        m_ClassImageMap.put(key, image);
    }
    return image;
}

From source file:com.hp.ov.sdk.rest.client.NetworkClientImplTest.java

@BeforeClass
public static void setupTest() throws IOException {
    Class<NetworkClientImplTest> clazz = NetworkClientImplTest.class;

    ethernetNetwork = IOUtils.toString(clazz.getResourceAsStream("EthernetNetworkResponse.json"), "UTF-8");
    ethernetNetworkCollection = IOUtils/*from w  w  w  . j av a2 s. c  o  m*/
            .toString(clazz.getResourceAsStream("EthernetNetworkCollectionResponse.json"), "UTF-8");
}