1 /*
   2  * Copyright (c) 1997, 2013, 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     public void write(byte[] b, int off, int len) throws IOException {
  85         for (int i = 0; i < len; i++)
  86             write(b[off + i]);
  87     }
  88 
  89     /**
  90      * Encodes <code>b.length</code> bytes to this output stream.
  91      * @param      b   the data to be written.
  92      * @exception  IOException  if an I/O error occurs.
  93      */
  94     public void write(byte[] b) throws IOException {
  95         write(b, 0, b.length);
  96     }
  97 
  98     /**
  99      * Encodes the specified <code>byte</code> to this output stream.
 100      * @param      c   the <code>byte</code>.
 101      * @exception  IOException  if an I/O error occurs.
 102      */
 103     public void write(int c) throws IOException {
 104         c = c & 0xff; // Turn off the MSB.
 105         if (gotSpace) { // previous character was <SPACE>
 106             if (c == '\r' || c == '\n')
 107                 // if CR/LF, we need to encode the <SPACE> char
 108                 output(' ', true);
 109             else // no encoding required, just output the char
 110                 output(' ', false);
 111             gotSpace = false;
 112         }
 113 
 114         if (c == '\r') {
 115             gotCR = true;
 116             outputCRLF();
 117         } else {
 118             if (c == '\n') {
 119                 if (gotCR)
 120                     // This is a CRLF sequence, we already output the
 121                     // corresponding CRLF when we got the CR, so ignore this
 122                     ;
 123                 else
 124                     outputCRLF();
 125             } else if (c == ' ') {
 126                 gotSpace = true;
 127             } else if (c < 040 || c >= 0177 || c == '=')
 128                 // Encoding required.
 129                 output(c, true);
 130             else // No encoding required
 131                 output(c, false);
 132             // whatever it was, it wasn't a CR
 133             gotCR = false;
 134         }
 135     }
 136 
 137     /**
 138      * Flushes this output stream and forces any buffered output bytes
 139      * to be encoded out to the stream.
 140      * @exception  IOException  if an I/O error occurs.
 141      */
 142     public void flush() throws IOException {
 143         out.flush();
 144     }
 145 
 146     /**
 147      * Forces any buffered output bytes to be encoded out to the stream
 148      * and closes this output stream
 149      */
 150     public void close() throws IOException {
 151         out.close();
 152     }
 153 
 154     private void outputCRLF() throws IOException {
 155         out.write('\r');
 156         out.write('\n');
 157         count = 0;
 158     }
 159 
 160     // The encoding table
 161     private final static char hex[] = {
 162         '0','1', '2', '3', '4', '5', '6', '7',
 163         '8','9', 'A', 'B', 'C', 'D', 'E', 'F'
 164     };
 165 
 166     protected void output(int c, boolean encode) throws IOException {
 167         if (encode) {
 168             if ((count += 3) > bytesPerLine) {
 169                 out.write('=');
 170                 out.write('\r');
 171                 out.write('\n');
 172                 count = 3; // set the next line's length
 173             }
 174             out.write('=');
 175             out.write(hex[c >> 4]);
 176             out.write(hex[c & 0xf]);
 177         } else {
 178             if (++count > bytesPerLine) {
 179                 out.write('=');
 180                 out.write('\r');
 181                 out.write('\n');
 182                 count = 1; // set the next line's length
 183             }
 184             out.write(c);
 185         }
 186     }
 187 
 188     /**** begin TEST program ***
 189     public static void main(String argv[]) throws Exception {
 190         FileInputStream infile = new FileInputStream(argv[0]);
 191         QPEncoderStream encoder = new QPEncoderStream(System.out);
 192         int c;
 193 
 194         while ((c = infile.read()) != -1)
 195             encoder.write(c);
 196         encoder.close();
 197     }
 198     *** end TEST program ***/
 199 }