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:com.baomidou.framework.log.LogbackConfigListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    try {/*  www. j  a  va  2s .  c  o  m*/
        String location = event.getServletContext().getInitParameter(CONFIG_LOCATION_PARAM);
        Resource resource = new DefaultResourceLoader().getResource(location);
        Map<Object, Object> context = new HashMap<Object, Object>();
        context.put("env", getRunEnvironment());
        StringWriter writer = new StringWriter();
        BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), getCharset()));
        Velocity.evaluate(new VelocityContext(context), writer, "LogbackConfigListener", br);
        this.initLogging(new ByteArrayInputStream(writer.toString().getBytes(getCharset())));
    } catch (Exception e) {
        throw new SpringWindException(e);
    }
}

From source file:com.fns.grivet.api.GrivetApiClientIT.java

@Test
public void testRegisterTypeBadRequest() {
    Resource r = resolver.getResource("classpath:BadTestType.json");
    try {//from w  w w.  ja va2s.c  o  m
        String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        given().contentType("application/json").request().body(json).then().expect().statusCode(equalTo(400))
                .when().post("/api/v1/definition");
    } catch (IOException e) {
        fail(e.getMessage());
    }
}

From source file:nl.flotsam.calendar.web.UriListHttpMessageConverterTest.java

@Test
public void shouldParseXsltProducedCorrectly() throws IOException {
    Resource resource = new ClassPathResource("scala-tribes.ical");
    UriListHttpMessageConverter converter = new UriListHttpMessageConverter();
    List<URI> list = new ArrayList<URI>();
    when(message.getHeaders()).thenReturn(headers);
    when(headers.getContentType()).thenReturn(MediaType.TEXT_PLAIN);
    when(message.getBody()).thenReturn(resource.getInputStream());
    list = converter.read((Class<? extends List<URI>>) list.getClass(), message);
    assertThat(list.size(), is(8));/*from w  ww  . j a  va 2 s  .  c  o  m*/
}

From source file:com.fns.grivet.api.GrivetApiClientIT.java

private String registerMultipleTypes() {
    String json = null;/*from w ww. j ava2s  . com*/
    Resource r = resolver.getResource("classpath:TestMultipleTypes.json");
    try {
        json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        given().contentType("application/json").request().body(json).then().expect().statusCode(equalTo(201))
                .when().post("/api/v1/definitions");
    } catch (IOException e) {
        fail(e.getMessage());
    }
    return json;

}

From source file:se.inera.axel.shs.camel.DefaultCamelShsMessageConverterTest.java

@DirtiesContext
@Test/* www  .j  a v a  2 s.  c  om*/
public void convertShsMessageToCamelMessage() throws Exception {

    Resource mimeMessage = new ClassPathResource("se/inera/axel/shs/camel/mimeMessage.txt");
    ShsMessageMarshaller marshaller = new ShsMessageMarshaller();
    ShsMessage shsMessage = marshaller.unmarshal(mimeMessage.getInputStream());

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:shsToCamelConverter", shsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();

    String responseBody = in.getBody(String.class);

    Assert.assertNotNull(responseBody, "body expected");
    Assert.assertNotNull(exchange.getProperty(ShsHeaders.LABEL),
            "Header " + ShsHeaders.LABEL + " should not be null");
    Assert.assertNull(exchange.getIn().getHeader(ShsHeaders.FROM),
            "Header value '" + ShsHeaders.FROM + "' found, should be null");

    Assert.assertEquals(responseBody, DEFAULT_TEST_BODY);
    Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_CONTENTTYPE),
            "text/plain; name=testfile.txt; charset=iso-8859-1");

    Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_FILENAME), "testfile.txt");
    Assert.assertEquals(in.getHeader(Exchange.CHARSET_NAME), "iso-8859-1");
    // Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_CONTENTLENGTH), 13);
    Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_TYPE), "txt");

    // TODO should this be set on the headers instead of leaving the label n the property?
    //        Assert.assertEquals(in.getHeader(ShsHeaders.FROM), DEFAULT_TEST_FROM);
    //        Assert.assertEquals(in.getHeader(ShsHeaders.TO), DEFAULT_TEST_TO);
    //
    //        Assert.assertEquals(in.getHeader(ShsHeaders.CONTENT_ID), DEFAULT_TEST_CONTENT_ID);
    //        Assert.assertNull(in.getHeader(ShsHeaders.ENDRECIPIENT));
    //
    //        @SuppressWarnings("unchecked")
    //        Map<String, String> metaMap = (Map<String, String>)in.getHeader(ShsHeaders.META);
    //        assertThat(metaMap.entrySet(), hasSize(1));
    //        assertEquals(metaMap.get("meta1"), "meta1value");

}

From source file:se.inera.axel.shs.camel.DefaultCamelShsMessageConverterTest.java

@DirtiesContext
@Test/*from w  w  w .j  ava2 s.c om*/
public void convertShsMessageToCamelMessageWithoutFilename() throws Exception {

    Resource mimeMessage = new ClassPathResource("se/inera/axel/shs/camel/mimeMessageWithoutFilename.txt");
    ShsMessageMarshaller marshaller = new ShsMessageMarshaller();
    ShsMessage shsMessage = marshaller.unmarshal(mimeMessage.getInputStream());

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:shsToCamelConverter", shsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();

    String responseBody = in.getBody(String.class);
    Assert.assertNotNull(responseBody, "body expected");
    Assert.assertNotNull(exchange.getProperty(ShsHeaders.LABEL),
            "Header " + ShsHeaders.LABEL + " should not be null");
    Assert.assertNull(exchange.getIn().getHeader(ShsHeaders.FROM),
            "Header value '" + ShsHeaders.FROM + "' found, should be null");

    Assert.assertEquals(responseBody, DEFAULT_TEST_BODY);
    Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_CONTENTTYPE), "text/plain; charset=UTF-8");

    Assert.assertNull(in.getHeader(ShsHeaders.DATAPART_FILENAME));
    Assert.assertEquals(in.getHeader(Exchange.CHARSET_NAME), "UTF-8");
    // TODO Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_CONTENTLENGTH), 13);
    Assert.assertEquals(in.getHeader(ShsHeaders.DATAPART_TYPE), "txt");

}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java

