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.sonar.core.persistence.TestDatabase.java

public void assertDbUnit(Class testClass, String filename, String... tables) {
    IDatabaseConnection connection = null;
    try {/*  ww w.  j  a  v a2s  .c o m*/
        connection = dbUnitConnection();
        IDataSet dataSet = connection.createDataSet();
        String path = "/" + testClass.getName().replace('.', '/') + "/" + filename;
        IDataSet expectedDataSet = dbUnitDataSet(testClass.getResourceAsStream(path));
        for (String table : tables) {
            DiffCollectingFailureHandler diffHandler = new DiffCollectingFailureHandler();

            Assertion.assertEquals(expectedDataSet.getTable(table), dataSet.getTable(table), diffHandler);
            // Evaluate the differences and ignore some column values
            List diffList = diffHandler.getDiffList();
            for (Object o : diffList) {
                Difference diff = (Difference) o;
                if (!"[ignore]".equals(diff.getExpectedValue())) {
                    throw new DatabaseUnitException(diff.toString());
                }
            }
        }
    } catch (DatabaseUnitException e) {
        fail(e.getMessage());
    } catch (Exception e) {
        throw translateException("Error while checking results", e);
    } finally {
        closeQuietly(connection);
    }
}

From source file:org.ebayopensource.twin.Application.java

/**
 * Upload a file to the host machine from the given resource.
 * The resource is evaluated relative to the given class, and the file extension is preserved.
 * E.g. if you pass in resource="bar.csv", context=com.ebay.package.Foo.class, 
 * then the uploaded resource will be "/com/ebay/package/bar.csv" and given a name ending in ".csv". 
 * If context is null, the resource will be forced to be absolute.
 * @throws IOException //from ww  w  . java2  s.co m
 * @throws TwinException 
 */
public Attachment upload(String resource, Class<?> context) throws TwinException, IOException {
    if (context == null) {
        context = Application.class;
        if (!resource.startsWith("/"))
            resource = "/" + resource;
    }
    return upload(context.getResourceAsStream(resource), resource);
}

From source file:org.eclipse.sw360.datahandler.common.CommonUtils.java

public static Optional<byte[]> loadResource(Class<?> clazz, String resourceFilePath,
        boolean useSystemResourses) {
    if (isNullOrEmpty(resourceFilePath)) {
        return Optional.empty();
    }//w  w  w  . ja  va2 s  .  c om
    if (useSystemResourses) {
        File systemResourceFile = new File(SYSTEM_CONFIGURATION_PATH, resourceFilePath);
        if (systemResourceFile.exists()) {
            try (InputStream resourceAsStream = new FileInputStream(systemResourceFile.getPath())) {
                if (resourceAsStream == null) {
                    throw new IOException("cannot open " + systemResourceFile.getPath());
                }
                return Optional.of(IOUtils.toByteArray(resourceAsStream));
            } catch (IOException e) {
                getLogger(clazz).error("Error opening resources " + systemResourceFile.getPath() + ".", e);
            }
        }
    }

    try (InputStream resourceAsStream = clazz.getResourceAsStream(resourceFilePath)) {
        if (resourceAsStream == null)
            throw new IOException("cannot open " + resourceFilePath);
        return Optional.of(IOUtils.toByteArray(resourceAsStream));
    } catch (IOException e) {
        getLogger(clazz).error("Error opening resources " + resourceFilePath + ".", e);
    }
    return Optional.empty();
}

From source file:com.jwebmp.core.htmlbuilder.javascript.JavaScriptPart.java

/**
 * Returns the template as a string//w  w  w . j  a v  a  2s . co  m
 *
 * @param templateName
 *       The file without .min.js or .js attached to it
 * @param fileName
 *
 * @return The string for the file
 */
public StringBuilder getFileTemplate(String templateName, String fileName, boolean alwaysRefresh) {
    StringBuilder template = FileTemplates.getTemplateScripts().get(templateName);
    if (template == null || alwaysRefresh) {
        try {
            String templateFileName = fileName;
            if (!(fileName.contains(".html") || fileName.contains(".htm") || fileName.contains(".js")
                    || fileName.contains(".css") || fileName.contains(".min") || fileName.contains(".txt"))) {
                templateFileName += ".js";
            }
            if (templateFileName.endsWith(".min")) {
                templateFileName = templateFileName + ".js";
            }
            Class clazz = getClass();
            InputStream is = clazz.getResourceAsStream(templateFileName);
            String contents = IOUtils.toString(is, StaticStrings.UTF8_CHARSET);
            setTemplateScript(templateName, new StringBuilder(contents));
            is.close();
        } catch (FileNotFoundException ex) {
            log.log(Level.SEVERE, "[Error]-[unable to find template file];[TemplateFile]-[" + templateName
                    + "];[TemplatePath]-[" + getClass().getResource(templateName).getPath() + "]", ex);
        } catch (IOException ex) {
            log.log(Level.SEVERE, "Unable to read file contents jwangular template File", ex);
        } catch (NullPointerException npe) {
            log.log(Level.SEVERE, "template file [" + fileName + "(.js)] not found.", npe);
        } catch (Exception npe) {
            log.log(Level.SEVERE, "Exception Rendering Template", npe);
        }
    }
    return FileTemplates.getTemplateScripts().get(templateName);
}

