Example usage for org.springframework.core.io Resource getInputStream

List of usage examples for org.springframework.core.io Resource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream for the content of an underlying resource.

Usage

From source file:org.powertac.samplebroker.core.BrokerPropertiesService.java

/**
 * Loads the properties from classpath, default config file,
 * and user-specified config file, just in case it's not already been
 * loaded. This is done when properties are first requested, to ensure
 * that the logger has been initialized. Because the CompositeConfiguration
 * treats its config sources in FIFO order, this should be called <i>after</i>
 * any user-specified config is loaded.//from w  w  w. jav  a2 s  .co m
 */
void lazyInit() {
    // only do this once
    if (initialized)
        return;
    initialized = true;

    // find and load the default properties file
    log.debug("lazyInit");
    try {
        File defaultProps = new File("broker.properties");
        log.info("adding " + defaultProps.getName());
        config.addConfiguration(new PropertiesConfiguration(defaultProps));
    } catch (Exception e1) {
        log.warn("broker.properties not found: " + e1.toString());
    }

    // set up the classpath props
    try {
        Resource[] xmlResources = context.getResources("classpath*:config/properties.xml");
        for (Resource xml : xmlResources) {
            if (validXmlResource(xml)) {
                log.info("loading config from " + xml.getURI());
                XMLConfiguration xconfig = new XMLConfiguration();
                xconfig.load(xml.getInputStream());
                config.addConfiguration(xconfig);
            }
        }
        Resource[] propResources = context.getResources("classpath*:config/*.properties");
        for (Resource prop : propResources) {
            if (validPropResource(prop)) {
                if (null == prop) {
                    log.error("Null resource");
                }
                log.info("loading config from " + prop.getURI());
                PropertiesConfiguration pconfig = new PropertiesConfiguration();
                pconfig.load(prop.getInputStream());
                config.addConfiguration(pconfig);
            }
        }
    } catch (ConfigurationException e) {
        log.error("Problem loading configuration: " + e.toString());
    } catch (Exception e) {
        log.error("Error loading configuration: " + e.toString());
    }

    // set up the configurator
    configurator.setConfiguration(config);
}

From source file:org.atomserver.core.validators.RelaxNGValidator.java

public void setSchemaLocation(final Resource schemaLocation) {
    validationDriver = new ThreadLocal<ValidationDriver>() {

        protected ValidationDriver initialValue() {
            ValidationDriver validationDriver = new ValidationDriver(ERROR_HANDLER_PROPERTY_MAP,
                    CompactSchemaReader.getInstance());
            try {
                validationDriver.loadSchema(new InputSource(schemaLocation.getInputStream()));
                return validationDriver;
            } catch (Exception e) {
                log.error("exception loading schema", e);
                throw new RuntimeException("exception loading schema", e);
            }//  ww w. j av  a 2  s  .c  o  m
        }
    };
    validationDriver.get();
}

From source file:com.hp.security.jauth.core.filter.SystemInit.java

