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.jmxtrans.embedded.spring.EmbeddedJmxTransFactory.java

@Override
public SpringEmbeddedJmxTrans getObject() throws Exception {
    logger.info("Load JmxTrans with configuration '{}'", configurationUrls);
    if (embeddedJmxTrans == null) {

        if (configurationUrls == null) {
            configurationUrls = Collections.singletonList(DEFAULT_CONFIGURATION_URL);
        }//from www  . j  ava 2  s  . c o m
        ConfigurationParser parser = new ConfigurationParser();
        SpringEmbeddedJmxTrans newJmxTrans = new SpringEmbeddedJmxTrans();
        newJmxTrans.setObjectName("org.jmxtrans.embedded:type=EmbeddedJmxTrans,name=" + beanName);

        for (String delimitedConfigurationUrl : configurationUrls) {
            String[] tokens = StringUtils.commaDelimitedListToStringArray(delimitedConfigurationUrl);
            tokens = StringUtils.trimArrayElements(tokens);
            for (String configurationUrl : tokens) {
                configurationUrl = configurationUrl.trim();
                logger.debug("Load configuration {}", configurationUrl);
                Resource configuration = resourceLoader.getResource(configurationUrl);
                if (configuration.exists()) {
                    try {
                        parser.mergeEmbeddedJmxTransConfiguration(configuration.getInputStream(), newJmxTrans);
                    } catch (Exception e) {
                        throw new EmbeddedJmxTransException("Exception loading configuration " + configuration,
                                e);
                    }
                } else if (ignoreConfigurationNotFound) {
                    logger.debug("Ignore missing configuration file {}", configuration);
                } else {
                    throw new EmbeddedJmxTransException("Configuration file " + configuration + " not found");
                }
            }
        }
        embeddedJmxTrans = newJmxTrans;
        logger.info("Created EmbeddedJmxTrans with configuration {})", configurationUrls);
        embeddedJmxTrans.start();
    }
    return embeddedJmxTrans;
}

From source file:com.baomidou.framework.velocity.VelocityPropertyPlaceholderConfigurer.java

@Override
protected void loadProperties(Properties props) throws IOException {
    if (this.locations != null && props != null) {
        for (Resource location : this.locations) {
            if (logger.isInfoEnabled()) {
                logger.info("Loading properties file from " + location);
            }//from   www.j  av a2  s . c o  m
            this.fillMergeProperties(props, location.getInputStream());
        }
    }
}

From source file:org.esupportail.papercut.services.PayBoxService.java

public void setDerPayboxPublicKeyFile(String derPayboxPublicKeyFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    org.springframework.core.io.Resource derPayboxPublicKeyRessource = new ClassPathResource(
            derPayboxPublicKeyFile);/*from  w w w  .j  av a 2s  .c  o  m*/
    InputStream fis = derPayboxPublicKeyRessource.getInputStream();
    DataInputStream dis = new DataInputStream(fis);
    byte[] pubKeyBytes = new byte[fis.available()];
    dis.readFully(pubKeyBytes);
    fis.close();
    dis.close();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    this.payboxPublicKey = kf.generatePublic(x509EncodedKeySpec);
}

From source file:com.qcadoo.view.internal.resource.JspResourceResolver.java

