QP Encoder Stream : Base64 « Development Class « Java






QP Encoder Stream

      
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

/*
 * @(#)QPEncoderStream.java 1.8 07/05/04
 */


import java.io.*;

/**
 * This class implements a Quoted Printable Encoder. It is implemented as
 * a FilterOutputStream, so one can just wrap this class around
 * any output stream and write bytes into this filter. The Encoding
 * is done as the bytes are written out.
 * 
 * @author John Mani
 */

public class QPEncoderStream extends FilterOutputStream {
    private int count = 0;  // number of bytes that have been output
    private int bytesPerLine; // number of bytes per line
    private boolean gotSpace = false;
    private boolean gotCR = false;

    /**
     * Create a QP encoder that encodes the specified input stream
     * @param out        the output stream
     * @param bytesPerLine  the number of bytes per line. The encoder
     *                   inserts a CRLF sequence after this many number
     *                   of bytes.
     */
    public QPEncoderStream(OutputStream out, int bytesPerLine) {
  super(out);
  // Subtract 1 to account for the '=' in the soft-return 
  // at the end of a line
  this.bytesPerLine = bytesPerLine - 1;
    }

    /**
     * Create a QP encoder that encodes the specified input stream.
     * Inserts the CRLF sequence after outputting 76 bytes.
     * @param out        the output stream
     */
    public QPEncoderStream(OutputStream out) {
  this(out, 76);  
    }

    /**
     * Encodes <code>len</code> bytes from the specified
     * <code>byte</code> array starting at offset <code>off</code> to
     * this output stream.
     *
     * @param      b     the data.
     * @param      off   the start offset in the data.
     * @param      len   the number of bytes to write.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(byte[] b, int off, int len) throws IOException {
  for (int i = 0; i < len; i++)
      write(b[off + i]);
    }

    /**
     * Encodes <code>b.length</code> bytes to this output stream.
     * @param      b   the data to be written.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(byte[] b) throws IOException {
  write(b, 0, b.length);
    }

    /**
     * Encodes the specified <code>byte</code> to this output stream.
     * @param      c   the <code>byte</code>.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(int c) throws IOException {
  c = c & 0xff; // Turn off the MSB.
  if (gotSpace) { // previous character was <SPACE>
      if (c == '\r' || c == '\n')
    // if CR/LF, we need to encode the <SPACE> char
    output(' ', true);
      else // no encoding required, just output the char
    output(' ', false);
      gotSpace = false;
  }

  if (c == '\r') {
      gotCR = true;
      outputCRLF();
  } else {
      if (c == '\n') {
    if (gotCR) 
        // This is a CRLF sequence, we already output the 
        // corresponding CRLF when we got the CR, so ignore this
        ;
    else
        outputCRLF();
      } else if (c == ' ') {
    gotSpace = true;
      } else if (c < 040 || c >= 0177 || c == '=')
    // Encoding required. 
    output(c, true);
      else // No encoding required
    output(c, false);
      // whatever it was, it wasn't a CR
      gotCR = false;
  }
    }

    /**
     * Flushes this output stream and forces any buffered output bytes
     * to be encoded out to the stream.
     * @exception  IOException  if an I/O error occurs.
     */
    public void flush() throws IOException {
  out.flush();
    }

    /**
     * Forces any buffered output bytes to be encoded out to the stream
     * and closes this output stream
     */
    public void close() throws IOException {
  out.close();
    }

    private void outputCRLF() throws IOException {
  out.write('\r');
  out.write('\n');
  count = 0;
    }

    // The encoding table
    private final static char hex[] = {
  '0','1', '2', '3', '4', '5', '6', '7',
  '8','9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    protected void output(int c, boolean encode) throws IOException {
  if (encode) {
      if ((count += 3) > bytesPerLine) {
    out.write('=');
        out.write('\r');
        out.write('\n');
    count = 3; // set the next line's length
      }
      out.write('=');
      out.write(hex[c >> 4]);
      out.write(hex[c & 0xf]);
  } else {
      if (++count > bytesPerLine) {
    out.write('=');
        out.write('\r');
        out.write('\n');
    count = 1; // set the next line's length
      }
      out.write(c);
  }
    }