public void initMessageProperties(ResourcePatternResolver resolver) throws IOException {
    //finding system messages.
    Resource jauthCoreMessages = resolver.getResource("jauth-core-message.properties");
    Properties jauthCoreProp = new Properties();
    jauthCoreProp.load(jauthCoreMessages.getInputStream());
    Set<Object> jauthCoreKeys = jauthCoreProp.keySet();
    for (Object k : jauthCoreKeys) {
        String key = k.toString();
        String value = jauthCoreProp.get(key).toString();
        MessageContext.messages.put(key, value);
    }/*from w ww. jav  a2s  .  c  om*/
    log.info("loaded jauth core messages.");

    try {
        Resource jauthAdminMessages = resolver.getResource("jauth-admin-message.properties");
        Properties jauthAdminProp = new Properties();
        jauthAdminProp.load(jauthAdminMessages.getInputStream());
        Set<Object> jauthAdminKeys = jauthAdminProp.keySet();
        for (Object k : jauthAdminKeys) {
            String key = k.toString();
            String value = jauthAdminProp.get(key).toString();
            MessageContext.messages.put(key, value);
        }
        log.info("loaded jauth admin messages.");
    } catch (FileNotFoundException e) {
        log.info("didn't find any jauth admin messages.");
    }

    try {
        Resource jauthSoapMessages = resolver.getResource("jauth-soap-message.properties");
        Properties jauthSoapProp = new Properties();
        jauthSoapProp.load(jauthSoapMessages.getInputStream());
        Set<Object> jauthSoapKeys = jauthSoapProp.keySet();
        for (Object k : jauthSoapKeys) {
            String key = k.toString();
            String value = jauthSoapProp.get(key).toString();
            MessageContext.messages.put(key, value);
        }
        log.info("loaded jauth soap messages.");
    } catch (FileNotFoundException e) {
        log.info("didn't find any jauth soap messages.");
    }

    //finding custom messages.
    try {
        Resource customMessages = resolver.getResource("message.properties");
        Properties customProp = new Properties();
        customProp.load(customMessages.getInputStream());
        Set<Object> customKeys = customProp.keySet();
        for (Object k : customKeys) {
            String key = k.toString();
            String value = customProp.get(key).toString();
            MessageContext.messages.put(key, value);
        }
        log.info("loaded jauth custom messages.");
    } catch (FileNotFoundException e) {
        log.info("didn't find any jauth custom messages.");
    }

    //finding jauth properties
    try {
        Resource jauth = resolver.getResource("jauth.properties");
        Properties jauthProp = new Properties();
        jauthProp.load(jauth.getInputStream());
        authActive = jauthProp.get(Constants.CONFIG_KEY_ACTIVE) == null
                ? configService.findByKey(Constants.CONFIG_KEY_ACTIVE).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_ACTIVE).toString();
        authorizationCheck = jauthProp.get(Constants.CONFIG_AUTHORIZATION_CHECK) == null
                ? configService.findByKey(Constants.CONFIG_AUTHORIZATION_CHECK).getValue()
                : jauthProp.get(Constants.CONFIG_AUTHORIZATION_CHECK).toString();
        arithmeticIndex = jauthProp.get(Constants.CONFIG_KEY_ARITHMETIC) == null
                ? configService.findByKey(Constants.CONFIG_KEY_ARITHMETIC).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_ARITHMETIC).toString();
        sessionID = jauthProp.get(Constants.CONFIG_KEY_SESSION_ID) == null
                ? configService.findByKey(Constants.CONFIG_KEY_SESSION_ID).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_SESSION_ID).toString();
        sessionACL = jauthProp.get(Constants.CONFIG_KEY_SESSION_ACL) == null
                ? configService.findByKey(Constants.CONFIG_KEY_SESSION_ACL).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_SESSION_ACL).toString();
        rules = jauthProp.get(Constants.CONFIG_KEY_RULES) == null
                ? configService.findByKey(Constants.CONFIG_KEY_RULES).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_RULES).toString();
        accessiblePage = jauthProp.get(Constants.CONFIG_KEY_ACCESSIBLE_PAGE) == null
                ? configService.findByKey(Constants.CONFIG_KEY_ACCESSIBLE_PAGE).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_ACCESSIBLE_PAGE).toString();
        accessibleHost = jauthProp.get(Constants.CONFIG_KEY_ACCESSIBLE_HOST) == null
                ? configService.findByKey(Constants.CONFIG_KEY_ACCESSIBLE_HOST).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_ACCESSIBLE_HOST).toString();
        exceptionPage = jauthProp.get(Constants.CONFIG_KEY_EXCEPTION) == null
                ? configService.findByKey(Constants.CONFIG_KEY_EXCEPTION).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_EXCEPTION).toString();
        loginPage = jauthProp.get(Constants.CONFIG_KEY_LOGIN_PAGE) == null
                ? configService.findByKey(Constants.CONFIG_KEY_LOGIN_PAGE).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_LOGIN_PAGE).toString();
        soapEnabled = jauthProp.get(Constants.CONFIG_KEY_SOAP_ENABLED) == null
                ? configService.findByKey(Constants.CONFIG_KEY_SOAP_ENABLED).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_SOAP_ENABLED).toString();
        protectWSDL = jauthProp.get(Constants.CONFIG_KEY_PROTECT_WSDL) == null
                ? configService.findByKey(Constants.CONFIG_KEY_PROTECT_WSDL).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_PROTECT_WSDL).toString();
        dbLogEnabled = jauthProp.get(Constants.CONFIG_KEY_DB_LOG_ENABLED) == null
                ? configService.findByKey(Constants.CONFIG_KEY_DB_LOG_ENABLED).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_DB_LOG_ENABLED).toString();
        logPath = jauthProp.get(Constants.CONFIG_KEY_LOG_PATH) == null
                ? configService.findByKey(Constants.CONFIG_KEY_LOG_PATH).getValue()
                : jauthProp.get(Constants.CONFIG_KEY_LOG_PATH).toString();
        if (logPath.length() > 0) {
            File logDir = new File(logPath);
            if (!logDir.exists()) {
                logDir.mkdirs();
            }
        }
        log.info("loaded jauth.properties.");
    } catch (FileNotFoundException e) {
        log.info("didn't find jauth.properties.");
    }
}

From source file:org.codehaus.grails.struts.action.ServletContextWrapper.java

public InputStream getResourceAsStream(String name) {
    if (!application.isWarDeployed() && name.equals("/WEB-INF/web.xml")) {
        BuildSettings settings = BuildSettingsHolder.getSettings();
        try {/*from w ww .  j  a v  a 2 s. co m*/
            Resource resource = new FileSystemResource(
                    settings.getResourcesDir().getAbsolutePath() + "/web.xml");
            if (resource.exists()) {
                return resource.getInputStream();
            } else {
                return null;
            }
        } catch (IOException e) {
            adaptee.log(e.getMessage(), e);
            return null;
        }

    } else {
        return adaptee.getResourceAsStream(name);
    }
}