private void copyResource(final Resource resource) {
    if (!resource.isReadable()) {
        return;//w ww  .j a va  2  s.  c  o m
    }

    try {
        String path = resource.getURI().toString().split("WEB-INF/jsp/")[1];
        File file = new File(webappPath + "/WEB-INF/jsp/" + path);

        if (resource.getInputStream().available() == 0) {
            FileUtils.forceMkdir(file);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Copying " + path + " to " + file.getAbsolutePath());
            }

            OutputStream output = null;

            try {
                output = new BufferedOutputStream(new FileOutputStream(file));
                IOUtils.copy(resource.getInputStream(), output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException("Cannot copy resource " + resource, e);
    }
}

From source file:com.vilt.minium.jasmine.MiniumJasmineTestRunner.java

private Object getVal(JsVariable jsVariable, Class<?> clazz, Object object) {
    try {//from   w ww  .  jav a  2s.  com
        if (StringUtils.isNotEmpty(jsVariable.resource())) {
            Resource resource = resourceLoader.getResource(jsVariable.resource());
            checkState(resource.exists() && resource.isReadable());

            if (clazz == String.class) {
                InputStream is = resource.getInputStream();
                try {
                    return IOUtils.toString(is, Charsets.UTF_8.name());
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                Object val = parseJson(rhinoContext, resource);
                checkState(clazz.isAssignableFrom(val.getClass()));
                return val;
            }
        } else {
            return object;
        }
    } catch (IOException e) {
        throw propagate(e);
    } catch (ParseException e) {
        throw propagate(e);
    }
}

From source file:org.dineth.shooter.app.view.ImageController.java

@RequestMapping(value = "/get/{name}.{ext}")
public ResponseEntity<byte[]> getImage(@PathVariable("name") String name, @PathVariable("ext") String ext) {

    Resource resource = context.getResource("file:/home/dewmal/files/" + name + "." + ext);
    System.out.println(resource.getFilename());
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);
    try {/*from   w w  w .j a v  a  2 s  .c  o  m*/
        return new ResponseEntity<>(IOUtils.toByteArray(resource.getInputStream()), headers,
                HttpStatus.CREATED);
    } catch (IOException ex) {
        Logger.getLogger(ImageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java

@Override
protected Resource[] getConfigResources() {
    List<Resource> resources = new ArrayList<Resource>();
    if (includeDefault) {
        try {/*w w w .  j  a v  a 2s.  c om*/
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                    Thread.currentThread().getContextClassLoader());

            Collections.addAll(resources, resolver.getResources(DEFAULT_CFG_FILE));

            Resource[] exts = resolver.getResources(DEFAULT_EXT_CFG_FILE);
            for (Resource r : exts) {
                InputStream is = r.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = rd.readLine();
                while (line != null) {
                    if (!"".equals(line)) {
                        resources.add(resolver.getResource(line));
                    }
                    line = rd.readLine();
                }
                is.close();
            }

        } catch (IOException ex) {
            // ignore
        }
    }
    boolean usingDefault = false;
    if (cfgFiles == null) {
        String userConfig = System.getProperty(BeanConfigurer.USER_CFG_FILE_PROPERTY_NAME);
        if (userConfig != null) {
            cfgFiles = new String[] { userConfig };
        }
    }
    if (cfgFiles == null) {
        usingDefault = true;
        cfgFiles = new String[] { BeanConfigurer.USER_CFG_FILE };
    }
    for (String cfgFile : cfgFiles) {
        final Resource f = findResource(cfgFile);
        if (f != null && f.exists()) {
            resources.add(f);
            LOG.info("Used configed file {}", cfgFile);
        } else {
            if (!usingDefault) {
                LOG.warn("Can't find configure file {}", cfgFile);
                throw new ApplicationContextException("Can't find configure file");
            }
        }
    }
    if (cfgURLs != null) {
        for (URL u : cfgURLs) {
            UrlResource ur = new UrlResource(u);
            if (ur.exists()) {
                resources.add(ur);
            } else {
                LOG.warn("Can't find configure file {}", u.getPath());
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating application context with resources " + resources.size());
    }
    if (0 == resources.size()) {
        return null;
    }
    Resource[] res = new Resource[resources.size()];
    res = resources.toArray(res);
    return res;

}

From source file:org.geomajas.gwt.server.mvc.ResourceSerializationPolicyLocator.java

@Override
public SerializationPolicy loadPolicy(HttpServletRequest request, String moduleBaseURL, String strongName) {

    SerializationPolicy serializationPolicy = null;
    String serializationPolicyFilePath = SerializationPolicyLoader.getSerializationPolicyFileName(strongName);

    for (Resource directory : policyRoots) {
        Resource policy;
        try {/*from   w w  w .  ja v  a 2 s.  c o m*/
            policy = directory.createRelative(serializationPolicyFilePath);
            if (policy.exists()) {
                // Open the RPC resource file and read its contents.
                InputStream is = policy.getInputStream();
                try {
                    if (is != null) {
                        try {
                            serializationPolicy = SerializationPolicyLoader.loadFromStream(is, null);
                            break;
                        } catch (ParseException e) {
                            log.error("Failed to parse the policy file '" + policy + "'", e);
                        } catch (IOException e) {
                            log.error("Could not read the policy file '" + policy + "'", e);
                        }
                    } else {
                        // existing spring resources should not return null, log anyways
                        log.error("Unexpected null stream from the policy file resource '" + policy + "'");
                    }
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            // Ignore this error
                        }
                    }
                }
            }
        } catch (IOException e1) {
            log.debug("Could not create the policy resource '" + serializationPolicyFilePath
                    + "' from parent resource " + directory, e1);
        }
    }
    if (serializationPolicy == null) {
        String message = "The serialization policy file '" + serializationPolicyFilePath
                + "' was not found; did you forget to include it in this deployment?";
        log.error(message);
    }
    return serializationPolicy;
}

From source file:org.mifos.tools.service.PPIUploaderService.java

private boolean uploadSurvey(final Properties properties, final MifosRestResource restResource,
        final String countryCode) {
    final Resource surveyResource = this.resourceLoader
            .getResource("classpath:template/" + countryCode.toUpperCase() + "/survey.json");

    if (surveyResource.exists()) {
        try {/*from   w  ww . j a  v  a 2 s  .c o  m*/
            final JsonReader reader = new JsonReader(new InputStreamReader(surveyResource.getInputStream()));
            final Survey survey = this.gson.fromJson(reader, Survey.class);
            restResource.createSurvey(this.authToken(properties), properties.getProperty("tenant"),
                    PPIUploaderConstant.CONTENT_TYPE, survey);
            return true;
        } catch (Throwable th) {
            this.logger.error("Error while uploading survey!", th);
            System.out.println("Could not upload survey! See logfile for more information.");
        }
    } else {
        System.out.println("Unknown country code " + countryCode + "!");
    }
    return false;
}