    /**** begin TEST program ***
    public static void main(String argv[]) throws Exception {
        FileInputStream infile = new FileInputStream(argv[0]);
        QPEncoderStream encoder = new QPEncoderStream(System.out);
        int c;
 
        while ((c = infile.read()) != -1)
            encoder.write(c);
        encoder.close();
    }
    *** end TEST program ***/
}

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

/*
 * @(#)ASCIIUtility.java  1.11 07/05/04
 */
 class ASCIIUtility {

    // Private constructor so that this class is not instantiated
    private ASCIIUtility() { }
  
    /**
     * Convert the bytes within the specified range of the given byte 
     * array into a signed integer in the given radix . The range extends 
     * from <code>start</code> till, but not including <code>end</code>. <p>
     *
     * Based on java.lang.Integer.parseInt()
     */
    public static int parseInt(byte[] b, int start, int end, int radix)
    throws NumberFormatException {
  if (b == null)
      throw new NumberFormatException("null");
  
  int result = 0;
  boolean negative = false;
  int i = start;
  int limit;
  int multmin;
  int digit;

  if (end > start) {
      if (b[i] == '-') {
    negative = true;
    limit = Integer.MIN_VALUE;
    i++;
      } else {
    limit = -Integer.MAX_VALUE;
      }
      multmin = limit / radix;
      if (i < end) {
    digit = Character.digit((char)b[i++], radix);
    if (digit < 0) {
        throw new NumberFormatException(
      "illegal number: " + toString(b, start, end)
      );
    } else {
        result = -digit;
    }
      }
      while (i < end) {
    // Accumulating negatively avoids surprises near MAX_VALUE
    digit = Character.digit((char)b[i++], radix);
    if (digit < 0) {
        throw new NumberFormatException("illegal number");
    }
    if (result < multmin) {
        throw new NumberFormatException("illegal number");
    }
    result *= radix;
    if (result < limit + digit) {
        throw new NumberFormatException("illegal number");
    }
    result -= digit;
      }
  } else {
      throw new NumberFormatException("illegal number");
  }
  if (negative) {
      if (i > start + 1) {
    return result;
      } else {  /* Only got "-" */
    throw new NumberFormatException("illegal number");
      }
  } else {
      return -result;
  }
    }

    /**
     * Convert the bytes within the specified range of the given byte 
     * array into a signed integer . The range extends from 
     * <code>start</code> till, but not including <code>end</code>. <p>
     */
    public static int parseInt(byte[] b, int start, int end)
    throws NumberFormatException {
  return parseInt(b, start, end, 10);
    }

    /**
     * Convert the bytes within the specified range of the given byte 
     * array into a signed long in the given radix . The range extends 
     * from <code>start</code> till, but not including <code>end</code>. <p>
     *
     * Based on java.lang.Long.parseLong()
     */
    public static long parseLong(byte[] b, int start, int end, int radix)
    throws NumberFormatException {
  if (b == null)
      throw new NumberFormatException("null");
  
  long result = 0;
  boolean negative = false;
  int i = start;
  long limit;
  long multmin;
  int digit;

  if (end > start) {
      if (b[i] == '-') {
    negative = true;
    limit = Long.MIN_VALUE;
    i++;
      } else {
    limit = -Long.MAX_VALUE;
      }
      multmin = limit / radix;
      if (i < end) {
    digit = Character.digit((char)b[i++], radix);
    if (digit < 0) {
        throw new NumberFormatException(
      "illegal number: " + toString(b, start, end)
      );
    } else {
        result = -digit;
    }
      }
      while (i < end) {
    // Accumulating negatively avoids surprises near MAX_VALUE
    digit = Character.digit((char)b[i++], radix);
    if (digit < 0) {
        throw new NumberFormatException("illegal number");
    }
    if (result < multmin) {
        throw new NumberFormatException("illegal number");
    }
    result *= radix;
    if (result < limit + digit) {
        throw new NumberFormatException("illegal number");
    }
    result -= digit;
      }
  } else {
      throw new NumberFormatException("illegal number");
  }
  if (negative) {
      if (i > start + 1) {
    return result;
      } else {  /* Only got "-" */
    throw new NumberFormatException("illegal number");
      }
  } else {
      return -result;
  }
    }

    /**
     * Convert the bytes within the specified range of the given byte 
     * array into a signed long . The range extends from 
     * <code>start</code> till, but not including <code>end</code>. <p>
     */
    public static long parseLong(byte[] b, int start, int end)
    throws NumberFormatException {
  return parseLong(b, start, end, 10);
    }

    /**
     * Convert the bytes within the specified range of the given byte 
     * array into a String. The range extends from <code>start</code>
     * till, but not including <code>end</code>. <p>
     */
    public static String toString(byte[] b, int start, int end) {
  int size = end - start;
  char[] theChars = new char[size];

  for (int i = 0, j = start; i < size; )
      theChars[i++] = (char)(b[j++]&0xff);
  
  return new String(theChars);
    }

    public static String toString(ByteArrayInputStream is) {
  int size = is.available();
  char[] theChars = new char[size];
  byte[] bytes    = new byte[size];

  is.read(bytes, 0, size);
  for (int i = 0; i < size;)
      theChars[i] = (char)(bytes[i++]&0xff);
  
  return new String(theChars);
    }


    public static byte[] getBytes(String s) {
  char [] chars= s.toCharArray();
  int size = chars.length;
  byte[] bytes = new byte[size];
      
  for (int i = 0; i < size;)
      bytes[i] = (byte) chars[i++];
  return bytes;
    }

    public static byte[] getBytes(InputStream is) throws IOException {

  int len;
  int size = 1024;
  byte [] buf;


  if (is instanceof ByteArrayInputStream) {
      size = is.available();
      buf = new byte[size];
      len = is.read(buf, 0, size);
  }
  else {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      buf = new byte[size];
      while ((len = is.read(buf, 0, size)) != -1)
    bos.write(buf, 0, len);
      buf = bos.toByteArray();
  }
  return buf;
    }
}

   
    
    
    
    
    
  








