BaseNCodecOutputStream.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.  *      https://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.codec.binary;

  18. import static org.apache.commons.codec.binary.BaseNCodec.EOF;

  19. import java.io.FilterOutputStream;
  20. import java.io.IOException;
  21. import java.io.OutputStream;
  22. import java.util.Objects;

  23. import org.apache.commons.codec.binary.BaseNCodec.Context;

  24. /**
  25.  * Abstract superclass for Base-N output streams.
  26.  * <p>
  27.  * To write the EOF marker without closing the stream, call {@link #eof()} or use an <a
  28.  * href="https://commons.apache.org/proper/commons-io/">Apache Commons IO</a> <a href=
  29.  * "https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/CloseShieldOutputStream.html"
  30.  * >CloseShieldOutputStream</a>.
  31.  * </p>
  32.  *
  33.  * @since 1.5
  34.  */
  35. public class BaseNCodecOutputStream extends FilterOutputStream {

  36.     private final boolean doEncode;

  37.     private final BaseNCodec baseNCodec;

  38.     private final byte[] singleByte = new byte[1];

  39.     private final Context context = new Context();

  40.     /**
  41.      * Constructs a new instance.
  42.      *
  43.      * TODO should this be protected?
  44.      *
  45.      * @param outputStream the underlying output or null.
  46.      * @param basedCodec a BaseNCodec.
  47.      * @param doEncode true to encode, false to decode, TODO should be an enum?
  48.      */
  49.     public BaseNCodecOutputStream(final OutputStream outputStream, final BaseNCodec basedCodec, final boolean doEncode) {
  50.         super(outputStream);
  51.         this.baseNCodec = basedCodec;
  52.         this.doEncode = doEncode;
  53.     }

  54.     /**
  55.      * Closes this output stream and releases any system resources associated with the stream.
  56.      * <p>
  57.      * To write the EOF marker without closing the stream, call {@link #eof()} or use an
  58.      * <a href="https://commons.apache.org/proper/commons-io/">Apache Commons IO</a> <a href=
  59.      * "https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/CloseShieldOutputStream.html"
  60.      * >CloseShieldOutputStream</a>.
  61.      * </p>
  62.      *
  63.      * @throws IOException
  64.      *             if an I/O error occurs.
  65.      */
  66.     @Override
  67.     public void close() throws IOException {
  68.         eof();
  69.         flush();
  70.         out.close();
  71.     }

  72.     /**
  73.      * Writes EOF.
  74.      *
  75.      * @since 1.11
  76.      */
  77.     public void eof() {
  78.         // Notify encoder of EOF (-1).
  79.         if (doEncode) {
  80.             baseNCodec.encode(singleByte, 0, EOF, context);
  81.         } else {
  82.             baseNCodec.decode(singleByte, 0, EOF, context);
  83.         }
  84.     }

  85.     /**
  86.      * Flushes this output stream and forces any buffered output bytes to be written out to the stream.
  87.      *
  88.      * @throws IOException
  89.      *             if an I/O error occurs.
  90.      */
  91.     @Override
  92.     public void flush() throws IOException {
  93.         flush(true);
  94.     }

  95.     /**
  96.      * Flushes this output stream and forces any buffered output bytes to be written out to the stream. If propagate is
  97.      * true, the wrapped stream will also be flushed.
  98.      *
  99.      * @param propagate
  100.      *            boolean flag to indicate whether the wrapped OutputStream should also be flushed.
  101.      * @throws IOException
  102.      *             if an I/O error occurs.
  103.      */
  104.     private void flush(final boolean propagate) throws IOException {
  105.         final int avail = baseNCodec.available(context);
  106.         if (avail > 0) {
  107.             final byte[] buf = new byte[avail];
  108.             final int c = baseNCodec.readResults(buf, 0, avail, context);
  109.             if (c > 0) {
  110.                 out.write(buf, 0, c);
  111.             }
  112.         }
  113.         if (propagate) {
  114.             out.flush();
  115.         }
  116.     }

  117.     /**
  118.      * Returns true if decoding behavior is strict. Decoding will raise an
  119.      * {@link IllegalArgumentException} if trailing bits are not part of a valid encoding.
  120.      *
  121.      * <p>
  122.      * The default is false for lenient encoding. Decoding will compose trailing bits
  123.      * into 8-bit bytes and discard the remainder.
  124.      * </p>
  125.      *
  126.      * @return true if using strict decoding
  127.      * @since 1.15
  128.      */
  129.     public boolean isStrictDecoding() {
  130.         return baseNCodec.isStrictDecoding();
  131.     }

  132.     /**
  133.      * Writes {@code len} bytes from the specified {@code b} array starting at {@code offset} to this
  134.      * output stream.
  135.      *
  136.      * @param array
  137.      *            source byte array
  138.      * @param offset
  139.      *            where to start reading the bytes
  140.      * @param len
  141.      *            maximum number of bytes to write
  142.      *
  143.      * @throws IOException
  144.      *             if an I/O error occurs.
  145.      * @throws NullPointerException
  146.      *             if the byte array parameter is null
  147.      * @throws IndexOutOfBoundsException
  148.      *             if offset, len or buffer size are invalid
  149.      */
  150.     @Override
  151.     public void write(final byte[] array, final int offset, final int len) throws IOException {
  152.         Objects.requireNonNull(array, "array");
  153.         if (offset < 0 || len < 0 || offset > array.length || offset + len > array.length) {
  154.             throw new IndexOutOfBoundsException();
  155.         }
  156.         if (len > 0) {
  157.             if (doEncode) {
  158.                 baseNCodec.encode(array, offset, len, context);
  159.             } else {
  160.                 baseNCodec.decode(array, offset, len, context);
  161.             }
  162.             flush(false);
  163.         }
  164.     }

  165.     /**
  166.      * Writes the specified {@code byte} to this output stream.
  167.      *
  168.      * @param i
  169.      *            source byte
  170.      * @throws IOException
  171.      *             if an I/O error occurs.
  172.      */
  173.     @Override
  174.     public void write(final int i) throws IOException {
  175.         singleByte[0] = (byte) i;
  176.         write(singleByte, 0, 1);
  177.     }

  178. }