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.net.io;
019
020import java.io.FilterOutputStream;
021import java.io.IOException;
022import java.io.OutputStream;
023
024/**
025 * This class wraps an output stream, replacing all occurrences of <CR><LF> (carriage return followed by a linefeed), which is the NETASCII standard
026 * for representing a newline, with the local line separator representation. You would use this class to implement ASCII file transfers requiring conversion
027 * from NETASCII.
028 * <p>
029 * Because of the translation process, a call to {@code flush()} will not flush the last byte written if that byte was a carriage return. A call to
030 * {@link #close close()}, however, will flush the carriage return.
031 * </p>
032 */
033public final class FromNetASCIIOutputStream extends FilterOutputStream {
034    private boolean lastWasCR;
035
036    /**
037     * Creates a FromNetASCIIOutputStream instance that wraps an existing OutputStream.
038     *
039     * @param output The OutputStream to wrap.
040     */
041    public FromNetASCIIOutputStream(final OutputStream output) {
042        super(output);
043    }
044
045    /**
046     * Closes the stream, writing all pending data.
047     *
048     * @throws IOException If an error occurs while closing the stream.
049     */
050    @Override
051    public synchronized void close() throws IOException {
052        if (FromNetASCIIInputStream.NO_CONVERSION_REQUIRED) {
053            super.close();
054            return;
055        }
056        if (lastWasCR) {
057            out.write('\r');
058        }
059        super.close();
060    }
061
062    /**
063     * Writes a byte array to the stream.
064     *
065     * @param buffer The byte array to write.
066     * @throws IOException If an error occurs while writing to the underlying stream.
067     */
068    @Override
069    public synchronized void write(final byte buffer[]) throws IOException {
070        write(buffer, 0, buffer.length);
071    }
072
073    /**
074     * Writes a number of bytes from a byte array to the stream starting from a given offset.
075     *
076     * @param buffer The byte array to write.
077     * @param offset The offset into the array at which to start copying data.
078     * @param length The number of bytes to write.
079     * @throws IOException If an error occurs while writing to the underlying stream.
080     */
081    @Override
082    public synchronized void write(final byte buffer[], int offset, int length) throws IOException {
083        if (FromNetASCIIInputStream.NO_CONVERSION_REQUIRED) {
084            // FilterOutputStream method is very slow.
085            // super.write(buffer, offset, length);
086            out.write(buffer, offset, length);
087            return;
088        }
089        while (length-- > 0) {
090            writeInt(buffer[offset++]);
091        }
092    }
093
094    /**
095     * Writes a byte to the stream. Note that a call to this method might not actually write a byte to the underlying stream until a subsequent character is
096     * written, from which it can be determined if a NETASCII line separator was encountered. This is transparent to the programmer and is only mentioned for
097     * completeness.
098     *
099     * @param ch The byte to write.
100     * @throws IOException If an error occurs while writing to the underlying stream.
101     */
102    @Override
103    public synchronized void write(final int ch) throws IOException {
104        if (FromNetASCIIInputStream.NO_CONVERSION_REQUIRED) {
105            out.write(ch);
106            return;
107        }
108        writeInt(ch);
109    }
110
111    private void writeInt(final int ch) throws IOException {
112        switch (ch) {
113        case '\r':
114            lastWasCR = true;
115            // Don't write anything. We need to see if next one is linefeed
116            break;
117        case '\n':
118            if (lastWasCR) {
119                out.write(FromNetASCIIInputStream.LINE_SEPARATOR_BYTES);
120                lastWasCR = false;
121                break;
122            }
123            out.write('\n');
124            break;
125        default:
126            if (lastWasCR) {
127                out.write('\r');
128                lastWasCR = false;
129            }
130            out.write(ch);
131            break;
132        }
133    }
134}