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.brekka.stillingar.spring.snapshot.ResourceSnapshotManager.java

/**
 * Perform the load operation that will convert a resource into a snapshot.
 * @param resourceToLoad the resouce to load into a snapshot
 * @return the snapshot loaded from the specified resource
 * @throws ConfigurationException if something goes wrong such as an IO error.
 *///from   ww  w .  j  a  v a  2 s. c o  m
protected Snapshot performLoad(Resource resourceToLoad) {
    Snapshot snapshot = null;
    if (resourceToLoad != null && resourceToLoad.exists() && resourceToLoad.isReadable()) {
        InputStream sourceStream = null;
        try {
            sourceStream = resourceToLoad.getInputStream();
            long timestamp = resourceToLoad.lastModified();
            ConfigurationSource configurationSource = configurationSourceLoader.parse(sourceStream, null);
            snapshot = new ResourceSnapshot(configurationSource, new Date(timestamp), resourceToLoad);
        } catch (IOException e) {
            throw new ConfigurationException(format("Resouce '%s'", resourceToLoad), e);
        } catch (RuntimeException e) {
            // Wrap to include location details
            throw new ConfigurationException(format("Resouce '%s' processing problem", resourceToLoad), e);
        } finally {
            closeQuietly(sourceStream);
        }
    }
    return snapshot;
}

From source file:org.cloudfoundry.tools.timeout.TimeoutResourceHttpRequestHandler.java

private String getContent(Resource resource) throws IOException {
    WeakReference<String> contentReference = this.cache.get(resource);
    String content = contentReference == null ? null : contentReference.get();
    if (content == null) {
        Assert.notNull(this.timeoutValues, "TimeoutValues must not be null");
        content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
        content = content.replace("{polltimeout}",
                String.valueOf(this.timeoutValues.getThreshold() + ONE_SECOND));
        content = content.replace("{failtimeout}", String.valueOf(this.timeoutValues.getFailTimeout()));
        this.cache.put(resource, new WeakReference<String>(content));
    }//from  w  w w .  jav a2s. c o m
    return content;
}

From source file:com.opengamma.examples.simulated.livedata.ExampleLiveDataServer.java

