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.silverpeas.core.test.rule.DbSetupRule.java

@SuppressWarnings("ConstantConditions")
private Operation loadOperationFromSqlScripts(Class classOfTest, String[] scripts) {
    List<Operation> statements = new ArrayList<>();
    if (scripts != null) {
        for (final String script : scripts) {
            if (FilenameUtils.getExtension(script).toLowerCase().equals("sql")) {
                try (InputStream sqlScriptInput = classOfTest.getResourceAsStream(script)) {
                    if (sqlScriptInput != null) {
                        StringWriter sqlScriptContent = new StringWriter();
                        IOUtils.copy(sqlScriptInput, sqlScriptContent, Charsets.UTF_8);
                        if (sqlScriptContent.toString() != null && !sqlScriptContent.toString().isEmpty()) {
                            String[] sql = sqlScriptContent.toString().split(";");
                            //prepareCleanUpOperation(sql);
                            statements.add(Operations.sql(sql));
                        }// w  w  w .  jav  a 2 s  .com
                    }
                } catch (IOException e) {
                    Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE,
                            "Error while loading the SQL script {0}!", script);
                }
            }
        }
    }
    return Operations.sequenceOf(statements);
}

From source file:org.eclipse.swt.examples.paint.PaintExample.java

/**
 * Loads the image resources.//from www.  j  a va2  s.c  o  m
 */
