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, String encoding) throws IOException 

Source Link

Document

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

Usage

From source file:cool.pandora.modeller.ui.handlers.common.TextSequenceMetadata.java

/**
 * getTextSequenceMetadata./*  w ww .j a va2s  .c o  m*/
 *
 * @param resourceIDList       Map
 * @param pageId               String
 * @param canvasRegionURI      String
 * @param collectionPredicate  String
 * @param resourceContainerIRI URI
 * @return InputStream
 */
public static InputStream getTextSequenceMetadata(final Map<String, List<String>> resourceIDList,
        final String pageId, final String canvasRegionURI, final String collectionPredicate,
        final URI resourceContainerIRI) {
    final ArrayList<String> idList = new ArrayList<>(resourceIDList.get(pageId));
    final TextCollectionWriter collectionWriter;
    collectionWriter = TextCollectionWriter.collection().idList(idList).collectionPredicate(collectionPredicate)
            .resourceContainerIRI(resourceContainerIRI.toString()).canvasURI(canvasRegionURI).build();

    final String collection = collectionWriter.render();
    final MetadataTemplate metadataTemplate;
    final List<CollectionScope.Prefix> prefixes = Arrays.asList(new CollectionScope.Prefix(FedoraPrefixes.RDFS),
            new CollectionScope.Prefix(FedoraPrefixes.MODE));

    final CollectionScope scope = new CollectionScope().fedoraPrefixes(prefixes).sequenceGraph(collection);

    metadataTemplate = MetadataTemplate.template().template("template/sparql-update-seq" + ".mustache")
            .scope(scope).throwExceptionOnFailure().build();

    final String metadata = unescapeXml(metadataTemplate.render());
    return IOUtils.toInputStream(metadata, UTF_8);
}

From source file:gobblin.writer.objectstore.ObjectStoreWriterTest.java

@Test
public void testDelete() throws Exception {

    WorkUnitState wu = new WorkUnitState();
    wu.setProp(ObjectStoreDeleteConverter.OBJECT_ID_FIELD, "objectId");

    ObjectStoreClient client = new MockObjectStoreClient();
    byte[] objId = client.put(IOUtils.toInputStream("test", "UTF-8"), ConfigFactory.empty());
    Assert.assertEquals(IOUtils.toString(client.getObject(objId).getObjectData(), "UTF-8"), "test");

    try (ObjectStoreWriter writer = new ObjectStoreWriter(client, new State());) {
        ObjectStoreDeleteConverter converter = new ObjectStoreDeleteConverter();
        converter.init(wu);/*from www .  j  a  va2  s  .c  o  m*/

        Schema schema = new Schema.Parser().parse(SCHEMA_STR);
        GenericRecord datum = new GenericData.Record(schema);
        datum.put("objectId", objId);

        Iterables.getFirst(converter.convertRecord(converter.convertSchema(schema, wu), datum, wu), null);
        writer.write(Iterables.getFirst(
                converter.convertRecord(converter.convertSchema(schema, wu), datum, new WorkUnitState()),
                null));
    }

    try {
        client.getObject(objId);
        Assert.fail("should have thrown an IOException as object is already deleted");
    } catch (IOException e) {
        // All good exception thrown because object does not exist
    }
}

From source file:car_counter.processing.TestDefaultProcessor.java

@Before
public void setUp() throws Exception {
    BasicConfigurator.configure();/*  ww w . ja v  a2 s.co  m*/

    dbFile = Files.createTempFile("test", ".db");
    tempDirectory = Files.createTempDirectory("test");

    incoming = tempDirectory.resolve("incoming");
    data = tempDirectory.resolve("data");

    Files.createDirectories(incoming);
    Files.createDirectories(data);

    String iniValue = String.format(
            "[Counting]\n" + "implementation = noop\n" + "[Storage]\n" + "implementation = sqlite\n"
                    + "database = %s\n" + "[Processing]\n" + "incoming = %s\n" + "data = %s\n",
            dbFile, incoming, data);

    ini = new Wini();
    ini.getConfig().setMultiOption(true);

    try (InputStream stream = IOUtils.toInputStream(iniValue, StandardCharsets.UTF_8)) {
        ini.load(stream);
    }
}

From source file:com.hypirion.io.PipeTest.java

/**
 * Test that multiple InputStreams with random ascii characters will be
 * completely piped through the pipe, and not close the OutputStream.
 *///www.j  a v  a 2s.  c o m
@Test(timeout = 1000)
public void testStreamConcatenation() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String input = "";
    for (int i = 0; i < 10; i++) {
        String inString = RandomStringUtils.random(3708);
        input += inString;
        InputStream in = IOUtils.toInputStream(inString, "UTF-8");
        Pipe p = new Pipe(in, out);
        p.start();
        p.join();
        in.close();
    }
    String output = out.toString("UTF-8");
    out.close();
    assertEquals(input, output);
}

From source file:ch.cyberduck.core.onedrive.OneDriveReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {//  www .j a v  a 2  s .  co m
        if (file.getType().contains(Path.Type.placeholder)) {
            final DescriptiveUrl link = new OneDriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http);
            if (DescriptiveUrl.EMPTY.equals(link)) {
                log.warn(String.format("Missing web link for file %s", file));
                return new NullInputStream(file.attributes().getSize());
            }
            // Write web link file
            return IOUtils.toInputStream(UrlFileWriterFactory.get().write(link), Charset.defaultCharset());
        } else {
            if (status.isAppend()) {
                final HttpRange range = HttpRange.withStatus(status);
                final String header;
                if (-1 == range.getEnd()) {
                    header = String.format("%d-", range.getStart());
                } else {
                    header = String.format("%d-%d", range.getStart(), range.getEnd());
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Add range header %s for file %s", header, file));
                }
                return session.toFile(file).download(header);
            }
            return session.toFile(file).download();
        }
    } catch (OneDriveAPIException e) {
        throw new OneDriveExceptionMappingService().map("Download {0} failed", e, file);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map("Download {0} failed", e, file);
    }
}