private Map<String, DatasetDescriptionImpl> loadFromYaml() throws IOException {
    // Scan for locators
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] locators = resolver.getResources("classpath:META-INF/org.dkpro.core/datasets.txt");

    // Read locators
    Set<String> patterns = new LinkedHashSet<>();
    for (Resource locator : locators) {
        try (InputStream is = locator.getInputStream()) {
            IOUtils.lineIterator(is, "UTF-8").forEachRemaining(l -> patterns.add(l));
        }/*from  ww w . j  a v  a 2 s .  co m*/
    }

    // Scan for YAML dataset descriptions
    List<Resource> resources = new ArrayList<>();
    for (String pattern : patterns) {
        for (Resource r : resolver.getResources(pattern)) {
            resources.add(r);
        }
    }

    // Configure YAML deserialization
    Constructor datasetConstructor = new Constructor(DatasetDescriptionImpl.class);
    TypeDescription datasetDesc = new TypeDescription(DatasetDescriptionImpl.class);
    datasetDesc.putMapPropertyType("artifacts", String.class, ArtifactDescriptionImpl.class);
    datasetDesc.putListPropertyType("licenses", LicenseDescriptionImpl.class);
    datasetConstructor.addTypeDescription(datasetDesc);
    TypeDescription artifactDesc = new TypeDescription(ArtifactDescriptionImpl.class);
    artifactDesc.putListPropertyType("actions", ActionDescriptionImpl.class);
    datasetConstructor.addTypeDescription(artifactDesc);
    Yaml yaml = new Yaml(datasetConstructor);

    // Ensure that there is a fixed order (at least if toString is correctly implemented)
    Collections.sort(resources, (a, b) -> {
        return a.toString().compareTo(b.toString());
    });

    // Load the YAML descriptions
    Map<String, DatasetDescriptionImpl> sets = new LinkedHashMap<>();
    for (Resource res : resources) {
        LOG.debug("Loading [" + res + "]");
        try (InputStream is = res.getInputStream()) {
            String id = FilenameUtils.getBaseName(res.getFilename());
            DatasetDescriptionImpl ds = yaml.loadAs(is, DatasetDescriptionImpl.class);
            ds.setId(id);
            ds.setOwner(this);

            // Inject artifact names into artifacts
            for (Entry<String, ArtifactDescription> e : ds.getArtifacts().entrySet()) {
                ((ArtifactDescriptionImpl) e.getValue()).setName(e.getKey());
            }

            sets.put(ds.getId(), ds);
        }
    }

    return sets;
}

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

@Test
public void testMultipleCalendarResponse() throws IOException {
    Resource controlExample = new ClassPathResource("caldav-examples/report-response-multiple-calendars.xml");

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

    CalendarWithURI withUri = calendars.get(0);
    Assert.assertEquals("http://cal.example.com/bernard/work/abcd2.ics", withUri.getUri());
    Assert.assertEquals("\"fffff-abcd2\"", withUri.getEtag());
    Calendar cal = withUri.getCalendar();
    ProdId prodId = cal.getProductId();//from   ww w.  j  a v a 2 s .  co  m
    Assert.assertNotNull(prodId);
    Assert.assertEquals("-//CalendarKey 2.0//iCal4j 1.0//EN", prodId.getValue());

    ComponentList components = cal.getComponents(VEvent.VEVENT);
    Assert.assertEquals(1, components.size());
    VEvent event = (VEvent) components.get(0);
    Assert.assertEquals("regular 10 am meeting", event.getSummary().getValue());

    CalendarWithURI withUri2 = calendars.get(1);
    Assert.assertEquals("http://cal.example.com/bernard/work/abcd3.ics", withUri2.getUri());
    Assert.assertEquals("\"fffff-abcd3\"", withUri2.getEtag());
    Calendar cal2 = withUri2.getCalendar();
    ComponentList components2 = cal2.getComponents(VEvent.VEVENT);
    Assert.assertEquals(2, components2.size());
}

From source file:com.ogaclejapan.dotapk.controller.ApkApiController.java

@RequestMapping(value = "/{name:.+}", method = RequestMethod.GET)
public void download(@PathVariable String name, HttpServletResponse response) throws Exception {
    log.info("download: " + name);

    Resource file = new FileSystemResource(apkManager.getByName(name));
    response.setContentType("application/vnd.android.package-archive");
    response.setContentLength((int) FileUtils.sizeOf(file.getFile()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFile().getName() + "\"");
    FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());

}

From source file:org.elasticsoftware.elasticactors.test.configuration.TestConfiguration.java

@PostConstruct
public void init() throws IOException {
    // get the yaml resource
    Resource configResource = resourceLoader
            .getResource(env.getProperty("ea.node.config.location", "classpath:ea-test.yaml"));
    // yaml mapper
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    configuration = objectMapper.readValue(configResource.getInputStream(), DefaultConfiguration.class);
}