From source file:org.radeox.macro.book.TextFileUrlMapper.java

public TextFileUrlMapper(Class klass) {
    services = new HashMap();

    boolean fileNotFound = false;
    try {//from   w  w w  . j  a  v  a  2 s  .c  o  m
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(getFileName())));
        addMapping(br);
    } catch (IOException e) {
        log.warn("Unable to read " + getFileName()); //$NON-NLS-1$
        fileNotFound = true;
    }

    if (fileNotFound) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(klass.getResourceAsStream("/" + getFileName()))); //$NON-NLS-1$
            addMapping(br);
        } catch (Exception e) {
            log.warn("Unable to read /" + getFileName() + " from jar"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
}

From source file:org.apache.axis2.wsdl.codegen.writer.FileWriter.java

/** Loads the template. */
public void loadTemplate() throws CodeGenerationException {
    // the default behavior for the class writers is to use the property map from the languge specific types
    // The properties are arranged in the following order
    // <lang-name>.* .template=<write-class>,<template-name>

    //first get the language specific property map
    Class clazz = this.getClass();
    Map languageSpecificPropertyMap = (Map) ConfigPropertyFileLoader.getLanguageSpecificPropertiesMap()
            .get(this.language);
    if (languageSpecificPropertyMap == null) {
        throw new CodeGenerationException(CodegenMessages.getMessage("writer.noLangPropertiesExtension"));
    }/*from  w w w . java 2 s . c  o m*/

    String templateName = findTemplate(languageSpecificPropertyMap);
    if (templateName != null) {
        this.xsltStream = clazz.getResourceAsStream(templateName);
    } else {
        throw new CodeGenerationException(CodegenMessages.getMessage("writer.templateMissing"));
    }

}

From source file:org.eclipse.swt.examples.browserexample.BrowserExample.java

/**
 * Loads the resources//from   ww  w . j  a va  2s  . c o m
 */
void initResources() {
    final Class<? extends BrowserExample> clazz = this.getClass();
    if (resourceBundle != null) {
        try {
            if (images == null) {
                images = new Image[imageLocations.length];
                for (int i = 0; i < imageLocations.length; ++i) {
                    try (InputStream sourceStream = clazz.getResourceAsStream(imageLocations[i])) {
                        ImageData source = new ImageData(sourceStream);
                        ImageData mask = source.getTransparencyMask();
                        images[i] = new Image(null, source, mask);
                    }
                }
            }
            return;
        } catch (Throwable t) {
        }
    }
    String error = (resourceBundle != null) ? getResourceString("error.CouldNotLoadResources")
            : "Unable to load resources";
    freeResources();
    throw new RuntimeException(error);
}

From source file:org.sonar.core.persistence.DbTester.java

public void assertDbUnit(Class testClass, String filename, String... tables) {
    IDatabaseConnection connection = null;
    try {/*from   ww w. java2s. c  o m*/
        connection = dbUnitConnection();

        IDataSet dataSet = connection.createDataSet();
        String path = "/" + testClass.getName().replace('.', '/') + "/" + filename;
        IDataSet expectedDataSet = dbUnitDataSet(testClass.getResourceAsStream(path));
        for (String table : tables) {
            DiffCollectingFailureHandler diffHandler = new DiffCollectingFailureHandler();

            Assertion.assertEquals(expectedDataSet.getTable(table), dataSet.getTable(table), diffHandler);
            // Evaluate the differences and ignore some column values
            List diffList = diffHandler.getDiffList();
            for (Object o : diffList) {
                Difference diff = (Difference) o;
                if (!"[ignore]".equals(diff.getExpectedValue())) {
                    throw new DatabaseUnitException(diff.toString());
                }
            }
        }
    } catch (DatabaseUnitException e) {
        fail(e.getMessage());
    } catch (Exception e) {
        throw translateException("Error while checking results", e);
    } finally {
        closeQuietly(connection);
    }
}

From source file:com.adito.agent.client.gui.swt.SWTSystemTrayGUI.java

protected Image loadImage(Class clazz, String path) {
    InputStream stream = clazz.getResourceAsStream(path);
    return stream == null ? null : new Image(display, stream);
}

From source file:org.sonar.core.persistence.DbTester.java

public void prepareDbUnit(Class testClass, String... testNames) {
    InputStream[] streams = new InputStream[testNames.length];
    try {/*w  w w .  ja  v  a2s.co  m*/
        // Purge previous data
        commands.truncateDatabase(db.getDataSource());

        for (int i = 0; i < testNames.length; i++) {
            String path = "/" + testClass.getName().replace('.', '/') + "/" + testNames[i];
            streams[i] = testClass.getResourceAsStream(path);
            if (streams[i] == null) {
                throw new IllegalStateException("DbUnit file not found: " + path);
            }
        }

        prepareDbUnit(streams);
        commands.resetPrimaryKeys(db.getDataSource());
    } catch (SQLException e) {
        throw translateException("Could not setup DBUnit data", e);
    } finally {
        for (InputStream stream : streams) {
            IOUtils.closeQuietly(stream);
        }
    }
}