From source file:org.carewebframework.api.alias.AliasTypeRegistry.java

/**
 * Load aliases from a property file.//from ww w . j  a v a  2 s  .  co m
 * 
 * @param applicationContext The application context.
 * @param propertyFile A property file.
 */
private void loadAliases(ApplicationContext applicationContext, String propertyFile) {
    if (propertyFile.isEmpty()) {
        return;
    }

    Resource[] resources;

    try {
        resources = applicationContext.getResources(propertyFile);
    } catch (IOException e) {
        log.error("Failed to locate alias property file: " + propertyFile, e);
        return;
    }

    for (Resource resource : resources) {
        if (!resource.exists()) {
            log.info("Did not find alias property file: " + resource.getFilename());
            continue;
        }

        InputStream is = null;

        try {
            is = resource.getInputStream();
            Properties props = new Properties();
            props.load(is);

            for (Entry<Object, Object> entry : props.entrySet()) {
                try {
                    register((String) entry.getKey(), (String) entry.getValue());
                    entryCount++;
                } catch (Exception e) {
                    log.error("Error registering alias for '" + entry.getKey() + "'.", e);
                }
            }

            fileCount++;
        } catch (IOException e) {
            log.error("Failed to load alias property file: " + resource.getFilename(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:net.sf.jabb.util.db.StartAndStopSQL.java

/**
 * Execute SQL statements stored in a resource. RuntimeException will be thrown if SQLException was caught.
 * @param resource the resource where SQL statements are stored
 *///from w w w .j av  a  2 s. c om
protected void executeSqlResource(String resource) {
    Resource sqlResource = context.getResource(resource);
    InputStream in = null;
    String sql = null;
    try {
        in = sqlResource.getInputStream();
        sql = IOUtils.toString(in);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to get SQL (" + ioe.getMessage() + ") from: " + resource, ioe);
    } finally {
        IOUtils.closeQuietly(in);
    }
    if (StringUtils.isNotBlank(sql)) {
        executeSQL(sql);
    }
}

From source file:org.obiba.onyx.spring.context.OnyxMessageSourceFactoryBean.java

protected MessageSource loadJarBundles() throws IOException {
    ResourcePatternResolver resolver = (ResourcePatternResolver) this.resourceLoader;

    String bundlePattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "META-INF/" + MESSAGES_BUNDLENAME
            + "*" + MESSAGES_PROPERTIES_SUFFIX;

    Resource[] messageResources = resolver.getResources(bundlePattern);

    StaticMessageSource sms = new StaticMessageSource();
    for (int i = 0; i < messageResources.length; i++) {
        Resource resource = messageResources[i];
        Locale locale = extractLocale(resource, MESSAGES_PROPERTIES_SUFFIX);
        log.debug("Found module bundle resource {} with locale {}", resource.getDescription(), locale);

        Properties props = new Properties();
        props.load(resource.getInputStream());
        sms.addMessages(Maps.fromProperties(props), locale);
    }/*w w  w .  ja v  a2 s. c  om*/
    return sms;
}

From source file:net.sf.jabb.util.db.StartAndStopSQL.java

/**
 * Check if the database is in a specific condition by checking the result of a SQL statement loaded as a resource.
 * @param resource  the resource containing the SQL statement that would return a number
 * @return true if the returned number is greater than 0
 */// w  w w  .  j  a v  a2  s.c om
protected boolean isInConditionResource(String resource) {
    Resource sqlResource = context.getResource(resource);
    InputStream in = null;
    String sql = null;
    try {
        in = sqlResource.getInputStream();
        sql = IOUtils.toString(in);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to get condition SQL (" + ioe.getMessage() + ") from: " + resource,
                ioe);
    } finally {
        IOUtils.closeQuietly(in);
    }
    if (StringUtils.isNotBlank(sql)) {
        return isInCondition(sql);
    } else {
        return true;
    }
}

From source file:com.dvidder.service.AccountService.java

@Transactional
public byte[] getProfilePictureForUsername(String username) throws IOException {
    Account account = accountRepository.findByUsername(username);
    if (account.getProfilePicture().isDefaultPic()) {

        byte[] imgData = new byte[5000];
        Resource resource = new ClassPathResource("static/img/default-profile-pic.png");
        if (!resource.exists()) {
            System.out.println("RESOURCE DOESN'T EXIST");
        } else {/*ww w  . j ava2s  .c om*/
            System.out.println("YES, RESOURCE EXISTS");

            System.out.println("resource content length: " + resource.contentLength());
        }

        imgData = IOUtils.toByteArray(resource.getInputStream());
        System.out.println("byte array length: " + imgData.length);
        return imgData;
    }
    return accountRepository.findByUsername(username).getProfilePicture().getImageData();
}