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:com.sap.dirigible.ide.template.ui.common.TemplateGenerator.java

protected void copyFile(String targetFileName, String templateLocation, Class<?> clazz)
        throws IOException, Exception {
    IPath location = new Path(getModel().getTargetLocation()).append(targetFileName);
    InputStream in = clazz.getResourceAsStream(templateLocation);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(in, out);//from  ww w . j ava  2s. co m
    createFile(location, out.toByteArray());
}

From source file:net.padaf.xmpbox.parser.XMLPropertiesDescriptionManager.java

/**
 * Load Properties Description from a well-formed XML File
 * /*  ww w  .j a  v a2  s . co  m*/
 * @param classSchem
 *            Description Schema where properties description are used
 * @param path
 *            Relative Path (file loading search in same class Schema
 *            representation folder)
 * @throws BuildPDFAExtensionSchemaDescriptionException
 *             When problems to get or treat data in XML description file
 */
public void loadListFromXML(Class<? extends XMPSchema> classSchem, String path)
        throws BuildPDFAExtensionSchemaDescriptionException {
    InputStream fis = classSchem.getResourceAsStream(path);
    if (fis == null) {
        // resource not found
        throw new BuildPDFAExtensionSchemaDescriptionException(
                "Failed to find specified XML properties descriptions resource");
    }
    loadListFromXML(fis);

}

From source file:org.pentaho.test.platform.util.XmlHelperTest.java

public void testGetDocFromString() {
    try {//from  w ww .j  av  a2s .  co m
        Class resourceClass = this.getClass();
        InputStream in = resourceClass.getResourceAsStream("/test/xml/index.xml");
        Document doc = XmlDom4JHelper.getDocFromStream(in);
        System.out.println("Document as String" + doc.getStringValue()); //$NON-NLS-1$      
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue("Exception thrown " + e.getMessage(), false); //$NON-NLS-1$
    }
}

From source file:org.pentaho.test.platform.util.XmlHelperTest.java

/**
 * Load an XML file into a dom4j.Document, convert that document to a string, load that string
 * into a w3c.Document, and turn it back into a string.
 * //from  w  w w  .  j  a  v a  2s .c  o m
 * @throws FileNotFoundException
 * @throws TransformerConfigurationException
 * @throws TransformerException
 */
public void testGetXMLFromDocument()
        throws FileNotFoundException, TransformerConfigurationException, TransformerException {
    try {
        Class resourceClass = this.getClass();
        InputStream in = resourceClass.getResourceAsStream("/test/xml/JFreeQuadrantForRegion.xml");
        org.dom4j.Document doc = XmlDom4JHelper.getDocFromStream(in);

        org.w3c.dom.Document w3cDoc = XmlW3CHelper.getDomFromString(doc.asXML());

        StringBuffer strBuff = XmlDom4JHelper.docToString(w3cDoc);
        System.out.println(strBuff.toString());
        Assert.assertTrue(!StringUtils.isEmpty(strBuff.toString()));
    } catch (Throwable e) {
        System.out.println("Exception thrown " + e.getMessage()); //$NON-NLS-1$
        Assert.assertTrue("Exception thrown " + e.getMessage(), false); //$NON-NLS-1$
    }
}

From source file:org.opencms.ui.CmsVaadinUtils.java

/**
 * Reads a layout from a resource, applies basic i18n macro substitution on the contained text, and returns a stream of the transformed
 * data.<p>/*from   w  w w.j a va2 s.co m*/
 *
 * @param layoutClass the class relative to which the layout resource will be looked up
 * @param relativeName the file name of the layout file
 *
 * @return an input stream which produces the transformed layout resource html
 */
public static InputStream readCustomLayout(Class<? extends Component> layoutClass, String relativeName) {

    CmsMacroResolver resolver = new CmsMacroResolver() {

        @Override
        public String getMacroValue(String macro) {

            return CmsEncoder.escapeXml(super.getMacroValue(macro));
        }
    };
    resolver.setMessages(CmsVaadinUtils.getWpMessagesForCurrentLocale());
    InputStream layoutStream = CmsVaadinUtils
            .filterUtf8ResourceStream(layoutClass.getResourceAsStream(relativeName), resolver.toFunction());
    return layoutStream;
}

From source file:net.padaf.xmpbox.parser.XMLValueTypeDescriptionManager.java

/**
 * Load Value Types Descriptions from a well-formed XML File
 * //from   w w  w.  j av  a2s  .com
 * @param classSchem
 *            Description Schema where properties description are used
 * @param path
 *            Relative Path (file loading search in same class Schema
 *            representation folder)
 * @throws BuildPDFAExtensionSchemaDescriptionException
 *             When problems to get or treat data in XML description file
 */
public void loadListFromXML(Class<? extends XMPSchema> classSchem, String path)
        throws BuildPDFAExtensionSchemaDescriptionException {
    InputStream fis = classSchem.getResourceAsStream(path);
    if (fis == null) {
        throw new BuildPDFAExtensionSchemaDescriptionException(
                "Failed to find specified XML valuetypes descriptions File");
    }
    loadListFromXML(fis);
}

From source file:org.sakaiproject.citation.impl.SakaiOsidLoader.java

/**
 * Get an InputStream for a particular file name - first check the sakai.home area and then 
 * revert to the classpath.//from w w w.ja  v a 2  s .co m
 *
 * This is a utility method used several places.
 */