Related examples in the same category

1.Base64 encoding/decoding.
2.Decodes Base64 data into octects
3.Implementation of MIME's Base64 encoding and decoding conversions.
4.Encode/decode for RFC 2045 Base64 as defined by RFC 2045
5.Encode/decode for RFC 2045 Base64 as defined by RFC 2045, N. Freed and N. Borenstein.
6.Encodes and decodes to and from Base64 notation.
7.Encodes hex octects into Base64
8.Helper class to provide Base64 encoding routines.
9.Represents a collection of 64 boolean (on/off) flags.
10.byte to be tested if it is Base64 alphabet
11.to Base64
12.One of the fastest implementation of the Base64 encoding. Jakarta and others are slower
13.array of byte to encode
14.Codes number up to radix 62
15.A Base64 Encoder/Decoder
16.A fast and memory efficient class to encode and decode to and from BASE64 in full accordance with RFC 2045
17.BASE64 encoder implementation
18.Base-64 Encoder - translates from base-64 text into binary
19.Base64 Character encoder as specified in RFC1113
20.Base64 Utils
21.Base64 encoder/decoder
22.Base64 from by Funambol, Inc.
23.Convert to hex from byte arrays and back
24.Converting hexadecimal strings
25.Encode and decode data in Base64 format as described in RFC 1521
26.Encode and decode integers, times, and internationalized strings to and from popular binary formats
27.Encoding of raw bytes to base64-encoded characters, and decoding of base64 characters to raw bytes
28.Performs Base64 encoding and/or decoding
29.Provides Base64 encoding and decoding as defined by RFC 2045
30.Provides Base64 encoding and decoding with URL and filename safe alphabet as defined by RFC 3548, section 4.
31.Provides utility methods to Base64 encode data
32.QP Decoder Stream
33.A class to decode Base64 streams and strings.
34.A class to encode Base64 streams and strings.
35.Encodes binary data to plain text as Base64
36.A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance with RFC 2045.
37.Decodes InputStreams which contain binary data in base64 form
38.Base 64 Converter
39.Base64 from org.cspoker.common.util
40.Base64 converted from code at http://iharder.sourceforge.net/base64/
41.Encodes and decodes to and from Base64 notation.
42.Simple Base64 string decoding function
43.Class to represent unsigned 64-bit numbers.
44.A Base64 encoder/decoder.
45.The Base64 utility class implements Base-64 and Base-85 encoding and decoding algorithms.
46.Provides Base64 encoding and decoding
47.Code to read and write Base64-encoded text.
48.Base32 encoding/decoding class.