ReaderInputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.io.input;

  18. import static org.apache.commons.io.IOUtils.EOF;

  19. import java.io.BufferedReader;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.InputStreamReader;
  23. import java.io.OutputStreamWriter;
  24. import java.io.Reader;
  25. import java.nio.ByteBuffer;
  26. import java.nio.CharBuffer;
  27. import java.nio.charset.Charset;
  28. import java.nio.charset.CharsetEncoder;
  29. import java.nio.charset.CoderResult;
  30. import java.nio.charset.CodingErrorAction;
  31. import java.util.Objects;

  32. import org.apache.commons.io.Charsets;
  33. import org.apache.commons.io.IOUtils;
  34. import org.apache.commons.io.build.AbstractStreamBuilder;
  35. import org.apache.commons.io.charset.CharsetEncoders;

  36. /**
  37.  * {@link InputStream} implementation that reads a character stream from a {@link Reader} and transforms it to a byte stream using a specified charset encoding.
  38.  * The stream is transformed using a {@link CharsetEncoder} object, guaranteeing that all charset encodings supported by the JRE are handled correctly. In
  39.  * particular for charsets such as UTF-16, the implementation ensures that one and only one byte order marker is produced.
  40.  * <p>
  41.  * Since in general it is not possible to predict the number of characters to be read from the {@link Reader} to satisfy a read request on the
  42.  * {@link ReaderInputStream}, all reads from the {@link Reader} are buffered. There is therefore no well defined correlation between the current position of the
  43.  * {@link Reader} and that of the {@link ReaderInputStream}. This also implies that in general there is no need to wrap the underlying {@link Reader} in a
  44.  * {@link BufferedReader}.
  45.  * </p>
  46.  * <p>
  47.  * {@link ReaderInputStream} implements the inverse transformation of {@link InputStreamReader}; in the following example, reading from {@code in2}
  48.  * would return the same byte sequence as reading from {@code in} (provided that the initial byte sequence is legal with respect to the charset encoding):
  49.  * </p>
  50.  * <p>
  51.  * To build an instance, use {@link Builder}.
  52.  * </p>
  53.  * <pre>
  54.  * InputStream inputStream = ...
  55.  * Charset cs = ...
  56.  * InputStreamReader reader = new InputStreamReader(inputStream, cs);
  57.  * ReaderInputStream in2 = ReaderInputStream.builder()
  58.  *   .setReader(reader)
  59.  *   .setCharset(cs)
  60.  *   .get();
  61.  * </pre>
  62.  * <p>
  63.  * {@link ReaderInputStream} implements the same transformation as {@link OutputStreamWriter}, except that the control flow is reversed: both classes
  64.  * transform a character stream into a byte stream, but {@link OutputStreamWriter} pushes data to the underlying stream, while {@link ReaderInputStream}
  65.  * pulls it from the underlying stream.
  66.  * </p>
  67.  * <p>
  68.  * Note that while there are use cases where there is no alternative to using this class, very often the need to use this class is an indication of a flaw in
  69.  * the design of the code. This class is typically used in situations where an existing API only accepts an {@link InputStream}, but where the most natural way
  70.  * to produce the data is as a character stream, by providing a {@link Reader} instance. An example of a situation where this problem may appear is when
  71.  * implementing the {@code javax.activation.DataSource} interface from the Java Activation Framework.
  72.  * </p>
  73.  * <p>
  74.  * The {@link #available()} method of this class always returns 0. The methods {@link #mark(int)} and {@link #reset()} are not supported.
  75.  * </p>
  76.  * <p>
  77.  * Instances of {@link ReaderInputStream} are not thread safe.
  78.  * </p>
  79.  *
  80.  * @see Builder
  81.  * @see org.apache.commons.io.output.WriterOutputStream
  82.  * @since 2.0
  83.  */
  84. public class ReaderInputStream extends AbstractInputStream {

  85.     // @formatter:off
  86.     /**
  87.      * Builds a new {@link ReaderInputStream}.
  88.      *
  89.      * <p>
  90.      * For example:
  91.      * </p>
  92.      * <pre>{@code
  93.      * ReaderInputStream s = ReaderInputStream.builder()
  94.      *   .setPath(path)
  95.      *   .setCharsetEncoder(Charset.defaultCharset().newEncoder())
  96.      *   .get();}
  97.      * </pre>
  98.      *
  99.      * @see #get()
  100.      * @since 2.12.0
  101.      */
  102.     // @formatter:on
  103.     public static class Builder extends AbstractStreamBuilder<ReaderInputStream, Builder> {

  104.         private CharsetEncoder charsetEncoder = newEncoder(getCharset());

  105.         /**
  106.          * Constructs a new builder of {@link ReaderInputStream}.
  107.          */
  108.         public Builder() {
  109.             // empty
  110.         }

  111.         /**
  112.          * Builds a new {@link ReaderInputStream}.
  113.          *
  114.          * <p>
  115.          * You must set an aspect that supports {@link #getReader()}, otherwise, this method throws an exception.
  116.          * </p>
  117.          * <p>
  118.          * This builder uses the following aspects:
  119.          * </p>
  120.          * <ul>
  121.          * <li>{@link #getReader()} gets the target aspect.</li>
  122.          * <li>{@link #getBufferSize()}</li>
  123.          * <li>{@link #getCharset()}</li>
  124.          * <li>{@link CharsetEncoder}</li>
  125.          * </ul>
  126.          *
  127.          * @return a new instance.
  128.          * @throws UnsupportedOperationException if the origin cannot provide a {@link Reader}.
  129.          * @throws IllegalStateException         if the {@code origin} is {@code null}.
  130.          * @throws IOException                   if an I/O error occurs converting to a {@link Reader} using {@link #getReader()}.
  131.          * @see #getReader()
  132.          * @see CharsetEncoder
  133.          * @see #getBufferSize()
  134.          * @see #getUnchecked()
  135.          */
  136.         @Override
  137.         public ReaderInputStream get() throws IOException {
  138.             return new ReaderInputStream(getReader(), charsetEncoder, getBufferSize());
  139.         }

  140.         CharsetEncoder getCharsetEncoder() {
  141.             return charsetEncoder;
  142.         }

  143.         @Override
  144.         public Builder setCharset(final Charset charset) {
  145.             super.setCharset(charset);
  146.             charsetEncoder = newEncoder(getCharset());
  147.             return this;
  148.         }

  149.         /**
  150.          * Sets the charset encoder. Assumes that the caller has configured the encoder.
  151.          *
  152.          * @param newEncoder the charset encoder, null resets to a default encoder.
  153.          * @return {@code this} instance.
  154.          */
  155.         public Builder setCharsetEncoder(final CharsetEncoder newEncoder) {
  156.             charsetEncoder = CharsetEncoders.toCharsetEncoder(newEncoder, () -> newEncoder(getCharsetDefault()));
  157.             super.setCharset(charsetEncoder.charset());
  158.             return this;
  159.         }

  160.     }

  161.     /**
  162.      * Constructs a new {@link Builder}.
  163.      *
  164.      * @return a new {@link Builder}.
  165.      * @since 2.12.0
  166.      */
  167.     public static Builder builder() {
  168.         return new Builder();
  169.     }

  170.     static int checkMinBufferSize(final CharsetEncoder charsetEncoder, final int bufferSize) {
  171.         final float minRequired = minBufferSize(charsetEncoder);
  172.         if (bufferSize < minRequired) {
  173.             throw new IllegalArgumentException(String.format("Buffer size %,d must be at least %s for a CharsetEncoder %s.", bufferSize, minRequired,
  174.                     charsetEncoder.charset().displayName()));
  175.         }
  176.         return bufferSize;
  177.     }

  178.     static float minBufferSize(final CharsetEncoder charsetEncoder) {
  179.         return charsetEncoder.maxBytesPerChar() * 2;
  180.     }

  181.     private static CharsetEncoder newEncoder(final Charset charset) {
  182.         // @formatter:off
  183.         return Charsets.toCharset(charset).newEncoder()
  184.                 .onMalformedInput(CodingErrorAction.REPLACE)
  185.                 .onUnmappableCharacter(CodingErrorAction.REPLACE);
  186.         // @formatter:on
  187.     }

  188.     private final Reader reader;

  189.     private final CharsetEncoder charsetEncoder;

  190.     /**
  191.      * CharBuffer used as input for the decoder. It should be reasonably large as we read data from the underlying Reader into this buffer.
  192.      */
  193.     private final CharBuffer encoderIn;
  194.     /**
  195.      * ByteBuffer used as output for the decoder. This buffer can be small as it is only used to transfer data from the decoder to the buffer provided by the
  196.      * caller.
  197.      */
  198.     private final ByteBuffer encoderOut;

  199.     private CoderResult lastCoderResult;

  200.     private boolean endOfInput;

  201.     /**
  202.      * Constructs a new {@link ReaderInputStream} that uses the virtual machine's {@link Charset#defaultCharset() default charset} with a default input buffer
  203.      * size of {@value IOUtils#DEFAULT_BUFFER_SIZE} characters.
  204.      *
  205.      * @param reader the target {@link Reader}
  206.      * @deprecated Use {@link ReaderInputStream#builder()} instead
  207.      */
  208.     @Deprecated
  209.     public ReaderInputStream(final Reader reader) {
  210.         this(reader, Charset.defaultCharset());
  211.     }

  212.     /**
  213.      * Constructs a new {@link ReaderInputStream} with a default input buffer size of {@value IOUtils#DEFAULT_BUFFER_SIZE} characters.
  214.      *
  215.      * <p>
  216.      * The encoder created for the specified charset will use {@link CodingErrorAction#REPLACE} for malformed input and unmappable characters.
  217.      * </p>
  218.      *
  219.      * @param reader  the target {@link Reader}
  220.      * @param charset the charset encoding
  221.      * @deprecated Use {@link ReaderInputStream#builder()} instead, will be protected for subclasses.
  222.      */
  223.     @Deprecated
  224.     public ReaderInputStream(final Reader reader, final Charset charset) {
  225.         this(reader, charset, IOUtils.DEFAULT_BUFFER_SIZE);
  226.     }

  227.     /**
  228.      * Constructs a new {@link ReaderInputStream}.
  229.      *
  230.      * <p>
  231.      * The encoder created for the specified charset will use {@link CodingErrorAction#REPLACE} for malformed input and unmappable characters.
  232.      * </p>
  233.      *
  234.      * @param reader     the target {@link Reader}.
  235.      * @param charset    the charset encoding.
  236.      * @param bufferSize the size of the input buffer in number of characters.
  237.      * @deprecated Use {@link ReaderInputStream#builder()} instead
  238.      */
  239.     @Deprecated
  240.     public ReaderInputStream(final Reader reader, final Charset charset, final int bufferSize) {
  241.         // @formatter:off
  242.         this(reader,
  243.             Charsets.toCharset(charset).newEncoder()
  244.                     .onMalformedInput(CodingErrorAction.REPLACE)
  245.                     .onUnmappableCharacter(CodingErrorAction.REPLACE),
  246.              bufferSize);
  247.         // @formatter:on
  248.     }

  249.     /**
  250.      * Constructs a new {@link ReaderInputStream}.
  251.      *
  252.      * <p>
  253.      * This constructor does not call {@link CharsetEncoder#reset() reset} on the provided encoder. The caller of this constructor should do this when providing
  254.      * an encoder which had already been in use.
  255.      * </p>
  256.      *
  257.      * @param reader         the target {@link Reader}
  258.      * @param charsetEncoder the charset encoder
  259.      * @since 2.1
  260.      * @deprecated Use {@link ReaderInputStream#builder()} instead
  261.      */
  262.     @Deprecated
  263.     public ReaderInputStream(final Reader reader, final CharsetEncoder charsetEncoder) {
  264.         this(reader, charsetEncoder, IOUtils.DEFAULT_BUFFER_SIZE);
  265.     }

  266.     /**
  267.      * Constructs a new {@link ReaderInputStream}.
  268.      *
  269.      * <p>
  270.      * This constructor does not call {@link CharsetEncoder#reset() reset} on the provided encoder. The caller of this constructor should do this when providing
  271.      * an encoder which had already been in use.
  272.      * </p>
  273.      *
  274.      * @param reader         the target {@link Reader}
  275.      * @param charsetEncoder the charset encoder, null defaults to the default Charset encoder.
  276.      * @param bufferSize     the size of the input buffer in number of characters
  277.      * @since 2.1
  278.      * @deprecated Use {@link ReaderInputStream#builder()} instead
  279.      */
  280.     @Deprecated
  281.     public ReaderInputStream(final Reader reader, final CharsetEncoder charsetEncoder, final int bufferSize) {
  282.         this.reader = reader;
  283.         this.charsetEncoder = CharsetEncoders.toCharsetEncoder(charsetEncoder);
  284.         this.encoderIn = CharBuffer.allocate(checkMinBufferSize(this.charsetEncoder, bufferSize));
  285.         this.encoderIn.flip();
  286.         this.encoderOut = ByteBuffer.allocate(128);
  287.         this.encoderOut.flip();
  288.     }

  289.     /**
  290.      * Constructs a new {@link ReaderInputStream} with a default input buffer size of {@value IOUtils#DEFAULT_BUFFER_SIZE} characters.
  291.      *
  292.      * <p>
  293.      * The encoder created for the specified charset will use {@link CodingErrorAction#REPLACE} for malformed input and unmappable characters.
  294.      * </p>
  295.      *
  296.      * @param reader      the target {@link Reader}
  297.      * @param charsetName the name of the charset encoding
  298.      * @deprecated Use {@link ReaderInputStream#builder()} instead
  299.      */
  300.     @Deprecated
  301.     public ReaderInputStream(final Reader reader, final String charsetName) {
  302.         this(reader, charsetName, IOUtils.DEFAULT_BUFFER_SIZE);
  303.     }

  304.     /**
  305.      * Constructs a new {@link ReaderInputStream}.
  306.      *
  307.      * <p>
  308.      * The encoder created for the specified charset will use {@link CodingErrorAction#REPLACE} for malformed input and unmappable characters.
  309.      * </p>
  310.      *
  311.      * @param reader      the target {@link Reader}
  312.      * @param charsetName the name of the charset encoding, null maps to the default Charset.
  313.      * @param bufferSize  the size of the input buffer in number of characters
  314.      * @deprecated Use {@link ReaderInputStream#builder()} instead
  315.      */
  316.     @Deprecated
  317.     public ReaderInputStream(final Reader reader, final String charsetName, final int bufferSize) {
  318.         this(reader, Charsets.toCharset(charsetName), bufferSize);
  319.     }

  320.     @Override
  321.     public int available() throws IOException {
  322.         if (encoderOut.hasRemaining()) {
  323.             return encoderOut.remaining();
  324.         }
  325.         return 0;
  326.     }

  327.     /**
  328.      * Closes the stream. This method will cause the underlying {@link Reader} to be closed.
  329.      *
  330.      * @throws IOException if an I/O error occurs.
  331.      */
  332.     @Override
  333.     public void close() throws IOException {
  334.         reader.close();
  335.         super.close();
  336.     }

  337.     /**
  338.      * Fills the internal char buffer from the reader.
  339.      *
  340.      * @throws IOException If an I/O error occurs
  341.      */
  342.     private void fillBuffer() throws IOException {
  343.         if (endOfInput) {
  344.             return;
  345.         }
  346.         if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) {
  347.             encoderIn.compact();
  348.             final int position = encoderIn.position();
  349.             // We don't use Reader#read(CharBuffer) here because it is more efficient
  350.             // to write directly to the underlying char array (the default implementation
  351.             // copies data to a temporary char array).
  352.             final int c = reader.read(encoderIn.array(), position, encoderIn.remaining());
  353.             if (c == EOF) {
  354.                 endOfInput = true;
  355.             } else {
  356.                 encoderIn.position(position + c);
  357.             }
  358.             encoderIn.flip();
  359.         }
  360.         encoderOut.compact();
  361.         lastCoderResult = charsetEncoder.encode(encoderIn, encoderOut, endOfInput);
  362.         if (endOfInput) {
  363.             lastCoderResult = charsetEncoder.flush(encoderOut);
  364.         }
  365.         if (lastCoderResult.isError()) {
  366.             lastCoderResult.throwException();
  367.         }
  368.         encoderOut.flip();
  369.     }

  370.     /**
  371.      * Gets the CharsetEncoder.
  372.      *
  373.      * @return the CharsetEncoder.
  374.      */
  375.     CharsetEncoder getCharsetEncoder() {
  376.         return charsetEncoder;
  377.     }

  378.     /**
  379.      * Reads a single byte.
  380.      *
  381.      * @return either the byte read or {@code -1} if the end of the stream has been reached
  382.      * @throws IOException if an I/O error occurs.
  383.      */
  384.     @Override
  385.     public int read() throws IOException {
  386.         checkOpen();
  387.         for (;;) {
  388.             if (encoderOut.hasRemaining()) {
  389.                 return encoderOut.get() & 0xFF;
  390.             }
  391.             fillBuffer();
  392.             if (endOfInput && !encoderOut.hasRemaining()) {
  393.                 return EOF;
  394.             }
  395.         }
  396.     }

  397.     /**
  398.      * Reads the specified number of bytes into an array.
  399.      *
  400.      * @param b the byte array to read into
  401.      * @return the number of bytes read or {@code -1} if the end of the stream has been reached
  402.      * @throws IOException if an I/O error occurs.
  403.      */
  404.     @Override
  405.     public int read(final byte[] b) throws IOException {
  406.         return read(b, 0, b.length);
  407.     }

  408.     /**
  409.      * Reads the specified number of bytes into an array.
  410.      *
  411.      * @param array the byte array to read into
  412.      * @param off   the offset to start reading bytes into
  413.      * @param len   the number of bytes to read
  414.      * @return the number of bytes read or {@code -1} if the end of the stream has been reached
  415.      * @throws IOException if an I/O error occurs.
  416.      */
  417.     @Override
  418.     public int read(final byte[] array, int off, int len) throws IOException {
  419.         Objects.requireNonNull(array, "array");
  420.         if (len < 0 || off < 0 || off + len > array.length) {
  421.             throw new IndexOutOfBoundsException("Array size=" + array.length + ", offset=" + off + ", length=" + len);
  422.         }
  423.         int read = 0;
  424.         if (len == 0) {
  425.             return 0; // Always return 0 if len == 0
  426.         }
  427.         while (len > 0) {
  428.             if (encoderOut.hasRemaining()) { // Data from the last read not fully copied
  429.                 final int c = Math.min(encoderOut.remaining(), len);
  430.                 encoderOut.get(array, off, c);
  431.                 off += c;
  432.                 len -= c;
  433.                 read += c;
  434.             } else if (endOfInput) { // Already reach EOF in the last read
  435.                 break;
  436.             } else { // Read again
  437.                 fillBuffer();
  438.             }
  439.         }
  440.         return read == 0 && endOfInput ? EOF : read;
  441.     }
  442. }