Example usage for org.apache.commons.io IOUtils toInputStream

List of usage examples for org.apache.commons.io IOUtils toInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toInputStream.

Prototype

public static InputStream toInputStream(String input) 

Source Link

Document

Convert the specified string to an input stream, encoded as bytes using the default character encoding of the platform.

Usage

From source file:com.autentia.web.rest.wadl.zipper.WadlZipper.java

/**
 * Just for easily inject dependencies on tests.
 *///  w w  w.ja  v  a  2 s .  com
void saveTo(HttpClient httpClient, Zip zip) throws IOException, URISyntaxException {
    try {
        final String wadlContent = httpClient.getAsString(wadlUri);
        zip.add(DEFAULT_WADL_FILENAME, IOUtils.toInputStream(wadlContent));

        for (String grammarUri : new GrammarsUrisExtractor().extractFrom(wadlContent)) {
            final URI uri = new URI(grammarUri);
            final String name = composesGrammarFileNameWith(uri);
            final InputStream inputStream = httpClient.getAsStream(wadlUri.resolve(uri));
            zip.add(name, inputStream);
        }

    } finally {
        zip.close();
    }
}

From source file:com.seajas.search.contender.service.builder.RSSDirectoryBuilder.java

/**
 * Create a UTF-8 stream containing the contents of the directory as a stream.
 *
 * @param directory//from   w  w w .  j a va 2  s  .  c o  m
 * @return InputStream
 * @throws IOException
 */
public static InputStream build(final File directory) throws IOException {
    if (!directory.isDirectory())
        throw new IllegalStateException("The given handle is not a directory");

    // Create a simple feed

    SyndFeedImpl feed = new SyndFeedImpl();

    feed.setEntries(new ArrayList<SyndEntry>());

    // Then add the entries to it

    Map<String, Long> files = travelDirectory(directory, new HashMap<String, Long>());

    for (Map.Entry<String, Long> file : files.entrySet()) {
        SyndEntryImpl entry = new SyndEntryImpl();

        entry.setUri("file://" + file.getKey());
        entry.setTitle(file.getKey());
        entry.setPublishedDate(new Date(file.getValue()));

        feed.getEntries().add(entry);
    }

    // And serialize it to an InputStream

    SyndFeedOutput serializer = new SyndFeedOutput();

    try {
        WebFeeds.validate(feed, URI.create("file://" + directory.getAbsolutePath()));

        return IOUtils.toInputStream(serializer.outputString(feed, true));
    } catch (FeedException e) {
        throw new IOException("Unable to serialize stream", e);
    }
}

From source file:es.us.isa.sedl.core.analysis.datasetspecification.AbstractDatasetSpecificationTest.java

/**
 * Test of apply method, of class AbstractDatasetSpecification.
 *///from ww  w . j a v  a 2 s.c  om
