Example usage for org.apache.commons.io.input ReaderInputStream ReaderInputStream

List of usage examples for org.apache.commons.io.input ReaderInputStream ReaderInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input ReaderInputStream ReaderInputStream.

Prototype

public ReaderInputStream(Reader reader, String charsetName) 

Source Link

Document

Construct a new ReaderInputStream with a default input buffer size of 1024 characters.

Usage

From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java

@Test
public void testClob() throws Exception {
    try (final Statement stmt = con.createStatement()) {
        stmt.executeUpdate("CREATE TABLE clobtest (id INT, text CLOB(64 K))");
        stmt.execute("INSERT INTO blobtest VALUES (41, NULL)");
        PreparedStatement ps = con.prepareStatement("INSERT INTO clobtest VALUES (?, ?)");
        ps.setInt(1, 42);/*from   ww  w .ja v  a 2s .co m*/
        final char[] buffer = new char[4002];
        IntStream.range(0, 4002).forEach((i) -> buffer[i] = String.valueOf(i % 10).charAt(0));
        ReaderInputStream isr = new ReaderInputStream(new CharArrayReader(buffer), Charset.defaultCharset());

        // - set the value of the input parameter to the input stream
        ps.setAsciiStream(2, isr, 4002);
        ps.execute();
        isr.close();

        final ResultSet resultSet = stmt.executeQuery("select * from clobtest");

        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        JdbcCommon.convertToAvroStream(resultSet, outStream, false);

        final byte[] serializedBytes = outStream.toByteArray();
        assertNotNull(serializedBytes);

        // Deserialize bytes to records
        final InputStream instream = new ByteArrayInputStream(serializedBytes);

        final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
        try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) {
            GenericRecord record = null;
            while (dataFileReader.hasNext()) {
                // Reuse record object by passing it to next(). This saves us from
                // allocating and garbage collecting many objects for files with
                // many items.
                record = dataFileReader.next(record);
                Integer id = (Integer) record.get("ID");
                Object o = record.get("TEXT");
                if (id == 41) {
                    assertNull(o);
                } else {
                    assertNotNull(o);
                    assertEquals(4002, o.toString().length());
                }
            }
        }
    }
}

From source file:org.apache.synapse.transport.passthru.util.RelayUtilsTest.java

@Test
public void testBinaryRelayPayloadExpandsToOriginalPayload() throws IOException, XMLStreamException {

    // Transform request soap message into a binary payload
    BinaryRelayBuilder builder = new BinaryRelayBuilder();
    InputStream stream = new ReaderInputStream(new StringReader(xml), UTF8);
    OMElement element = builder.processDocument(stream, "text/xml", msgCtx);
    msgCtx.setEnvelope((SOAPEnvelope) element);

    // Build message when using pass through pipe or binary relay builder
    RelayUtils.buildMessage(msgCtx);//from w ww  . ja  v  a  2 s. c  o  m

    // Ensure that the binary payload is transformed to the appropriate element
    assertEquals(payloadQName, msgCtx.getEnvelope().getBody().getFirstElement().getQName());

    // Ensure that the body isn't fully build to support the use of deferred building
    assertFalse(msgCtx.getEnvelope().getBody().isComplete());
}

From source file:org.codice.ddf.admin.application.service.migratable.ProfileMigratableTest.java

private static Answer callWithJson(MigrationReport report) {
    return AdditionalAnswers
            .<Boolean, BiThrowingConsumer<MigrationReport, Optional<InputStream>, IOException>>answer(c -> {
                // callback the consumer
                c.accept(report, Optional.of(
                        new ReaderInputStream(new StringReader(JSON_PROFILE_STR), Charset.defaultCharset())));
                return true;
            });/* w w  w.j a va2  s . co m*/
}

From source file:org.culturegraph.mf.io.TarReader.java

@Override
public void process(final Reader reader) {
    try (InputStream stream = new ReaderInputStream(reader, Charset.defaultCharset());
            ArchiveInputStream tarStream = new TarArchiveInputStream(stream);) {
        ArchiveEntry entry;//w w  w. j a va2 s.  co m
        while ((entry = tarStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                processFileEntry(tarStream);
            }
        }
    } catch (IOException e) {
        throw new MetafactureException(e);
    }
}

From source file:org.jenkinsci.plugins.workflow.job.WorkflowRun.java

/**
 * Equivalent to calling {@link LargeText#writeLogTo(long, OutputStream)} without the unwanted override in {@link AnnotatedLargeText} that wraps in a {@link PlainTextConsoleOutputStream}.
 * TODO replace with {@code AnnotatedLargeText#writeRawLogTo} in 1.577
 *//* w  w w. j a v  a2 s. co  m*/
private static long writeLogTo(AnnotatedLargeText<?> text, long position, OutputStream os) throws IOException {
    Charset c;
    try {
        Field f = LargeText.class.getDeclaredField("charset");
        f.setAccessible(true);
        c = (Charset) f.get(text);
    } catch (Exception x) {
        LOGGER.log(Level.WARNING, null, x);
        return text.writeLogTo(position, os); // give up
    }
    Reader r = text.readAll();
    try {
        InputStream is = new ReaderInputStream(r, c);
        is.skip(position);
        return position + IOUtils.copyLarge(is, os);
    } finally {
        r.close();
    }
}

