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.carewebframework.ui.command.CommandShortcuts.java

public CommandShortcuts(Resource mappings) {
    put("help", "#f1");
    String filename = " '" + mappings.getFilename() + "'.";
    InputStream is;/*from  w w  w .j  av  a  2 s  .  c  om*/

    try {
        if (!mappings.exists()) {
            log.info("No shortcut mappings found at" + filename);
            return;
        }

        is = mappings.getInputStream();

        if (is != null) {
            load(is);
            is.close();
            log.info("Shortcut mappings loaded from" + filename);
        }
    } catch (IOException e) {
        log.error("Error loading shortcut mappings from" + filename, e);
    }
}

From source file:mvctest.web.TestController.java

@RequestMapping(value = "/appCtxGetResourceGetInputStream")
public void appCtxGetResourceGetInputStream(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String path = getRequiredStringParameter(request, "path");
    String output = "<html><head><title>Testing path [" + path + "]</title></head><body>";
    Resource resource = this.resourceLoader.getResource(path);
    InputStream resourceStream = resource.getInputStream();
    output += "From ApplicationContext/ResourceLoader's getResource().getInputStream() for [" + path
            + "]: first char: [" + (char) resourceStream.read() + "]";
    output += "</body></html>";
    response.getWriter().write(output);/*from   w ww .j  a v a2 s .c om*/
}

From source file:org.activiti.engine.impl.cfg.spring.ProcessEngineFactoryBean.java

private void deploy(DeploymentBuilder deploymentBuilder, Resource resource, String name) throws IOException {
    if (name.endsWith(".zip") || name.endsWith(".jar")) {
        deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
    } else {//from  w ww  .  j  a va2 s.  c om
        deploymentBuilder.addInputStream(name, resource.getInputStream());
    }
    deploymentBuilder.deploy();
}

From source file:de.codecentric.boot.admin.actuate.LogfileMvcEndpoint.java

@RequestMapping(method = RequestMethod.GET)
public void invoke(HttpServletResponse response) throws IOException {
    if (!isAvailable()) {
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return;//from w  w  w  . j  av a 2s  .c  o m
    }

    Resource file = new FileSystemResource(logfile);
    response.setContentType(MediaType.TEXT_PLAIN_VALUE);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
    FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());
}

From source file:com.haulmont.cuba.restapi.RestServicePermissions.java

protected void init() {
    String configName = AppContext.getProperty(CUBA_REST_SERVICES_CONFIG_PROP_NAME);
    StrTokenizer tokenizer = new StrTokenizer(configName);
    for (String location : tokenizer.getTokenArray()) {
        Resource resource = resources.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                loadConfig(Dom4j.readDocument(stream).getRootElement());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(stream);
            }/*www .  jav a2  s.com*/
        } else {
            log.warn("Resource " + location + " not found, ignore it");
        }
    }
}

From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java

private List<Dependency> loadFromJSON(Resource licenseFile) throws Exception {
    List<Dependency> deps = new LinkedList<>();
    ObjectMapper om = new ObjectMapper();
    JsonNode licenseRoot = om.readTree(licenseFile.getInputStream());
    Iterator<String> entryNames = licenseRoot.fieldNames();
    while (entryNames.hasNext()) {
        String entryName = entryNames.next();
        JsonNode licenceNode = licenseRoot.get(entryName);

        String[] npmNameFragments = StringUtils.split(entryName, '@');
        final String groupId = "npm";
        final String artifactId = npmNameFragments[0];
        final String version = npmNameFragments[1];

        final String lName = getFieldValue(licenceNode, "licenses");
        final String lUrl = getFieldValue(licenceNode, "repository");
        final String lDistro = "repo";
        String comments = "";

        deps.add(new Dependency(groupId, artifactId, version, new License(lName, lUrl, lDistro, comments)));
    }//w w w  .  j av a  2  s  .  c  o m
    Collections.sort(deps);
    return deps;
}