public void testApply() {
    try {
        CSVLoader csvLoader = new CSVLoader(Boolean.TRUE);
        String initialDatasetContent = "Sex;Height" + NEW_LINE + "man;1.82" + NEW_LINE + "woman;1.63";
        DataSet initialDataset = csvLoader.load(IOUtils.toInputStream(initialDatasetContent), "csv");
        // TESTING PROJECTION APPLICATION:
        String expectedResultContent = "Height" + NEW_LINE + "1.82" + NEW_LINE + "1.63";
        DataSet expectedResult = csvLoader.load(IOUtils.toInputStream(expectedResultContent), "csv");
        DatasetSpecification datasetSpecification = new DatasetSpecification();
        Projection projection = new Projection();
        projection.getProjectedVariables().add("Height");
        datasetSpecification.getProjections().add(projection);
        DataSet result = datasetSpecification.apply(initialDataset);
        assertEquals(expectedResult, result);
        // TESTING PROJECTION & FILTER APPLICATION:
        expectedResultContent = "Height" + NEW_LINE + "1.82";
        expectedResult = csvLoader.load(IOUtils.toInputStream(expectedResultContent), "csv");
        ValuationFilter filter = new ValuationFilter();
        Variable var = new Outcome();
        var.setName("Sex");
        var.setKind(VariableKind.NOMINAL);
        Level l = new Level();
        l.setValue("man");
        VariableValuation valuation = new VariableValuation();
        valuation.setVariable(var);
        valuation.setLevel(l);
        filter.getVariableValuations().add(valuation);
        datasetSpecification.getFilters().add(filter);
        result = datasetSpecification.apply(initialDataset);
        assertEquals(expectedResult, result);
    } catch (IOException ex) {
        Logger.getLogger(AbstractDatasetSpecificationTest.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
        fail(ex.getMessage());
    }
}

From source file:com.cazcade.billabong.store.impl.FileBasedBinaryStoreTest.java

@Test
public void testEntryAdditionAndReplacement() throws IOException {
    StaticTestDateHelper dateHelper = new StaticTestDateHelper();
    dateHelper.setDate(lastModifiedDate);
    FileBasedBinaryStore store = new FileBasedBinaryStore(storeDirectory);
    store.setDateHelper(dateHelper);// w  w w . j a v  a 2s . c o  m

    Assert.assertEquals(0, storeDirectory.list().length);

    InputStream storeEntry = IOUtils.toInputStream("TESTY");
    Assert.assertTrue(store.placeInStore(STORE_KEY, storeEntry, false));
    Assert.assertEquals(1, storeDirectory.list().length);
    Assert.assertTrue(storeFile.exists());
    Assert.assertFalse(storeFile2.exists());

    storeEntry = IOUtils.toInputStream("TESTY2");
    Assert.assertTrue(store.placeInStore(STORE_KEY2, storeEntry, true));
    Assert.assertEquals(2, storeDirectory.list().length);
    Assert.assertTrue(storeFile.exists());
    Assert.assertTrue(storeFile2.exists());

    Assert.assertEquals("TESTY", IOUtils.toString(store.retrieveFromStore(STORE_KEY).getContent()));
    Assert.assertEquals("TESTY2", IOUtils.toString(store.retrieveFromStore(STORE_KEY2).getContent()));

    storeEntry = IOUtils.toInputStream("TESTY3");
    Assert.assertFalse(store.placeInStore(STORE_KEY, storeEntry, false));
    Assert.assertEquals("TESTY", IOUtils.toString(store.retrieveFromStore(STORE_KEY).getContent()));
    Assert.assertEquals(2, storeDirectory.list().length);
    Assert.assertTrue(storeFile.exists());
    Assert.assertTrue(storeFile2.exists());

    Assert.assertTrue(store.placeInStore(STORE_KEY, storeEntry, true));
    Assert.assertEquals("TESTY2", IOUtils.toString(store.retrieveFromStore(STORE_KEY2).getContent()));
    Assert.assertEquals("TESTY3", IOUtils.toString(store.retrieveFromStore(STORE_KEY).getContent()));
    Assert.assertEquals(2, storeDirectory.list().length);
    Assert.assertTrue(storeFile.exists());
    Assert.assertTrue(storeFile2.exists());

    //last modified only accurate to the nearest second last 3 digits 000.

    Assert.assertTrue(Math.abs(lastModifiedDate.getTime() - storeFile.lastModified()) <= 1000l);
    Assert.assertTrue(Math.abs(lastModifiedDate.getTime() - storeFile2.lastModified()) <= 1000l);
}

From source file:com.googlecode.fascinator.storage.ram.RamStorageTest.java

@Test
public void createObject() throws Exception {
    // Create a test object
    DigitalObject newObject = ram.createObject("oai:eprints.usq.edu.au:318");
    Payload dcPayload = newObject.createStoredPayload("oai_dc",
            IOUtils.toInputStream("<dc><title>test</title></dc>"));
    dcPayload.setLabel("Dublin Core Metadata");

    // Makes sure the object reports only 1 payload
    Set<String> payloads = newObject.getPayloadIdList();
    Assert.assertEquals(1, payloads.size());

    // Make sure our payload retrieves and is labelled correctly
    Payload payload = newObject.getPayload("oai_dc");
    Assert.assertEquals("Dublin Core Metadata", payload.getLabel());

    // Remove the payload and recheck object payload size
    newObject.removePayload(payload.getId());
    payloads = newObject.getPayloadIdList();
    Assert.assertEquals(0, payloads.size());

    // Remove the object from storage
    try {/*  ww  w. j  av a  2s .  c o m*/
        ram.removeObject(newObject.getId());
    } catch (StorageException ex) {
        Assert.fail("Error deleting newObject : " + ex.getMessage());
    }
}

From source file:com.planyourexchange.utils.PropertyReaderTest.java

License:asdf

@Test
public void testGetSecretData() throws Exception {
    InputStream inputStream = IOUtils.toInputStream("ASDFG=1QAZ2WSX3EDC");
    when(assetManager.open(any(String.class))).thenReturn(inputStream);
    PropertyReader propertyReader = new PropertyReader(context, sensitiveDataUtils);

    when(sensitiveDataUtils.hashKey("secretData")).thenReturn("ASDFG");
    when(sensitiveDataUtils.decrypt("1QAZ2WSX3EDC")).thenReturn("XYZ");

    String secretData = propertyReader.getProperty("secretData");
    assertEquals("XYZ", secretData);
}

From source file:ddf.catalog.registry.transformer.Gml3ToWkt.java

public String convert(String xml) {
    return convert(IOUtils.toInputStream(xml));
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.StudyCalendarXmlSerializerTest.java

public void testReadDocumentReadsTheRootElement() throws Exception {
    Map<String, String> actual = serializer.readDocument(IOUtils
            .toInputStream(String.format("<map xmlns=\"%s\"><entry key=\"foo\">quux</entry></map>", PSC_NS)));

    assertEquals("Wrong number of things read from document", 1, actual.size());
    assertEquals("Wrong thing read", "quux", actual.get("foo"));
}

From source file:com.sun.jersey.server.impl.uri.rules.UriRuleContextDbl.java

public static UriRuleContext make() throws Exception {
    WebApplicationImpl app = new WebApplicationImpl();
    ContainerRequest request = new ContainerRequest(app, // web application requested
            "GET", // HTTP method
            new URI("/"), // base URI
            new URI("/test"), // request URI
            new InBoundHeaders(), // headers
            IOUtils.toInputStream("") // incoming entity
    );/*from w  w w  .j  ava  2  s  .  c o  m*/
    ContainerResponse response = new ContainerResponse(app, // web application requested
            request, // container request
            new ResponseWriterDbl());
    UriRuleContext context = new WebApplicationContext(app, request, response);
    return context;
}

From source file:au.edu.usq.fascinator.harvester.feed.FeedItemContentPayload.java

@Override
public InputStream getInputStream() {
    try {/*  w  ww  .ja  v  a  2s . c o m*/
        return IOUtils.toInputStream(FeedHelper.toXHTMLSegment(feedEntry, FeedItemContentPayload.htmlTemplate));
    } catch (ResourceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseErrorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}