001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.io.output;
018
019import java.io.IOException;
020import java.io.OutputStream;
021import java.io.Writer;
022import java.nio.ByteBuffer;
023import java.nio.CharBuffer;
024import java.nio.charset.Charset;
025import java.nio.charset.CharsetDecoder;
026import java.nio.charset.CoderResult;
027import java.nio.charset.CodingErrorAction;
028import java.nio.charset.StandardCharsets;
029
030import org.apache.commons.io.Charsets;
031import org.apache.commons.io.IOUtils;
032import org.apache.commons.io.build.AbstractStreamBuilder;
033import org.apache.commons.io.charset.CharsetDecoders;
034
035/**
036 * {@link OutputStream} implementation that transforms a byte stream to a character stream using a specified charset encoding and writes the resulting stream to
037 * a {@link Writer}. The stream is transformed using a {@link CharsetDecoder} object, guaranteeing that all charset encodings supported by the JRE are handled
038 * correctly.
039 * <p>
040 * The output of the {@link CharsetDecoder} is buffered using a fixed size buffer. This implies that the data is written to the underlying {@link Writer} in
041 * chunks that are no larger than the size of this buffer. By default, the buffer is flushed only when it overflows or when {@link #flush()} or {@link #close()}
042 * is called. In general there is therefore no need to wrap the underlying {@link Writer} in a {@link java.io.BufferedWriter}. {@link WriterOutputStream} can
043 * also be instructed to flush the buffer after each write operation. In this case, all available data is written immediately to the underlying {@link Writer},
044 * implying that the current position of the {@link Writer} is correlated to the current position of the {@link WriterOutputStream}.
045 * </p>
046 * <p>
047 * {@link WriterOutputStream} implements the inverse transformation of {@link java.io.OutputStreamWriter}; in the following example, writing to {@code out2}
048 * would have the same result as writing to {@code out} directly (provided that the byte sequence is legal with respect to the charset encoding):
049 * </p>
050 * <p>
051 * To build an instance, see {@link Builder}.
052 * </p>
053 * <pre>
054 * OutputStream out = ...
055 * Charset cs = ...
056 * OutputStreamWriter writer = new OutputStreamWriter(out, cs);
057 * WriterOutputStream out2 = WriterOutputStream.builder()
058 *   .setWriter(writer)
059 *   .setCharset(cs)
060 *   .get();
061 * </pre>
062 * <p>
063 * {@link WriterOutputStream} implements the same transformation as {@link java.io.InputStreamReader}, except that the control flow is reversed: both classes
064 * transform a byte stream into a character stream, but {@link java.io.InputStreamReader} pulls data from the underlying stream, while
065 * {@link WriterOutputStream} pushes it to the underlying stream.
066 * </p>
067 * <p>
068 * 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
069 * the design of the code. This class is typically used in situations where an existing API only accepts an {@link OutputStream} object, but where the stream is
070 * known to represent character data that must be decoded for further use.
071 * </p>
072 * <p>
073 * Instances of {@link WriterOutputStream} are not thread safe.
074 * </p>
075 *
076 * @see org.apache.commons.io.input.ReaderInputStream
077 * @since 2.0
078 */
079public class WriterOutputStream extends OutputStream {
080
081    /**
082     * Builds a new {@link WriterOutputStream} instance.
083     * <p>
084     * For example:
085     * </p>
086     * <pre>{@code
087     * WriterOutputStream s = WriterOutputStream.builder()
088     *   .setPath(path)
089     *   .setBufferSize(8192)
090     *   .setCharset(StandardCharsets.UTF_8)
091     *   .setWriteImmediately(false)
092     *   .get();}
093     * </pre>
094     *
095     * @since 2.12.0
096     */
097    public static class Builder extends AbstractStreamBuilder<WriterOutputStream, Builder> {
098
099        private CharsetDecoder charsetDecoder;
100        private boolean writeImmediately;
101
102        public Builder() {
103            this.charsetDecoder = getCharset().newDecoder();
104        }
105
106        /**
107         * Constructs a new instance.
108         * <p>
109         * This builder use the aspect Writer, OpenOption[], Charset, CharsetDecoder, buffer size and writeImmediately.
110         * </p>
111         * <p>
112         * You must provide an origin that can be converted to a Writer by this builder, otherwise, this call will throw an
113         * {@link UnsupportedOperationException}.
114         * </p>
115         *
116         * @return a new instance.
117         * @throws UnsupportedOperationException if the origin cannot provide a Writer.
118         * @see #getWriter()
119         */
120        @SuppressWarnings("resource")
121        @Override
122        public WriterOutputStream get() throws IOException {
123            return new WriterOutputStream(getWriter(), charsetDecoder, getBufferSize(), writeImmediately);
124        }
125
126        @Override
127        public Builder setCharset(final Charset charset) {
128            super.setCharset(charset);
129            this.charsetDecoder = getCharset().newDecoder();
130            return this;
131        }
132
133        @Override
134        public Builder setCharset(final String charset) {
135            super.setCharset(charset);
136            this.charsetDecoder = getCharset().newDecoder();
137            return this;
138        }
139
140        /**
141         * Sets the charset decoder.
142         *
143         * @param charsetDecoder the charset decoder.
144         * @return this
145         */
146        public Builder setCharsetDecoder(final CharsetDecoder charsetDecoder) {
147            this.charsetDecoder = charsetDecoder != null ? charsetDecoder : getCharsetDefault().newDecoder();
148            super.setCharset(this.charsetDecoder.charset());
149            return this;
150        }
151
152        /**
153         * Sets whether the output buffer will be flushed after each write operation ({@code true}), i.e. all available data will be written to the underlying
154         * {@link Writer} immediately. If {@code false}, the output buffer will only be flushed when it overflows or when {@link #flush()} or {@link #close()}
155         * is called.
156         *
157         * @param writeImmediately If {@code true} the output buffer will be flushed after each write operation, i.e. all available data will be written to the
158         *                         underlying {@link Writer} immediately. If {@code false}, the output buffer will only be flushed when it overflows or when
159         *                         {@link #flush()} or {@link #close()} is called.
160         * @return this
161         */
162        public Builder setWriteImmediately(final boolean writeImmediately) {
163            this.writeImmediately = writeImmediately;
164            return this;
165        }
166
167    }
168
169    private static final int BUFFER_SIZE = IOUtils.DEFAULT_BUFFER_SIZE;
170
171    /**
172     * Constructs a new {@link Builder}.
173     *
174     * @return a new {@link Builder}.
175     * @since 2.12.0
176     */
177    public static Builder builder() {
178        return new Builder();
179    }
180
181    /**
182     * Checks if the JDK in use properly supports the given charset.
183     *
184     * @param charset the charset to check the support for
185     */
186    private static void checkIbmJdkWithBrokenUTF16(final Charset charset) {
187        if (!StandardCharsets.UTF_16.name().equals(charset.name())) {
188            return;
189        }
190        final String TEST_STRING_2 = "v\u00e9s";
191        final byte[] bytes = TEST_STRING_2.getBytes(charset);
192
193        final CharsetDecoder charsetDecoder2 = charset.newDecoder();
194        final ByteBuffer bb2 = ByteBuffer.allocate(16);
195        final CharBuffer cb2 = CharBuffer.allocate(TEST_STRING_2.length());
196        final int len = bytes.length;
197        for (int i = 0; i < len; i++) {
198            bb2.put(bytes[i]);
199            bb2.flip();
200            try {
201                charsetDecoder2.decode(bb2, cb2, i == len - 1);
202            } catch (final IllegalArgumentException e) {
203                throw new UnsupportedOperationException("UTF-16 requested when running on an IBM JDK with broken UTF-16 support. "
204                        + "Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
205            }
206            bb2.compact();
207        }
208        cb2.rewind();
209        if (!TEST_STRING_2.equals(cb2.toString())) {
210            throw new UnsupportedOperationException("UTF-16 requested when running on an IBM JDK with broken UTF-16 support. "
211                    + "Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
212        }
213
214    }
215
216    private final Writer writer;
217    private final CharsetDecoder decoder;
218
219    private final boolean writeImmediately;
220
221    /**
222     * ByteBuffer used as input for the decoder. This buffer can be small as it is used only to transfer the received data to the decoder.
223     */
224    private final ByteBuffer decoderIn = ByteBuffer.allocate(128);
225
226    /**
227     * CharBuffer used as output for the decoder. It should be somewhat larger as we write from this buffer to the underlying Writer.
228     */
229    private final CharBuffer decoderOut;
230
231    /**
232     * Constructs a new {@link WriterOutputStream} that uses the default character encoding and with a default output buffer size of {@value #BUFFER_SIZE}
233     * characters. The output buffer will only be flushed when it overflows or when {@link #flush()} or {@link #close()} is called.
234     *
235     * @param writer the target {@link Writer}
236     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
237     */
238    @Deprecated
239    public WriterOutputStream(final Writer writer) {
240        this(writer, Charset.defaultCharset(), BUFFER_SIZE, false);
241    }
242
243    /**
244     * Constructs a new {@link WriterOutputStream} with a default output buffer size of {@value #BUFFER_SIZE} characters. The output buffer will only be flushed
245     * when it overflows or when {@link #flush()} or {@link #close()} is called.
246     *
247     * @param writer  the target {@link Writer}
248     * @param charset the charset encoding
249     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
250     */
251    @Deprecated
252    public WriterOutputStream(final Writer writer, final Charset charset) {
253        this(writer, charset, BUFFER_SIZE, false);
254    }
255
256    /**
257     * Constructs a new {@link WriterOutputStream}.
258     *
259     * @param writer           the target {@link Writer}
260     * @param charset          the charset encoding
261     * @param bufferSize       the size of the output buffer in number of characters
262     * @param writeImmediately If {@code true} the output buffer will be flushed after each write operation, i.e. all available data will be written to the
263     *                         underlying {@link Writer} immediately. If {@code false}, the output buffer will only be flushed when it overflows or when
264     *                         {@link #flush()} or {@link #close()} is called.
265     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
266     */
267    @Deprecated
268    public WriterOutputStream(final Writer writer, final Charset charset, final int bufferSize, final boolean writeImmediately) {
269        // @formatter:off
270        this(writer,
271            Charsets.toCharset(charset).newDecoder()
272                    .onMalformedInput(CodingErrorAction.REPLACE)
273                    .onUnmappableCharacter(CodingErrorAction.REPLACE)
274                    .replaceWith("?"),
275             bufferSize,
276             writeImmediately);
277        // @formatter:on
278    }
279
280    /**
281     * Constructs a new {@link WriterOutputStream} with a default output buffer size of {@value #BUFFER_SIZE} characters. The output buffer will only be flushed
282     * when it overflows or when {@link #flush()} or {@link #close()} is called.
283     *
284     * @param writer  the target {@link Writer}
285     * @param decoder the charset decoder
286     * @since 2.1
287     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
288     */
289    @Deprecated
290    public WriterOutputStream(final Writer writer, final CharsetDecoder decoder) {
291        this(writer, decoder, BUFFER_SIZE, false);
292    }
293
294    /**
295     * Constructs a new {@link WriterOutputStream}.
296     *
297     * @param writer           the target {@link Writer}
298     * @param decoder          the charset decoder
299     * @param bufferSize       the size of the output buffer in number of characters
300     * @param writeImmediately If {@code true} the output buffer will be flushed after each write operation, i.e. all available data will be written to the
301     *                         underlying {@link Writer} immediately. If {@code false}, the output buffer will only be flushed when it overflows or when
302     *                         {@link #flush()} or {@link #close()} is called.
303     * @since 2.1
304     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
305     */
306    @Deprecated
307    public WriterOutputStream(final Writer writer, final CharsetDecoder decoder, final int bufferSize, final boolean writeImmediately) {
308        checkIbmJdkWithBrokenUTF16(CharsetDecoders.toCharsetDecoder(decoder).charset());
309        this.writer = writer;
310        this.decoder = CharsetDecoders.toCharsetDecoder(decoder);
311        this.writeImmediately = writeImmediately;
312        this.decoderOut = CharBuffer.allocate(bufferSize);
313    }
314
315    /**
316     * Constructs a new {@link WriterOutputStream} with a default output buffer size of {@value #BUFFER_SIZE} characters. The output buffer will only be flushed
317     * when it overflows or when {@link #flush()} or {@link #close()} is called.
318     *
319     * @param writer      the target {@link Writer}
320     * @param charsetName the name of the charset encoding
321     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
322     */
323    @Deprecated
324    public WriterOutputStream(final Writer writer, final String charsetName) {
325        this(writer, charsetName, BUFFER_SIZE, false);
326    }
327
328    /**
329     * Constructs a new {@link WriterOutputStream}.
330     *
331     * @param writer           the target {@link Writer}
332     * @param charsetName      the name of the charset encoding
333     * @param bufferSize       the size of the output buffer in number of characters
334     * @param writeImmediately If {@code true} the output buffer will be flushed after each write operation, i.e. all available data will be written to the
335     *                         underlying {@link Writer} immediately. If {@code false}, the output buffer will only be flushed when it overflows or when
336     *                         {@link #flush()} or {@link #close()} is called.
337     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
338     */
339    @Deprecated
340    public WriterOutputStream(final Writer writer, final String charsetName, final int bufferSize, final boolean writeImmediately) {
341        this(writer, Charsets.toCharset(charsetName), bufferSize, writeImmediately);
342    }
343
344    /**
345     * Close the stream. Any remaining content accumulated in the output buffer will be written to the underlying {@link Writer}. After that
346     * {@link Writer#close()} will be called.
347     *
348     * @throws IOException if an I/O error occurs.
349     */
350    @Override
351    public void close() throws IOException {
352        processInput(true);
353        flushOutput();
354        writer.close();
355    }
356
357    /**
358     * Flush the stream. Any remaining content accumulated in the output buffer will be written to the underlying {@link Writer}. After that
359     * {@link Writer#flush()} will be called.
360     *
361     * @throws IOException if an I/O error occurs.
362     */
363    @Override
364    public void flush() throws IOException {
365        flushOutput();
366        writer.flush();
367    }
368
369    /**
370     * Flush the output.
371     *
372     * @throws IOException if an I/O error occurs.
373     */
374    private void flushOutput() throws IOException {
375        if (decoderOut.position() > 0) {
376            writer.write(decoderOut.array(), 0, decoderOut.position());
377            decoderOut.rewind();
378        }
379    }
380
381    /**
382     * Decode the contents of the input ByteBuffer into a CharBuffer.
383     *
384     * @param endOfInput indicates end of input
385     * @throws IOException if an I/O error occurs.
386     */
387    private void processInput(final boolean endOfInput) throws IOException {
388        // Prepare decoderIn for reading
389        decoderIn.flip();
390        CoderResult coderResult;
391        while (true) {
392            coderResult = decoder.decode(decoderIn, decoderOut, endOfInput);
393            if (coderResult.isOverflow()) {
394                flushOutput();
395            } else if (coderResult.isUnderflow()) {
396                break;
397            } else {
398                // The decoder is configured to replace malformed input and unmappable characters,
399                // so we should not get here.
400                throw new IOException("Unexpected coder result");
401            }
402        }
403        // Discard the bytes that have been read
404        decoderIn.compact();
405    }
406
407    /**
408     * Write bytes from the specified byte array to the stream.
409     *
410     * @param b the byte array containing the bytes to write
411     * @throws IOException if an I/O error occurs.
412     */
413    @Override
414    public void write(final byte[] b) throws IOException {
415        write(b, 0, b.length);
416    }
417
418    /**
419     * Write bytes from the specified byte array to the stream.
420     *
421     * @param b   the byte array containing the bytes to write
422     * @param off the start offset in the byte array
423     * @param len the number of bytes to write
424     * @throws IOException if an I/O error occurs.
425     */
426    @Override
427    public void write(final byte[] b, int off, int len) throws IOException {
428        while (len > 0) {
429            final int c = Math.min(len, decoderIn.remaining());
430            decoderIn.put(b, off, c);
431            processInput(false);
432            len -= c;
433            off += c;
434        }
435        if (writeImmediately) {
436            flushOutput();
437        }
438    }
439
440    /**
441     * Write a single byte to the stream.
442     *
443     * @param b the byte to write
444     * @throws IOException if an I/O error occurs.
445     */
446    @Override
447    public void write(final int b) throws IOException {
448        write(new byte[] { (byte) b }, 0, 1);
449    }
450}