private void readInitialValues(final Resource initialValuesFile) {
    CSVReader reader = null;/*from  ww w.j  a  va2  s. c om*/
    try {
        reader = new CSVReader(new BufferedReader(new InputStreamReader(initialValuesFile.getInputStream())));
        // Read header row
        @SuppressWarnings("unused")
        final String[] headers = reader.readNext();
        String[] line;
        int lineNum = 1;
        while ((line = reader.readNext()) != null) {
            lineNum++;
            if (line.length > 0 && line[0].startsWith("#")) {
                continue;
            }
            if (line.length != NUM_FIELDS) {
                s_logger.error("Not enough fields in CSV on line " + lineNum);
            } else {
                final String identifier = line[0];
                final String fieldName = line[1];
                final String valueStr = line[2];
                final Double value = Double.parseDouble(valueStr);
                addTicks(identifier, fieldName, value);
            }
        }
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:batch.demo.job.FlatFilePartitioner.java

/**
 * Returns the number of elements in the specified {@link Resource}.
 *
 * @param resource the resource/*from  w w  w  .java2s .c o  m*/
 * @return the number of items contained in the resource
 */
protected long countItems(Resource resource) {
    try {
        final InputStream in = resource.getInputStream();
        try {
            return countLines(in);
        } finally {
            in.close();
        }
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unexpected IO exception while counting items for [" + resource.getDescription() + "]", e);
    }
}

From source file:org.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImplTest.java

@Test
public void testBedworkSingleCalendar() throws IOException {
    Resource controlExample = new ClassPathResource(
            "caldav-examples/report-response-bedework-single-calendar.xml");

    ReportResponseHandlerImpl handler = new ReportResponseHandlerImpl();
    List<CalendarWithURI> calendars = handler.extractCalendars(controlExample.getInputStream());
    Assert.assertEquals(1, calendars.size());

    CalendarWithURI withUri = calendars.get(0);
    Assert.assertEquals("/ucaldav/user/schwag/calendar/CAL-00e8903c-2fbc6e9b-012f-bc6f2d42-00000002.ics",
            withUri.getUri());/*from   w ww  .  j a  v  a2 s  .co m*/
    Assert.assertEquals("\"20110505T151112Z-0\"", withUri.getEtag());
    Calendar cal = withUri.getCalendar();
    ProdId prodId = cal.getProductId();
    Assert.assertNotNull(prodId);
    Assert.assertEquals("//Bedework.org//BedeWork V3.7//EN", prodId.getValue());

    ComponentList components = cal.getComponents(VEvent.VEVENT);
    Assert.assertEquals(1, components.size());
    VEvent event = (VEvent) components.get(0);
    Assert.assertEquals("dentist appointment", event.getSummary().getValue());
}

From source file:org.elasticsoftware.elasticactors.configuration.NodeConfiguration.java

@PostConstruct
public void init() throws IOException {
    // get the yaml resource
    Resource configResource = resourceLoader
            .getResource(env.getProperty("ea.node.config.location", "classpath:ea-default.yaml"));
    // yaml mapper
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    configuration = objectMapper.readValue(configResource.getInputStream(), DefaultConfiguration.class);
    String nodeId = env.getRequiredProperty("ea.node.id");
    InetAddress nodeAddress = InetAddress.getByName(env.getRequiredProperty("ea.node.address"));
    String clusterName = env.getRequiredProperty("ea.cluster");
    node = new ElasticActorsNode(clusterName, nodeId, nodeAddress, configuration);
}

From source file:com.enonic.cms.server.service.admin.mvc.controller.SiteDebugInfoController.java

/**
 * Read external javascript file.//from  w  w w  .  j a v a 2s  . c  o  m
 */
private String readStaticFile(Resource path) throws Exception {
    StringWriter out = new StringWriter();
    InputStreamReader in = new InputStreamReader(path.getInputStream());
    FileCopyUtils.copy(in, out);
    return out.getBuffer().toString();
}

From source file:com.samples.platform.core.config.CoreSpringConfig.java

/** Initialize failure messages. */
private void initializeFailureMessages() {
    try {// w ww  . j a v a 2 s  .  co  m
        Resource[] resources = this.applicationContext.getResources(new StringBuffer(32).append("classpath*:")
                .append(BaseFailureHandler.FAILURE_MESSAGES_XML).toString());
        for (Resource resource : resources) {
            BaseFailureHandler.addFailureMessages(resource.getInputStream());
        }
        // PathMatchingResourcePatternResolver resolver = new
        // PathMatchingResourcePatternResolver();
        // Resource[] xsds = resolver.getResources("classpath*:**/*.xsd");
        // for (Resource xsd : xsds) {
        // if (!String.valueOf(xsd.getURL()).startsWith("jar")) {
        // this.logger.debug("contained xsds: {}",
        // xsd.getFile().getAbsolutePath());
        // }
        // }
    } catch (IOException e) {
        this.logger.error(e.getMessage(), e);
    }
}

From source file:com.vh.ds.iam.web.front.jxl.AbstractJxlView.java

/**
 * Create the workbook from an existing XLS document.
 * @param url the URL of the Excel template without localization part nor extension
 * @param request current HTTP request/* w  ww. j a  v a 2s  . com*/
 * @return the template workbook
 * @throws Exception in case of failure
 */
protected Workbook getTemplateSource(String url, HttpServletRequest request) throws Exception {
    LocalizedResourceHelper helper = new LocalizedResourceHelper(getApplicationContext());
    Locale userLocale = RequestContextUtils.getLocale(request);
    Resource inputFile = helper.findLocalizedResource(url, EXTENSION, userLocale);

    // Create the Excel document from the source.
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Loading Excel workbook from {}", inputFile);
    }
    return Workbook.getWorkbook(inputFile.getInputStream());
}

From source file:net.rrm.ehour.persistence.dbvalidator.DerbyDbValidator.java

/**
 * Create datamodel and fill with initial data
 *///w ww .  j  av a  2 s. c  om
private void createOrAlterDatamodel(DataSource dataSource, DdlType ddlType)
        throws DdlUtilsException, IOException {
    Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);

    Resource resource = new ClassPathResource(getDdlFilename());

    DatabaseIO reader = new DatabaseIO();
    reader.setValidateXml(false);
    reader.setUseInternalDtd(true);

    Database ddlModel = reader.read(new InputStreamReader(resource.getInputStream(), "UTF-8"));

    if (ddlType == DdlType.CREATE_TABLE) {
        platform.createTables(ddlModel, false, false);
        insertInitialData(platform, ddlModel);
    } else {
        platform.alterTables(ddlModel, false);
        insertDiffData(platform, ddlModel);
        updateVersion(platform, ddlModel);
    }
}