public void initResources() {
    final Class<PaintExample> clazz = PaintExample.class;
    if (resourceBundle != null) {
        try {
            for (Tool tool2 : tools) {
                Tool tool = tool2;
                String id = tool.group + '.' + tool.name;
                try (InputStream sourceStream = clazz.getResourceAsStream(getResourceString(id + ".image"))) {
                    ImageData source = new ImageData(sourceStream);
                    ImageData mask = source.getTransparencyMask();
                    tool.image = 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:com.googlecode.jsfFlex.renderkit.html.util.JsfFlexResourceImpl.java

@Override
public void processRequestResource(HttpServletResponse httpResponse, String[] requestURISplitted) {

    /*/*from w  w  w .  j ava  2 s .  c  om*/
     * need to get the resource as stream and flush it out using httpResponse
     *  The key should be [3] + [4] where :
     *     [3]   =   name of the packaged class where the resource lives [use it for loading the resource]
     *     [4] =   name of the resource file
     */

    Class resourceClass = null;

    try {
        resourceClass = Class.forName(requestURISplitted[3]);
    } catch (ClassNotFoundException classNotFound) {
        _log.debug("Class Not found for " + requestURISplitted[3], classNotFound);
    }

    StringBuilder resourcePath = new StringBuilder(RESOURCE_DIRECTORY_NAME);
    resourcePath.append("/");

    for (int i = 4; i < requestURISplitted.length; i++) {
        resourcePath.append(requestURISplitted[i]);

        if ((i + 1) < requestURISplitted.length) {
            resourcePath.append("/");
        }
    }

    InputStream resourceStream = resourceClass.getResourceAsStream(resourcePath.toString());

    readInputWriteOutput(resourceStream, httpResponse);

}

From source file:org.apache.felix.webconsole.AbstractWebConsolePlugin.java

private final String readTemplateFile(final Class clazz, final String templateFile) {
    InputStream templateStream = clazz.getResourceAsStream(templateFile);
    if (templateStream != null) {
        try {//  w  ww  . j ava2  s .  c o m
            String str = IOUtils.toString(templateStream, "UTF-8");
            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 (IOException e) {
            // don't use new Exception(message, cause) because cause is 1.4+
            throw new RuntimeException("readTemplateFile: Error loading " + templateFile + ": " + e);
        } finally {
            IOUtils.closeQuietly(templateStream);
        }
    }

    // template file does not exist, return an empty string
    log("readTemplateFile: File '" + templateFile + "' not found through class " + clazz);
    return "";
}

From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

private void createKeyStore(Class realClass, WithKeyStore withKeyStore) {

    try {/*www .  java 2  s  . c o m*/
        RegistryService registryService = createRegistryService(realClass, withKeyStore.tenantId(),
                withKeyStore.tenantDomain());
        ServerConfiguration serverConfigurationService = ServerConfiguration.getInstance();
        serverConfigurationService.init(realClass.getResourceAsStream("/repository/conf/carbon.xml"));
        KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(withKeyStore.tenantId(),
                serverConfigurationService, registryService);
        if (!Proxy.isProxyClass(keyStoreManager.getClass())
                && !keyStoreManager.getClass().getName().contains("EnhancerByMockitoWithCGLIB")) {
            KeyStore keyStore = ReadCertStoreSampleUtil.createKeyStore(getClass());
            org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "primaryKeyStore",
                    keyStore);
            org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "registryKeyStore",
                    keyStore);
        }
        CarbonCoreDataHolder.getInstance().setRegistryService(registryService);
        CarbonCoreDataHolder.getInstance().setServerConfigurationService(serverConfigurationService);
    } catch (Exception e) {
        throw new TestCreationException(
                "Unhandled error while reading cert for test class:  " + realClass.getName(), e);
    }
}

From source file:org.sonar.db.AbstractDbTester.java

public void prepareDbUnit(Class testClass, String... testNames) {
    InputStream[] streams = new InputStream[testNames.length];
    try {/*  w ww .ja  v a  2  s  .c o  m*/
        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);
        db.getCommands().resetPrimaryKeys(db.getDatabase().getDataSource());
    } catch (SQLException e) {
        throw translateException("Could not setup DBUnit data", e);
    } finally {
        for (InputStream stream : streams) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:uk.co.modularaudio.util.spring.SpringComponentHelper.java

public GenericApplicationContext makeAppContext(final String beansResourcePath, final String configResourcePath,
        final String[] additionalBeansResources, final String[] additionalConfigResources)
        throws DatastoreException {
    GenericApplicationContext appContext = null;

    final Class<SpringComponentHelper> thisClass = SpringComponentHelper.class;

    // Do any work needed before we instantiate the context
    for (final SpringContextHelper helper : contextHelpers) {
        try {//from w  w w  .  j  a  v a2s . c o m
            helper.preContextDoThings();
        } catch (final Exception ce) {
            final String msg = "Exception caught calling precontext of helper " + helper.getClass() + ": "
                    + ce.toString();
            log.error(msg, ce);
            // Will halt context creation.
            throw new DatastoreException(msg, ce);
        }
    }

    try {
        final InputStream bIStream = thisClass.getResourceAsStream(beansResourcePath);
        if (bIStream != null) {
            final InputSource bISource = new InputSource(bIStream);

            appContext = new GenericApplicationContext();
            appContext.addBeanFactoryPostProcessor(beanInstantiationList);

            final XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext);

            xbdr.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
            xbdr.loadBeanDefinitions(bISource);

            // And load any additional beans files now we've loaded the "driver"
            if (additionalBeansResources != null && additionalBeansResources.length > 0) {
                for (final String additionalBeansFilename : additionalBeansResources) {
                    InputStream aBiStream = null;
                    InputSource aBiSource = null;
                    try {
                        aBiStream = thisClass.getResourceAsStream(additionalBeansFilename);

                        if (aBiStream != null) {
                            aBiSource = new InputSource(aBiStream);
                            xbdr.loadBeanDefinitions(aBiSource);
                        } else {
                            throw new DatastoreException(
                                    "Failed to load additional services from file: " + additionalBeansFilename);
                        }
                    } finally {
                        if (aBiStream != null) {
                            aBiStream.close();
                        }
                    }
                }
            }

            final BeanDefinition bd = appContext.getBeanDefinition("configurationService");
            final MutablePropertyValues mpvs = bd.getPropertyValues();
            // Push in the configuration file if one needs to be set
            if (configResourcePath != null) {
                mpvs.removePropertyValue(CONFIG_RESOURCE_PATH_PROPERTY);
                mpvs.addPropertyValue(CONFIG_RESOURCE_PATH_PROPERTY, configResourcePath);

            }
            if (additionalConfigResources != null && additionalConfigResources.length > 0) {
                mpvs.removePropertyValue(ADDITIONAL_RESOURCE_PATHS);
                mpvs.addPropertyValue(ADDITIONAL_RESOURCE_PATHS, additionalConfigResources);
            }

            // Do any work needed before we refresh the context
            // Prerefresh
            for (final SpringContextHelper helper : contextHelpers) {
                try {
                    helper.preRefreshDoThings(appContext);
                } catch (final Exception prer) {
                    final String msg = "Exception caught calling prerefresh of helper " + helper.getClass()
                            + ": " + prer.toString();
                    log.error(msg, prer);
                    // Will halt context creation
                    throw new DatastoreException(msg, prer);
                }
            }

            appContext.refresh();

        } else {
            // Didn't find the beans file
            final String msg = "Unable to find beans file: " + beansResourcePath;
            log.error(msg);
            throw new DatastoreException(msg);
        }
    } catch (final Exception e) {
        final String msg = "Exception caught setting up app context: " + e.toString();
        log.error(msg, e);
        throw new DatastoreException(msg, e);
    }

    // Perform a GC pass here to clean up before things are launched post refresh
    Runtime.getRuntime().gc(); // NOPMD by dan on 30/07/15 15:00

    // Do any work needed after we refresh the context
    // Post refresh calls
    for (final SpringContextHelper helper : contextHelpers) {
        try {
            helper.postRefreshDoThings(appContext, beanInstantiationList);
        } catch (final Exception pre) {
            final String msg = "Exception caught calling postrefresh of helper " + helper.getClass() + ": "
                    + pre.toString();
            log.error(msg, pre);
            // Will halt context creation
            throw new DatastoreException(msg, pre);
        }
    }

    return appContext;
}

From source file:org.gvnix.support.MessageBundleUtilsImpl.java

/**
 * Copy properties associated with the given class to the message bundle of
 * given language.//from w w  w  .j  av a  2s . co  m
 * <p/>
 * Note that properties to add are taken from messages[_xx].properties files
 * and added to messages[_xx].properties in the destination project.
 * <p/>
 * <strong>This method doesn't check if messages[_xx].properties file exist
 * in the add-on invoking it</strong>
 * 
 * @param language Language locale as string (en, es, ca, ...)
 * @param invokingClass Class of the Add-on invoking this method. It's
 *        needed in order to load local resources
 * @param propFileOperations
 * @param projectOperations
 * @param fileManager
 */
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addPropertiesToMessageBundle(String language, Class invokingClass,
        PropFileOperations propFileOperations, ProjectOperations projectOperations, FileManager fileManager) {
    Properties properties = new Properties();
    LogicalPath webappPath = getWebProjectUtils().getWebappPath(projectOperations);

    String sourcePropertyFile = "/".concat(invokingClass.getPackage().getName()).replace('.', '/');

    // Take "en" as default language
    String targetFilePath = "/WEB-INF/i18n/messages.properties";
    String targetFile = projectOperations.getPathResolver().getIdentifier(webappPath, targetFilePath);

    try {
        if (language.equals("en")) {
            sourcePropertyFile = sourcePropertyFile.concat("/messages.properties");
            properties.load(invokingClass.getResourceAsStream(sourcePropertyFile));
        } else {
            targetFilePath = "/WEB-INF/i18n/messages_".concat(language).concat(".properties");
            targetFile = projectOperations.getPathResolver().getIdentifier(webappPath, targetFilePath);

            sourcePropertyFile = sourcePropertyFile.concat("/messages_".concat(language).concat(".properties"));
            properties.load(invokingClass.getResourceAsStream(sourcePropertyFile));
        }

        if (fileManager.exists(targetFile)) {
            propFileOperations.addProperties(webappPath, targetFilePath,
                    new HashMap<String, String>((Map) properties), true, true);
        } else {
            LOGGER.warning(targetFile.concat(" file doesn't exist in project."));
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE,
                "Message properties for language \"".concat(language).concat("\" can't be loaded"));
    }
}

From source file:org.sonar.db.AbstractDbTester.java

public void assertDbUnitTable(Class testClass, String filename, String table, String... columns) {
    IDatabaseConnection connection = dbUnitConnection();
    try {/* w ww  . j  a v a  2s  .  c om*/
        IDataSet dataSet = connection.createDataSet();
        String path = "/" + testClass.getName().replace('.', '/') + "/" + filename;
        IDataSet expectedDataSet = dbUnitDataSet(testClass.getResourceAsStream(path));
        ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns);
        ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table),
                columns);
        Assertion.assertEquals(filteredExpectedTable, filteredTable);
    } catch (DatabaseUnitException e) {
        fail(e.getMessage());
    } catch (SQLException e) {
        throw translateException("Error while checking results", e);
    } finally {
        closeQuietly(connection);
    }
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Load properties from classpath.//from  ww w.j  a  v  a  2s . c  o m
 * 
 * @param clasz
 *            Class in the same package as the properties file - Cannot be
 *            <code>null</code>.
 * @param filename
 *            Name of the properties file (without path) - Cannot be
 *            <code>null</code>.
 * 
 * @return Properties.
 */
public static Properties loadProperties(final Class clasz, final String filename) {
    checkNotNull("clasz", clasz);
    checkNotNull("filename", filename);

    final String path = getPackagePath(clasz);
    final String resPath = "/" + path + "/" + filename;
    try {
        final Properties props = new Properties();
        final InputStream inStream = clasz.getResourceAsStream(resPath);
        if (inStream == null) {
            throw new IllegalArgumentException("Resource '" + resPath + "' was not found!");
        }
        try {
            props.load(inStream);
        } finally {
            inStream.close();
        }
        return props;
    } catch (final IOException ex) {
        throw new RuntimeException(ex);
    }
}