public static java.io.InputStream getConfigStream(String fileName, Class curClass) {
    String sakaiHome = System.getProperty("sakai.home");
    String filePath = sakaiHome + fileName;

    try {
        java.io.File f = new java.io.File(filePath);
        if (f.exists()) {
            return new java.io.FileInputStream(f);
        }
    } catch (Throwable t) {
        // Not found in the sakai.home area
    }

    if (curClass == null) {
        return null;
    }

    // If there is a class context, load from the class context...
    java.io.InputStream istream = null;

    // Load from the class loader
    istream = curClass.getClassLoader().getResourceAsStream(fileName);
    if (istream != null) {
        return istream;
    }
    // Loading from the class at the data root
    istream = curClass.getResourceAsStream("/data/" + fileName);
    if (istream != null) {
        return istream;
    }
    // Load from the class relative
    istream = curClass.getResourceAsStream(fileName);
    if (istream != null) {
        return istream;
    }
    // Loading from the class at the root
    istream = curClass.getResourceAsStream("/" + fileName);
    if (istream != null) {
        return istream;
    }
    // Loading from the class at the config root
    istream = curClass.getResourceAsStream("/config/" + fileName);

    return istream;
}

From source file:be.iminds.aiolos.ui.CommonServlet.java

/**
 * Reads the <code>templateFile</code> as a resource through the class
 * loader of this class converting the binary data into a string using
 * UTF-8 encoding.//from  w w w .  j  av  a  2  s.  c om
 * <p>
 * If the template file cannot read into a string and an exception is
 * caused, the exception is logged and an empty string returned.
 *
 * @param templateFile The absolute path to the template file to read.
 * @return The contents of the template file as a string or and empty
 *      string if the template file fails to be read.
 *
 * @throws NullPointerException if <code>templateFile</code> is
 *      <code>null</code>
 * @throws RuntimeException if an <code>IOException</code> is thrown reading
 *      the template file into a string. The exception provides the
 *      exception thrown as its cause.
 */
protected final String readTemplateFile(final String templateFile) {
    Class<? extends HttpServlet> clazz = this.getClass();
    InputStream templateStream = clazz.getResourceAsStream(templateFile);
    if (templateStream != null) {
        try {
            String str = IOUtils.toString(templateStream, "UTF-8"); //$NON-NLS-1$
            switch (str.charAt(0)) { // skip BOM
            case 0xFEFF: // UTF-16/UTF-32, big-endian
            case 0xFFFE: // UTF-16, little-endian
            case 0xEFBB: // UTF-8
                return str.substring(1);
            }
            return str;
        } catch (Exception e) {
            // don't use new Exception(message, cause) because cause is 1.4+
            throw new RuntimeException("readTemplateFile: Error loading " + templateFile + ": " + e); //$NON-NLS-1$ //$NON-NLS-2$
        } finally {
            IOUtils.closeQuietly(templateStream);
        }
    }

    // template file does not exist, return an empty string
    Activator.logger.log(LogService.LOG_ERROR,
            "readTemplateFile: File '" + templateFile + "' not found through class " + clazz); //$NON-NLS-1$ //$NON-NLS-2$
    return ""; //$NON-NLS-1$
}

From source file:org.springframework.core.LocalVariableTableParameterNameDiscoverer.java

/**
 * Inspects the target class. Exceptions will be logged and a maker map returned
 * to indicate the lack of debug information.
 *///  ww  w .  j a  v  a2  s .c om
private Map<Member, String[]> inspectClass(Class<?> clazz) {
    InputStream is = clazz.getResourceAsStream(ClassUtils.getClassFileName(clazz));
    if (is == null) {
        // We couldn't load the class file, which is not fatal as it
        // simply means this method of discovering parameter names won't work.
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot find '.class' file for class [" + clazz
                    + "] - unable to determine constructor/method parameter names");
        }
        return NO_DEBUG_INFO_MAP;
    }
    try {
        ClassReader classReader = new ClassReader(is);
        Map<Member, String[]> map = new ConcurrentHashMap<>(32);
        classReader.accept(new ParameterNameDiscoveringVisitor(clazz, map), 0);
        return map;
    } catch (IOException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Exception thrown while reading '.class' file for class [" + clazz
                    + "] - unable to determine constructor/method parameter names", ex);
        }
    } catch (IllegalArgumentException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("ASM ClassReader failed to parse class file [" + clazz
                    + "], probably due to a new Java class file version that isn't supported yet "
                    + "- unable to determine constructor/method parameter names", ex);
        }
    } finally {
        try {
            is.close();
        } catch (IOException ex) {
            // ignore
        }
    }
    return NO_DEBUG_INFO_MAP;
}

From source file:appeng.recipes.loader.RecipeResourceCopier.java

/**
 * Copies a single file inside a folder to the destination.
 *
 * @param destination folder to which the file is copied to
 * @param directory the directory containing the file
 * @param fileName the file to copy/* w ww .  ja v  a 2 s .com*/
 *
 * @throws IOException if copying the file is not possible
 */
private void copyFile(@Nonnull final File destination, @Nonnull final String directory,
        @Nonnull final String fileName) throws IOException {
    assert destination != null;
    assert directory != null;
    assert fileName != null;

    final Class<? extends RecipeResourceCopier> copierClass = this.getClass();
    final InputStream inStream = copierClass.getResourceAsStream('/' + directory + fileName);
    final File outFile = new File(destination, fileName);

    if (!outFile.exists() && inStream != null) {
        FileUtils.copyInputStreamToFile(inStream, outFile);
        inStream.close();
    }
}