From source file:org.codehaus.griffon.plugins.AstPluginDescriptorReader.java

public GriffonPluginInfo readPluginInfo(Resource pluginLocation) {
    CompilationUnit compilationUnit = new CompilationUnit(classLoader);
    BasicGriffonPluginInfo pluginInfo = new BasicGriffonPluginInfo(pluginLocation);

    try {/*from   ww  w.j av  a2s  .c  om*/
        compilationUnit.addSource("dummy", pluginLocation.getInputStream());
        compilationUnit.addPhaseOperation(new PluginReadingPhaseOperation(pluginInfo), Phases.CONVERSION);
        compilationUnit.compile(Phases.CONVERSION);
        return pluginInfo;
    } catch (IOException e) {
        throw new PluginException("Cannot read plugin info: " + e.getMessage());
    }
}

From source file:org.springmodules.validation.bean.conf.loader.xml.AbstractXmlBeanValidationConfigurationLoader.java

/**
 * todo: document/*from   w ww  . j  a v a2 s.  com*/
 *
 * @see org.springmodules.validation.bean.conf.loader.xml.AbstractResourceBasedBeanValidationConfigurationLoader#loadConfigurations(org.springframework.core.io.Resource)
 */
protected final Map loadConfigurations(Resource resource) {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resource.getInputStream());
        return loadConfigurations(document, resource.getDescription());
    } catch (IOException ioe) {
        logger.error("Could not read resource '" + resource.getDescription() + "'", ioe);
        throw new ResourceConfigurationLoadingException(resource, ioe);
    } catch (ParserConfigurationException pce) {
        logger.error("Could not parse xml resource '" + resource.getDescription() + "'", pce);
        throw new ResourceConfigurationLoadingException(resource, pce);
    } catch (SAXException se) {
        logger.error("Could not parse xml resource '" + resource.getDescription() + "'", se);
        throw new ResourceConfigurationLoadingException(resource, se);
    } catch (Throwable t) {
        logger.error("Could not parse xml resource '" + resource.getDescription() + "'", t);
        throw new ResourceConfigurationLoadingException(resource, t);
    }
}

