1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * @(#)QPEncoderStream.java   1.6 02/03/27
  28  */
  29 
  30 
  31 
  32 package com.sun.xml.internal.messaging.saaj.packaging.mime.util;
  33 
  34 import java.io.*;
  35 
  36 /**
  37  * This class implements a Quoted Printable Encoder. It is implemented as
  38  * a FilterOutputStream, so one can just wrap this class around
  39  * any output stream and write bytes into this filter. The Encoding
  40  * is done as the bytes are written out.
  41  *
  42  * @author John Mani
  43  */
  44 
  45 public class QPEncoderStream extends FilterOutputStream {
  46     private int count = 0;      // number of bytes that have been output
  47     private int bytesPerLine;   // number of bytes per line
  48     private boolean gotSpace = false;
  49     private boolean gotCR = false;
  50 
  51     /**
  52      * Create a QP encoder that encodes the specified input stream
  53      * @param out        the output stream
  54      * @param bytesPerLine  the number of bytes per line. The encoder
  55      *                   inserts a CRLF sequence after this many number
  56      *                   of bytes.
  57      */
  58     public QPEncoderStream(OutputStream out, int bytesPerLine) {
  59         super(out);
  60         // Subtract 1 to account for the '=' in the soft-return
  61         // at the end of a line
  62         this.bytesPerLine = bytesPerLine - 1;
  63     }
  64 
  65     /**
  66      * Create a QP encoder that encodes the specified input stream.
  67      * Inserts the CRLF sequence after outputting 76 bytes.
  68      * @param out        the output stream
  69      */
  70     public QPEncoderStream(OutputStream out) {
  71         this(out, 76);
  72     }
  73 
  74     /**
  75      * Encodes <code>len</code> bytes from the specified
  76      * <code>byte</code> array starting at offset <code>off</code> to
  77      * this output stream.
  78      *
  79      * @param      b     the data.
  80      * @param      off   the start offset in the data.
  81      * @param      len   the number of bytes to write.
  82      * @exception  IOException  if an I/O error occurs.
  83      */
  84     @Override
  85     public void write(byte[] b, int off, int len) throws IOException {
  86         for (int i = 0; i < len; i++)
  87             write(b[off + i]);
  88     }
  89 
  90     /**
  91      * Encodes <code>b.length</code> bytes to this output stream.
  92      * @param      b   the data to be written.
  93      * @exception  IOException  if an I/O error occurs.
  94      */
  95     @Override
  96     public void write(byte[] b) throws IOException {
  97         write(b, 0, b.length);
  98     }
  99 
 100     /**
 101      * Encodes the specified <code>byte</code> to this output stream.
 102      * @param      c   the <code>byte</code>.
 103      * @exception  IOException  if an I/O error occurs.
 104      */
 105     @Override
 106     public void write(int c) throws IOException {
 107         c = c & 0xff; // Turn off the MSB.
 108         if (gotSpace) { // previous character was <SPACE>
 109             if (c == '\r' || c == '\n')
 110                 // if CR/LF, we need to encode the <SPACE> char
 111                 output(' ', true);
 112             else // no encoding required, just output the char
 113                 output(' ', false);
 114             gotSpace = false;
 115         }
 116 
 117         if (c == '\r') {
 118             gotCR = true;
 119             outputCRLF();
 120         } else {
 121             if (c == '\n') {
 122                 if (gotCR)
 123                     // This is a CRLF sequence, we already output the
 124                     // corresponding CRLF when we got the CR, so ignore this
 125                     ;
 126                 else
 127                     outputCRLF();
 128             } else if (c == ' ') {
 129                 gotSpace = true;
 130             } else if (c < 040 || c >= 0177 || c == '=')
 131                 // Encoding required.
 132                 output(c, true);
 133             else // No encoding required
 134                 output(c, false);
 135             // whatever it was, it wasn't a CR
 136             gotCR = false;
 137         }
 138     }
 139 
 140     /**
 141      * Flushes this output stream and forces any buffered output bytes
 142      * to be encoded out to the stream.
 143      * @exception  IOException  if an I/O error occurs.
 144      */
 145     @Override
 146     public void flush() throws IOException {
 147         out.flush();
 148     }
 149 
 150     /**
 151      * Forces any buffered output bytes to be encoded out to the stream
 152      * and closes this output stream
 153      */
 154     @Override
 155     public void close() throws IOException {
 156         out.close();
 157     }
 158 
 159     private void outputCRLF() throws IOException {
 160         out.write('\r');
 161         out.write('\n');
 162         count = 0;
 163     }
 164 
 165     // The encoding table
 166     private final static char hex[] = {
 167         '0','1', '2', '3', '4', '5', '6', '7',
 168         '8','9', 'A', 'B', 'C', 'D', 'E', 'F'
 169     };
 170 
 171     protected void output(int c, boolean encode) throws IOException {
 172         if (encode) {
 173             if ((count += 3) > bytesPerLine) {
 174                 out.write('=');
 175                 out.write('\r');
 176                 out.write('\n');
 177                 count = 3; // set the next line's length
 178             }
 179             out.write('=');
 180             out.write(hex[c >> 4]);
 181             out.write(hex[c & 0xf]);
 182         } else {
 183             if (++count > bytesPerLine) {
 184                 out.write('=');
 185                 out.write('\r');
 186                 out.write('\n');
 187                 count = 1; // set the next line's length
 188             }
 189             out.write(c);
 190         }
 191     }
 192 
 193     /**** begin TEST program ***
 194     public static void main(String argv[]) throws Exception {
 195         FileInputStream infile = new FileInputStream(argv[0]);
 196         QPEncoderStream encoder = new QPEncoderStream(System.out);
 197         int c;
 198 
 199         while ((c = infile.read()) != -1)
 200             encoder.write(c);
 201         encoder.close();
 202     }
 203     *** end TEST program ***/
 204 }