From source file:de.shadowhunt.subversion.internal.ResourcePropertyUtilsTest.java

@Test
public void testEscapedInputStream_tagWithTagText() throws Exception {
    final String xml = "<C:foo:bar>text >/C:foo:bar</C:foo:bar>";
    final String expected = "<C:foo" + MARKER + "bar>text >/C:foo:bar</C:foo" + MARKER + "bar>";
    final InputStream stream = IOUtils.toInputStream(xml, ResourcePropertyUtils.UTF8);

    final InputStream escapedStream = ResourcePropertyUtils.escapedInputStream(stream);
    final String escapedXml = IOUtils.toString(escapedStream, ResourcePropertyUtils.UTF8);

    Assert.assertEquals(expected, escapedXml);
}

From source file:com.norconex.collector.http.pipeline.queue.RobotsTxtFiltersStageTest.java

private boolean testAllow(final String robotTxt, final String url) throws IOException {
    StandardRobotsTxtProvider provider = new StandardRobotsTxtProvider() {
        @Override//from   w w w . j ava  2s .  com
        public synchronized RobotsTxt getRobotsTxt(HttpClient httpClient, String url, String userAgent) {
            try {
                return parseRobotsTxt(IOUtils.toInputStream(robotTxt, CharEncoding.UTF_8), url, "test-crawler");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
    HttpCrawlerConfig cfg = new HttpCrawlerConfig();
    cfg.setRobotsTxtProvider(provider);

    HttpQueuePipelineContext ctx = new HttpQueuePipelineContext(new HttpCrawler(cfg), null,
            new HttpCrawlData(url, 0));
    RobotsTxtFiltersStage filterStage = new RobotsTxtFiltersStage();
    return filterStage.execute(ctx);
}

From source file:com.ppcxy.cyfm.showcase.demos.utilities.io.IODemo.java

@Test
public void workWithStream() {
    InputStream in = null;/*  www . j av a  2 s.co m*/
    try {
        String content = "Stream testing";

        // String - > InputStream.
        in = IOUtils.toInputStream(content, "UTF-8");

        // String - > OutputStream
        System.out.println("String to OutputStram:");
        IOUtils.write(content, System.out, "UTF-8");

        // //////////////////
        // InputStream/Reader -> String
        System.out.println("\nInputStram to String:");
        System.out.println(IOUtils.toString(in, "UTF-8"));

        // InputStream/Reader -> OutputStream/Writer ???.
        InputStream in2 = IOUtils.toInputStream(content); // ?inputSteam
        System.out.println("InputStream to OutputStream:");
        IOUtils.copy(in2, System.out);

        // /////////////////
        // InputStream ->Reader
        InputStreamReader reader = new InputStreamReader(in, Charsets.UTF_8);
        // Reader->InputStream
        ReaderInputStream in3 = new ReaderInputStream(reader, Charsets.UTF_8);

        // OutputStream ->Writer
        OutputStreamWriter writer = new OutputStreamWriter(System.out, Charsets.UTF_8);
        // Writer->OutputStream
        WriterOutputStream out2 = new WriterOutputStream(writer, Charsets.UTF_8);

        // ////////////////////
        // WriterString.
        StringWriter sw = new StringWriter();
        sw.write("I am String writer");
        System.out.println("\nCollect writer content:");
        System.out.println(sw.toString());

    } catch (IOException e) {
        Exceptions.unchecked(e);
    } finally {
        // ?Stream
        IOUtils.closeQuietly(in);
    }
}

From source file:com.telefonica.euro_iaas.sdc.util.HttpsClientTest.java

@Before
public void setup() throws KeyManagementException, NoSuchAlgorithmException, IOException {
    httpsURLConnection = mock(HttpsURLConnection.class);
    connectionSetup = mock(ConnectionSetup.class);
    headers.put(HttpsClient.HEADER_AUTH, "");
    headers.put(HttpsClient.HEADER_TENNANT, "");

    when(connectionSetup.createConnection((URL) anyObject())).thenReturn(httpsURLConnection);

    String source = "test";
    InputStream in = IOUtils.toInputStream(source, "UTF-8");
    when(httpsURLConnection.getInputStream()).thenReturn(in);

    OutputStream os = new OutputStream() {
        @Override/*from w ww  . ja  v a2s  . co m*/
        public void write(int b) throws IOException {
        }
    };
    when(httpsURLConnection.getOutputStream()).thenReturn(os);

    httpsClient = new HttpsClient();
    httpsClient.setConnectionSetup(connectionSetup);

}

From source file:eu.freme.eservices.pipelines.core.Conversion.java

public String nifToHtml(final String enrichedNIF) throws IOException {
    try (InputStream enrichedFile = IOUtils.toInputStream(enrichedNIF, StandardCharsets.UTF_8);
            InputStream skeletonFile = IOUtils.toInputStream(skeletonNIF, StandardCharsets.UTF_8)) {
        try (Reader htmlReader = eInternationalizationApi.convertBack(skeletonFile, enrichedFile)) {
            String html = IOUtils.toString(htmlReader);
            skeletonNIF = "";
            return html;
        }/*w w  w . ja v  a  2s .  c  o m*/
    }
}