From source file:com.photon.phresco.configuration.XmlPropertyPlaceholderConfigurer.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (this.locations != null) {
        Properties mergedProps = new Properties();
        for (int i = 0; i < this.locations.length; i++) {
            Resource location = this.locations[i];
            InputStream in = null;
            try {
                in = location.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();/*from   ww w. jav a 2s  . c om*/
            }
            try {
                if (location.getFilename().endsWith(".xml")) {
                    // this.getClass().getClassLoader().getResourceAsStream(getLocation());
                    ConfigReader reader = new ConfigReader(in);
                    String envName = System.getProperty(serverEnvironment);
                    if (envName == null) {
                        envName = reader.getDefaultEnvName();
                    }
                    List<Configuration> configByEnv = reader.getConfigByEnv(envName);
                    for (Configuration config : configByEnv) {
                        if (this.configurationTypes != null) {
                            for (i = 0; i < this.configurationTypes.length; i++) {
                                Resource configurationTypes = this.configurationTypes[i];
                                String configTypes = configurationTypes.getFilename();

                                String[] splitStrings = configTypes.split(",");
                                List<String> allowedTokens = Arrays.asList(splitStrings);

                                if (allowedTokens.contains(config.getType())) {
                                    mergedProps = config.getProperties();
                                }
                            }
                        }
                        // props.list(System.out);
                    }
                } else {
                    if (this.fileEncoding != null) {
                        this.propertiesPersister.load(mergedProps,
                                new InputStreamReader(in, this.fileEncoding));
                    } else {
                        this.propertiesPersister.load(mergedProps, in);
                    }
                }

            } catch (IOException ex) {
                if (this.ignoreResourceNotFound) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
                    }
                } else {
                    try {
                        throw ex;
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        // Convert the merged properties, if necessary.
        convertProperties(mergedProps);
        // Let the subclass process the properties.
        processProperties(beanFactory, mergedProps);
    }
}

From source file:com.glaf.activiti.spring.SpringProcessEngineConfigurationBean.java

@Override
protected void initSqlSessionFactory() {
    logger.info("-------------------------------------------");
    logger.info("-------------initSqlSessionFactory()-------");
    logger.info("sqlSessionFactory:" + sqlSessionFactory);
    logger.info("transactionFactory:" + transactionFactory);
    if (sqlSessionFactory == null) {
        InputStream inputStream = null;
        try {//from   w ww.j  a  v a  2s . c  o m
            if (configLocation != null) {
                logger.info("mybatis config:" + this.configLocation.getFile().getAbsolutePath());
                inputStream = this.configLocation.getInputStream();
            } else {
                Resource resource = new ClassPathResource("com/glaf/activiti/activiti.mybatis.conf.xml");
                inputStream = resource.getInputStream();
            }

            if (!ObjectUtils.isEmpty(this.mapperLocations)) {
                SAXReader xmlReader = new SAXReader();
                EntityResolver entityResolver = new XMLMapperEntityResolver();
                xmlReader.setEntityResolver(entityResolver);
                Document doc = xmlReader.read(inputStream);
                Element root = doc.getRootElement();
                Element mappers = root.element("mappers");
                if (mappers != null) {
                    java.util.List<?> list = mappers.elements();
                    Collection<String> files = new HashSet<String>();

                    if (list != null && !list.isEmpty()) {
                        Iterator<?> iterator = list.iterator();
                        while (iterator.hasNext()) {
                            Element elem = (Element) iterator.next();
                            if (elem.attributeValue("resource") != null) {
                                String file = elem.attributeValue("resource");
                                files.add(file);
                            } else if (elem.attributeValue("url") != null) {
                                String file = elem.attributeValue("url");
                                files.add(file);
                            }
                        }
                    }

                    for (Resource mapperLocation : this.mapperLocations) {
                        if (mapperLocation == null) {
                            continue;
                        }
                        String url = mapperLocation.getURL().toString();
                        // logger.debug("find mapper:" + url);
                        if (!files.contains(url)) {
                            Element element = mappers.addElement("mapper");
                            element.addAttribute("url", url);
                        }
                    }
                }

                IOUtils.closeStream(inputStream);

                byte[] bytes = Dom4jUtils.getBytesFromPrettyDocument(doc);
                inputStream = new ByteArrayInputStream(bytes);

            }

            // update the jdbc parameters to the configured ones...
            Environment environment = new Environment("default", transactionFactory, dataSource);
            Reader reader = new InputStreamReader(inputStream);
            Properties properties = new Properties();
            properties.put("prefix", databaseTablePrefix);
            if (databaseType != null) {
                properties.put("limitBefore",
                        DbSqlSessionFactory.databaseSpecificLimitBeforeStatements.get(databaseType));
                properties.put("limitAfter",
                        DbSqlSessionFactory.databaseSpecificLimitAfterStatements.get(databaseType));
                properties.put("limitBetween",
                        DbSqlSessionFactory.databaseSpecificLimitBetweenStatements.get(databaseType));
                properties.put("orderBy",
                        DbSqlSessionFactory.databaseSpecificOrderByStatements.get(databaseType));
            }
            XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
            Configuration configuration = parser.getConfiguration();
            configuration.setEnvironment(environment);
            configuration.getTypeHandlerRegistry().register(VariableType.class, JdbcType.VARCHAR,
                    new IbatisVariableTypeHandler());
            configuration = parser.parse();

            sqlSessionFactory = new DefaultSqlSessionFactory(configuration);

        } catch (Exception e) {
            throw new ActivitiException("Error while building ibatis SqlSessionFactory: " + e.getMessage(), e);
        } finally {
            IoUtil.closeSilently(inputStream);
        }
    }
}