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 *      https://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 */
017
018package org.apache.commons.codec.binary;
019
020import java.io.OutputStream;
021
022import org.apache.commons.codec.CodecPolicy;
023import org.apache.commons.codec.binary.BaseNCodecOutputStream.AbstractBuilder; // NOPMD: Required by ECJ (Eclipse)
024
025/**
026 * Provides Base64 encoding in a streaming fashion (unlimited size). When encoding the default lineLength is 76 characters and the default lineEnding is CRLF,
027 * but these can be overridden by using the appropriate constructor.
028 * <p>
029 * The default behavior of the Base64OutputStream is to ENCODE, whereas the default behavior of the Base64InputStream is to DECODE. But this behavior can be
030 * overridden by using a different constructor.
031 * </p>
032 * <p>
033 * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One:
034 * Format of Internet Message Bodies</cite> by Freed and Borenstein.
035 * </p>
036 * <p>
037 * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode character encodings which are
038 * compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
039 * </p>
040 * <p>
041 * <strong>Note:</strong> It is mandatory to close the stream after the last byte has been written to it, otherwise the final padding will be omitted and the
042 * resulting data will be incomplete/inconsistent.
043 * </p>
044 * <p>
045 * You can set the decoding behavior when the input bytes contain leftover trailing bits that cannot be created by a valid encoding. These can be bits that are
046 * unused from the final character or entire characters. The default mode is lenient decoding.
047 * </p>
048 * <ul>
049 * <li>Lenient: Any trailing bits are composed into 8-bit bytes where possible. The remainder are discarded.
050 * <li>Strict: The decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid encoding. Any unused bits from the final
051 * character must be zero. Impossible counts of entire final characters are not allowed.
052 * </ul>
053 * <p>
054 * When strict decoding is enabled it is expected that the decoded bytes will be re-encoded to a byte array that matches the original, i.e. no changes occur on
055 * the final character. This requires that the input bytes use the same padding and alphabet as the encoder.
056 * </p>
057 *
058 * @see Base64
059 * @see <a href="https://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
060 * @since 1.4
061 */
062public class Base64OutputStream extends BaseNCodecOutputStream<Base64, Base64OutputStream, Base64OutputStream.Builder> {
063
064    /**
065     * Builds instances of Base32InputStream.
066     *
067     * @since 1.20.0
068     */
069    public static class Builder extends AbstractBuilder<Base64OutputStream, Base64, Builder> {
070
071        /**
072         * Constructs a new instance.
073         */
074        public Builder() {
075            setEncode(true);
076        }
077
078        @Override
079        public Base64OutputStream get() {
080            return new Base64OutputStream(this);
081        }
082
083        @Override
084        protected Base64 newBaseNCodec() {
085            return new Base64();
086        }
087    }
088
089    /**
090     * Constructs a new Builder.
091     *
092     * @return a new Builder.
093     */
094    public static Builder builder() {
095        return new Builder();
096    }
097
098    private Base64OutputStream(final Builder builder) {
099        super(builder);
100    }
101
102    /**
103     * Constructs a Base64OutputStream such that all data written is Base64-encoded to the original provided OutputStream.
104     *
105     * @param outputStream OutputStream to wrap.
106     */
107    public Base64OutputStream(final OutputStream outputStream) {
108        this(builder().setOutputStream(outputStream));
109    }
110
111    /**
112     * Constructs a Base64OutputStream such that all data written is either Base64-encoded or Base64-decoded to the original provided OutputStream.
113     *
114     * @param outputStream OutputStream to wrap.
115     * @param encode     true if we should encode all data written to us, false if we should decode.
116     * @deprecated Use {@link #builder()} and {@link Builder}.
117     */
118    @Deprecated
119    public Base64OutputStream(final OutputStream outputStream, final boolean encode) {
120        super(builder().setOutputStream(outputStream).setEncode(encode));
121    }
122
123    /**
124     * Constructs a Base64OutputStream such that all data written is either Base64-encoded or Base64-decoded to the original provided OutputStream.
125     *
126     * @param outputStream  OutputStream to wrap.
127     * @param encode      true if we should encode all data written to us, false if we should decode.
128     * @param lineLength    If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to the nearest multiple of 4). If
129     *                      lineLength &lt;= 0, the encoded data is not divided into lines. If doEncode is false, lineLength is ignored.
130     * @param lineSeparator If doEncode is true, each line of encoded data will be terminated with this byte sequence (for example \r\n). If lineLength &lt;= 0,
131     *                      the lineSeparator is not used. If doEncode is false lineSeparator is ignored.
132     * @deprecated Use {@link #builder()} and {@link Builder}.
133     */
134    @Deprecated
135    public Base64OutputStream(final OutputStream outputStream, final boolean encode, final int lineLength, final byte[] lineSeparator) {
136        super(builder().setOutputStream(outputStream).setEncode(encode)
137                .setBaseNCodec(Base64.builder().setLineLength(lineLength).setLineSeparator(lineSeparator).get()));
138    }
139
140    /**
141     * Constructs a Base64OutputStream such that all data written is either Base64-encoded or Base64-decoded to the original provided OutputStream.
142     *
143     * @param outputStream   OutputStream to wrap.
144     * @param encode       true if we should encode all data written to us, false if we should decode.
145     * @param lineLength     If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to the nearest multiple of 4). If
146     *                       lineLength &lt;= 0, the encoded data is not divided into lines. If doEncode is false, lineLength is ignored.
147     * @param lineSeparator  If doEncode is true, each line of encoded data will be terminated with this byte sequence (for example \r\n). If lineLength &lt;=
148     *                       0, the lineSeparator is not used. If doEncode is false lineSeparator is ignored.
149     * @param decodingPolicy The decoding policy.
150     * @since 1.15
151     * @deprecated Use {@link #builder()} and {@link Builder}.
152     */
153    @Deprecated
154    public Base64OutputStream(final OutputStream outputStream, final boolean encode, final int lineLength, final byte[] lineSeparator,
155            final CodecPolicy decodingPolicy) {
156        super(builder().setOutputStream(outputStream).setEncode(encode)
157                .setBaseNCodec(Base64.builder().setLineLength(lineLength).setLineSeparator(lineSeparator).setDecodingPolicy(decodingPolicy).get()));
158    }
159}