From source file:org.lockss.filter.RisFilterReader.java

/**
 * <p>/* w  w  w .  j ava 2 s . c  o  m*/
 * A convenience method to turn this {@link Reader} back into an
 * {@link InputStream}.
 * </p>
 * 
 * @param encoding
 *          An output encoding.
 * @return This {@link Reader} as an {@link InputStream}.
 * @since 1.66
 */
public InputStream toInputStream(String encoding) {
    // The ReaderInputStream from Commons IO, not org.lockss.util
    return new ReaderInputStream(this, encoding);
}

From source file:org.nuxeo.ecm.platform.convert.plugins.UTF8CharsetConverter.java

protected Blob convert(Blob blob) throws IOException, ConversionException {
    String mimetype = blob.getMimeType();
    if (mimetype == null || !mimetype.startsWith(TEXT_PREFIX)) {
        return blob;
    }//from   w  ww  .  java2s  .c om
    String encoding = blob.getEncoding();
    if (UTF_8.equals(encoding)) {
        return blob;
    }
    if (StringUtils.isEmpty(encoding)) {
        try (InputStream in = blob.getStream()) {
            encoding = detectEncoding(in);
        }
    }
    Blob newBlob;
    if (UTF_8.equals(encoding)) {
        // had no encoding previously, detected as UTF-8
        // just reuse the same blob
        try (InputStream in = blob.getStream()) {
            newBlob = Blobs.createBlob(in);
        }
    } else {
        // decode bytes as chars in the detected charset then encode chars as bytes in UTF-8
        try (InputStream in = new ReaderInputStream(new InputStreamReader(blob.getStream(), encoding), UTF_8)) {
            newBlob = Blobs.createBlob(in);
        }
    }
    newBlob.setMimeType(mimetype);
    newBlob.setEncoding(UTF_8);
    newBlob.setFilename(blob.getFilename());
    return newBlob;
}

From source file:org.nuxeo.ecm.web.resources.wro.processor.FlavorResourceProcessor.java

@Override
protected void process(final Resource resource, final Reader reader, final Writer writer, String flavorName)
        throws IOException {
    final InputStream is = new ProxyInputStream(new ReaderInputStream(reader, getEncoding())) {
    };/*from ww  w .  j  a  va  2s .co m*/
    final OutputStream os = new ProxyOutputStream(new WriterOutputStream(writer, getEncoding()));
    try {
        Map<String, String> presets = null;
        if (flavorName != null) {
            ThemeStylingService s = Framework.getService(ThemeStylingService.class);
            presets = s.getPresetVariables(flavorName);
        }
        if (presets == null || presets.isEmpty()) {
            IOUtils.copy(is, os);
        } else {
            String content = IOUtils.toString(reader);
            for (Map.Entry<String, String> preset : presets.entrySet()) {
                content = Pattern.compile("\"" + preset.getKey() + "\"", Pattern.LITERAL).matcher(content)
                        .replaceAll(Matcher.quoteReplacement(preset.getValue()));
            }
            writer.write(content);
            writer.flush();
        }
        is.close();
    } catch (final Exception e) {
        log.error("Error while serving resource " + resource.getUri(), e);
        throw WroRuntimeException.wrap(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.nuxeo.theme.styling.wro.FlavorResourceProcessor.java

protected void process(final Resource resource, final Reader reader, final Writer writer, String flavorName)
        throws IOException {
    final InputStream is = new ProxyInputStream(new ReaderInputStream(reader, getEncoding())) {
    };//from   w ww.j  av a 2s. co m
    final OutputStream os = new ProxyOutputStream(new WriterOutputStream(writer, getEncoding()));
    try {
        Map<String, String> presets = null;
        if (flavorName != null) {
            ThemeStylingService s = Framework.getService(ThemeStylingService.class);
            presets = s.getPresetVariables(flavorName);
        }
        if (presets == null || presets.isEmpty()) {
            IOUtils.copy(is, os);
        } else {
            String content = IOUtils.toString(reader);
            for (Map.Entry<String, String> preset : presets.entrySet()) {
                content = Pattern.compile(String.format("\"%s\"", preset.getKey()), Pattern.LITERAL)
                        .matcher(content).replaceAll(Matcher.quoteReplacement(preset.getValue()));
            }
            writer.write(content);
            writer.flush();
        }
        is.close();
        os.close();
    } catch (final Exception e) {
        throw WroRuntimeException.wrap(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.obm.push.cassandra.dao.SchemaCQLDataSet.java

@Override
protected InputStream getInputDataSetLocation(String dataSetLocation) {
    if (Strings.isNullOrEmpty(schema)) {
        return new ReaderInputStream(new StringReader(""), Charsets.UTF_8);
    }/*from  ww  w . j  a  v a2s. c  om*/
    return new ReaderInputStream(new StringReader(schema), Charsets.UTF_8);
}