KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > util > Base64


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.util;
23
24 import org.jboss.logging.Logger;
25
26 /**
27  * Encodes and decodes to and from Base64 notation.
28  *
29  * <p>
30  * Change Log:
31  * </p>
32  * <ul>
33  * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
34  * some convenience methods for reading and writing to and from files.</li>
35  * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
36  * with other encodings (like EBCDIC).</li>
37  * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
38  * encoded data was a single byte.</li>
39  * <li>v2.0 - I got rid of methods that used booleans to set options.
40  * Now everything is more consolidated and cleaner. The code now detects
41  * when data that's being decoded is gzip-compressed and will decompress it
42  * automatically. Generally things are cleaner. You'll probably have to
43  * change some method calls that you were making to support the new
44  * options format (<tt>int</tt>s that you "OR" together).</li>
45  * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
46  * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
47  * Added the ability to "suspend" encoding in the Output Stream so
48  * you can turn on and off the encoding if you need to embed base64
49  * data in an otherwise "normal" stream (like an XML file).</li>
50  * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
51  * This helps when using GZIP streams.
52  * Added the ability to GZip-compress objects before encoding them.</li>
53  * <li>v1.4 - Added helper methods to read/write files.</li>
54  * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
55  * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
56  * where last buffer being read, if not completely full, was not returned.</li>
57  * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
58  * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
59  * </ul>
60  *
61  * <p>
62  * I am placing this code in the Public Domain. Do with it as you will.
63  * This software comes with no guarantees or warranties but with
64  * plenty of well-wishing instead!
65  * Please visit <a HREF="http://iharder.net/base64">http://iharder.net/base64</a>
66  * periodically to check for updates or to contribute improvements.
67  * </p>
68  *
69  * @author Robert Harder
70  * @author rob@iharder.net
71  * @version 2.1
72  */

73 public class Base64
74 {
75    // provide logging
76
private static final Logger log = Logger.getLogger(Base64.class);
77
78    /* ******** P U B L I C F I E L D S ******** */
79
80    /** No options specified. Value is zero. */
81    public final static int NO_OPTIONS = 0;
82
83    /** Specify encoding. */
84    public final static int ENCODE = 1;
85
86    /** Specify decoding. */
87    public final static int DECODE = 0;
88
89    /** Specify that data should be gzip-compressed. */
90    public final static int GZIP = 2;
91
92    /** Don't break lines when encoding (violates strict Base64 specification) */
93    public final static int DONT_BREAK_LINES = 8;
94
95    /* ******** P R I V A T E F I E L D S ******** */
96
97    /** Maximum line length (76) of Base64 output. */
98    private final static int MAX_LINE_LENGTH = 76;
99
100    /** The equals sign (=) as a byte. */
101    private final static byte EQUALS_SIGN = (byte)'=';
102
103    /** The new line character (\n) as a byte. */
104    private final static byte NEW_LINE = (byte)'\n';
105
106    /** Preferred encoding. */
107    private final static String JavaDoc PREFERRED_ENCODING = "UTF-8";
108
109    /** The 64 valid Base64 values. */
110    private final static byte[] ALPHABET;
111    private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
112    { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
113          (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b',
114          (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p',
115          (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3',
116          (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' };
117
118    /** Determine which ALPHABET to use. */
119    static
120    {
121       byte[] __bytes;
122       try
123       {
124          __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes(PREFERRED_ENCODING);
125       } // end try
126
catch (java.io.UnsupportedEncodingException JavaDoc use)
127       {
128          __bytes = _NATIVE_ALPHABET; // Fall back to native encoding
129
} // end catch
130
ALPHABET = __bytes;
131    } // end static
132

133    /**
134     * Translates a Base64 value to either its 6-bit reconstruction value
135     * or a negative number indicating some other meaning.
136     **/

137    private final static byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
138
-5, -5, // Whitespace: Tab and Linefeed
139
-9, -9, // Decimal 11 - 12
140
-5, // Whitespace: Carriage Return
141
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
142
-9, -9, -9, -9, -9, // Decimal 27 - 31
143
-5, // Whitespace: Space
144
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
145
62, // Plus sign at decimal 43
146
-9, -9, -9, // Decimal 44 - 46
147
63, // Slash at decimal 47
148
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
149
-9, -9, -9, // Decimal 58 - 60
150
-1, // Equals sign at decimal 61
151
-9, -9, -9, // Decimal 62 - 64
152
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
153
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
154
-9, -9, -9, -9, -9, -9, // Decimal 91 - 96
155
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
156
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
157
-9, -9, -9, -9 // Decimal 123 - 126
158
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
159     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
160     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
161     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
162     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
163     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
164     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
165     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
166     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
167     -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */

168    };
169
170    // I think I end up not using the BAD_ENCODING indicator.
171
//private final static byte BAD_ENCODING = -9; // Indicates error in encoding
172
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
173
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
174

175    /** Defeats instantiation. */
176    private Base64()
177    {
178    }
179
180    /* ******** E N C O D I N G M E T H O D S ******** */
181
182    /**
183     * Encodes up to the first three bytes of array <var>threeBytes</var>
184     * and returns a four-byte array in Base64 notation.
185     * The actual number of significant bytes in your array is
186     * given by <var>numSigBytes</var>.
187     * The array <var>threeBytes</var> needs only be as big as
188     * <var>numSigBytes</var>.
189     * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
190     *
191     * @param b4 A reusable byte array to reduce array instantiation
192     * @param threeBytes the array to convert
193     * @param numSigBytes the number of significant bytes in your array
194     * @return four byte array in Base64 notation.
195     * @since 1.5.1
196     */

197    private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes)
198    {
199       encode3to4(threeBytes, 0, numSigBytes, b4, 0);
200       return b4;
201    } // end encode3to4
202

203    /**
204     * Encodes up to three bytes of the array <var>source</var>
205     * and writes the resulting four Base64 bytes to <var>destination</var>.
206     * The source and destination arrays can be manipulated
207     * anywhere along their length by specifying
208     * <var>srcOffset</var> and <var>destOffset</var>.
209     * This method does not check to make sure your arrays
210     * are large enough to accomodate <var>srcOffset</var> + 3 for
211     * the <var>source</var> array or <var>destOffset</var> + 4 for
212     * the <var>destination</var> array.
213     * The actual number of significant bytes in your array is
214     * given by <var>numSigBytes</var>.
215     *
216     * @param source the array to convert
217     * @param srcOffset the index where conversion begins
218     * @param numSigBytes the number of significant bytes in your array
219     * @param destination the array to hold the conversion
220     * @param destOffset the index where output will be put
221     * @return the <var>destination</var> array
222     * @since 1.3
223     */

224    private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset)
225    {
226       // 1 2 3
227
// 01234567890123456789012345678901 Bit position
228
// --------000000001111111122222222 Array position from threeBytes
229
// --------| || || || | Six bit groups to index ALPHABET
230
// >>18 >>12 >> 6 >> 0 Right shift necessary
231
// 0x3f 0x3f 0x3f Additional AND
232

233       // Create buffer with zero-padding if there are only one or two
234
// significant bytes passed in the array.
235
// We have to shift left 24 in order to flush out the 1's that appear
236
// when Java treats a value as negative that is cast from a byte to an int.
237
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
238             | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
239
240       switch (numSigBytes)
241       {
242          case 3:
243             destination[destOffset] = ALPHABET[(inBuff >>> 18)];
244             destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
245             destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
246             destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
247             return destination;
248
249          case 2:
250             destination[destOffset] = ALPHABET[(inBuff >>> 18)];
251             destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
252             destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
253             destination[destOffset + 3] = EQUALS_SIGN;
254             return destination;
255
256          case 1:
257             destination[destOffset] = ALPHABET[(inBuff >>> 18)];
258             destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
259             destination[destOffset + 2] = EQUALS_SIGN;
260             destination[destOffset + 3] = EQUALS_SIGN;
261             return destination;
262
263          default:
264             return destination;
265       } // end switch
266
} // end encode3to4
267

268    /**
269     * Serializes an object and returns the Base64-encoded
270     * version of that serialized object. If the object
271     * cannot be serialized or there is another error,
272     * the method will return <tt>null</tt>.
273     * The object is not GZip-compressed before being encoded.
274     *
275     * @param serializableObject The object to encode
276     * @return The Base64-encoded object
277     * @since 1.4
278     */

279    public static String JavaDoc encodeObject(java.io.Serializable JavaDoc serializableObject)
280    {
281       return encodeObject(serializableObject, NO_OPTIONS);
282    } // end encodeObject
283

284    /**
285     * Serializes an object and returns the Base64-encoded
286     * version of that serialized object. If the object
287     * cannot be serialized or there is another error,
288     * the method will return <tt>null</tt>.
289     * <p>
290     * Valid options:<pre>
291     * GZIP: gzip-compresses object before encoding it.
292     * DONT_BREAK_LINES: don't break lines at 76 characters
293     * <i>Note: Technically, this makes your encoding non-compliant.</i>
294     * </pre>
295     * <p>
296     * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
297     * <p>
298     * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
299     *
300     * @param serializableObject The object to encode
301     * @param options Specified options
302     * @return The Base64-encoded object
303     * @see Base64#GZIP
304     * @see Base64#DONT_BREAK_LINES
305     * @since 2.0
306     */

307    public static String JavaDoc encodeObject(java.io.Serializable JavaDoc serializableObject, int options)
308    {
309       // Streams
310
java.io.ByteArrayOutputStream JavaDoc baos = null;
311       java.io.OutputStream JavaDoc b64os = null;
312       java.io.ObjectOutputStream JavaDoc oos = null;
313       java.util.zip.GZIPOutputStream JavaDoc gzos = null;
314
315       // Isolate options
316
int gzip = (options & GZIP);
317       int dontBreakLines = (options & DONT_BREAK_LINES);
318
319       try
320       {
321          // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
322
baos = new java.io.ByteArrayOutputStream JavaDoc();
323          b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
324
325          // GZip?
326
if (gzip == GZIP)
327          {
328             gzos = new java.util.zip.GZIPOutputStream JavaDoc(b64os);
329             oos = new java.io.ObjectOutputStream JavaDoc(gzos);
330          } // end if: gzip
331
else oos = new java.io.ObjectOutputStream JavaDoc(b64os);
332
333          oos.writeObject(serializableObject);
334       } // end try
335
catch (java.io.IOException JavaDoc e)
336       {
337          e.printStackTrace();
338          return null;
339       } // end catch
340
finally
341       {
342          try
343          {
344             oos.close();
345          }
346          catch (Exception JavaDoc e)
347          {
348          }
349          try
350          {
351             gzos.close();
352          }
353          catch (Exception JavaDoc e)
354          {
355          }
356          try
357          {
358             b64os.close();
359          }
360          catch (Exception JavaDoc e)
361          {
362          }
363          try
364          {
365             baos.close();
366          }
367          catch (Exception JavaDoc e)
368          {
369          }
370       } // end finally
371

372       // Return value according to relevant encoding.
373
try
374       {
375          return new String JavaDoc(baos.toByteArray(), PREFERRED_ENCODING);
376       } // end try
377
catch (java.io.UnsupportedEncodingException JavaDoc uue)
378       {
379          return new String JavaDoc(baos.toByteArray());
380       } // end catch
381

382    } // end encode
383

384    /**
385     * Encodes a byte array into Base64 notation.
386     * Does not GZip-compress data.
387     *
388     * @param source The data to convert
389     * @since 1.4
390     */

391    public static String JavaDoc encodeBytes(byte[] source)
392    {
393       return encodeBytes(source, 0, source.length, NO_OPTIONS);
394    } // end encodeBytes
395

396    /**
397     * Encodes a byte array into Base64 notation.
398     * <p>
399     * Valid options:<pre>
400     * GZIP: gzip-compresses object before encoding it.
401     * DONT_BREAK_LINES: don't break lines at 76 characters
402     * <i>Note: Technically, this makes your encoding non-compliant.</i>
403     * </pre>
404     * <p>
405     * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
406     * <p>
407     * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
408     *
409     *
410     * @param source The data to convert
411     * @param options Specified options
412     * @see Base64#GZIP
413     * @see Base64#DONT_BREAK_LINES
414     * @since 2.0
415     */

416    public static String JavaDoc encodeBytes(byte[] source, int options)
417    {
418       return encodeBytes(source, 0, source.length, options);
419    } // end encodeBytes
420

421    /**
422     * Encodes a byte array into Base64 notation.
423     * Does not GZip-compress data.
424     *
425     * @param source The data to convert
426     * @param off Offset in array where conversion should begin
427     * @param len Length of data to convert
428     * @since 1.4
429     */

430    public static String JavaDoc encodeBytes(byte[] source, int off, int len)
431    {
432       return encodeBytes(source, off, len, NO_OPTIONS);
433    } // end encodeBytes
434

435    /**
436     * Encodes a byte array into Base64 notation.
437     * <p>
438     * Valid options:<pre>
439     * GZIP: gzip-compresses object before encoding it.
440     * DONT_BREAK_LINES: don't break lines at 76 characters
441     * <i>Note: Technically, this makes your encoding non-compliant.</i>
442     * </pre>
443     * <p>
444     * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
445     * <p>
446     * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
447     *
448     *
449     * @param source The data to convert
450     * @param off Offset in array where conversion should begin
451     * @param len Length of data to convert
452     * @param options Specified options
453     * @see Base64#GZIP
454     * @see Base64#DONT_BREAK_LINES
455     * @since 2.0
456     */

457    public static String JavaDoc encodeBytes(byte[] source, int off, int len, int options)
458    {
459       // Isolate options
460
int dontBreakLines = (options & DONT_BREAK_LINES);
461       int gzip = (options & GZIP);
462
463       // Compress?
464
if (gzip == GZIP)
465       {
466          java.io.ByteArrayOutputStream JavaDoc baos = null;
467          java.util.zip.GZIPOutputStream JavaDoc gzos = null;
468          Base64.OutputStream b64os = null;
469
470          try
471          {
472             // GZip -> Base64 -> ByteArray
473
baos = new java.io.ByteArrayOutputStream JavaDoc();
474             b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
475             gzos = new java.util.zip.GZIPOutputStream JavaDoc(b64os);
476
477             gzos.write(source, off, len);
478             gzos.close();
479          } // end try
480
catch (java.io.IOException JavaDoc e)
481          {
482             e.printStackTrace();
483             return null;
484          } // end catch
485
finally
486          {
487             try
488             {
489                gzos.close();
490             }
491             catch (Exception JavaDoc e)
492             {
493             }
494             try
495             {
496                b64os.close();
497             }
498             catch (Exception JavaDoc e)
499             {
500             }
501             try
502             {
503                baos.close();
504             }
505             catch (Exception JavaDoc e)
506             {
507             }
508          } // end finally
509

510          // Return value according to relevant encoding.
511
try
512          {
513             return new String JavaDoc(baos.toByteArray(), PREFERRED_ENCODING);
514          } // end try
515
catch (java.io.UnsupportedEncodingException JavaDoc uue)
516          {
517             return new String JavaDoc(baos.toByteArray());
518          } // end catch
519
} // end if: compress
520

521       // Else, don't compress. Better not to use streams at all then.
522
else
523       {
524          // Convert option to boolean in way that code likes it.
525
boolean breakLines = dontBreakLines == 0;
526
527          int len43 = len * 4 / 3;
528          byte[] outBuff = new byte[(len43) // Main 4:3
529
+ ((len % 3) > 0 ? 4 : 0) // Account for padding
530
+ (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines
531
int d = 0;
532          int e = 0;
533          int len2 = len - 2;
534          int lineLength = 0;
535          for (; d < len2; d += 3, e += 4)
536          {
537             encode3to4(source, d + off, 3, outBuff, e);
538
539             lineLength += 4;
540             if (breakLines && lineLength == MAX_LINE_LENGTH)
541             {
542                outBuff[e + 4] = NEW_LINE;
543                e++;
544                lineLength = 0;
545             } // end if: end of line
546
} // en dfor: each piece of array
547

548          if (d < len)
549          {
550             encode3to4(source, d + off, len - d, outBuff, e);
551             e += 4;
552          } // end if: some padding needed
553

554          // Return value according to relevant encoding.
555
try
556          {
557             return new String JavaDoc(outBuff, 0, e, PREFERRED_ENCODING);
558          } // end try
559
catch (java.io.UnsupportedEncodingException JavaDoc uue)
560          {
561             return new String JavaDoc(outBuff, 0, e);
562          } // end catch
563

564       } // end else: don't compress
565

566    } // end encodeBytes
567

568    /* ******** D E C O D I N G M E T H O D S ******** */
569
570    /**
571     * Decodes four bytes from array <var>source</var>
572     * and writes the resulting bytes (up to three of them)
573     * to <var>destination</var>.
574     * The source and destination arrays can be manipulated
575     * anywhere along their length by specifying
576     * <var>srcOffset</var> and <var>destOffset</var>.
577     * This method does not check to make sure your arrays
578     * are large enough to accomodate <var>srcOffset</var> + 4 for
579     * the <var>source</var> array or <var>destOffset</var> + 3 for
580     * the <var>destination</var> array.
581     * This method returns the actual number of bytes that
582     * were converted from the Base64 encoding.
583     *
584     *
585     * @param source the array to convert
586     * @param srcOffset the index where conversion begins
587     * @param destination the array to hold the conversion
588     * @param destOffset the index where output will be put
589     * @return the number of decoded bytes converted
590     * @since 1.3
591     */

592    private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset)
593    {
594       // Example: Dk==
595
if (source[srcOffset + 2] == EQUALS_SIGN)
596       {
597          // Two ways to do the same thing. Don't know which way I like best.
598
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
599
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
600
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
601
602          destination[destOffset] = (byte)(outBuff >>> 16);
603          return 1;
604       }
605
606       // Example: DkL=
607
else if (source[srcOffset + 3] == EQUALS_SIGN)
608       {
609          // Two ways to do the same thing. Don't know which way I like best.
610
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
611
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
612
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
613
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
614                | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
615
616          destination[destOffset] = (byte)(outBuff >>> 16);
617          destination[destOffset + 1] = (byte)(outBuff >>> 8);
618          return 2;
619       }
620
621       // Example: DkLE
622
else
623       {
624          try
625          {
626             // Two ways to do the same thing. Don't know which way I like best.
627
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
628
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
629
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
630
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
631
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
632                   | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF));
633
634             destination[destOffset] = (byte)(outBuff >> 16);
635             destination[destOffset + 1] = (byte)(outBuff >> 8);
636             destination[destOffset + 2] = (byte)(outBuff);
637
638             return 3;
639          }
640          catch (Exception JavaDoc e)
641          {
642             log.error("" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]]));
643             log.error("" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]]));
644             log.error("" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]]));
645             log.error("" + source[srcOffset + 3] + ": " + (DECODABET[source[srcOffset + 3]]));
646             return -1;
647          } //end catch
648
}
649    } // end decodeToBytes
650

651    /**
652     * Very low-level access to decoding ASCII characters in
653     * the form of a byte array. Does not support automatically
654     * gunzipping or any other "fancy" features.
655     *
656     * @param source The Base64 encoded data
657     * @param off The offset of where to begin decoding
658     * @param len The length of characters to decode
659     * @return decoded data
660     * @since 1.3
661     */

662    public static byte[] decode(byte[] source, int off, int len)
663    {
664       int len34 = len * 3 / 4;
665       byte[] outBuff = new byte[len34]; // Upper limit on size of output
666
int outBuffPosn = 0;
667
668       byte[] b4 = new byte[4];
669       int b4Posn = 0;
670       int i = 0;
671       byte sbiCrop = 0;
672       byte sbiDecode = 0;
673       for (i = off; i < off + len; i++)
674       {
675          sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
676
sbiDecode = DECODABET[sbiCrop];
677
678          if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better
679
{
680             if (sbiDecode >= EQUALS_SIGN_ENC)
681             {
682                b4[b4Posn++] = sbiCrop;
683                if (b4Posn > 3)
684                {
685                   outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
686                   b4Posn = 0;
687
688                   // If that was the equals sign, break out of 'for' loop
689
if (sbiCrop == EQUALS_SIGN)
690                      break;
691                } // end if: quartet built
692

693             } // end if: equals sign or better
694

695          } // end if: white space, equals sign or better
696
else
697          {
698             throw new IllegalStateException JavaDoc("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)");
699          } // end else:
700
} // each input character
701

702       byte[] out = new byte[outBuffPosn];
703       System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
704       return out;
705    } // end decode
706

707    /**
708     * Decodes data from Base64 notation, automatically
709     * detecting gzip-compressed data and decompressing it.
710     *
711     * @param s the string to decode
712     * @return the decoded data
713     * @since 1.4
714     */

715    public static byte[] decode(String JavaDoc s)
716    {
717       byte[] bytes;
718       try
719       {
720          bytes = s.getBytes(PREFERRED_ENCODING);
721       } // end try
722
catch (java.io.UnsupportedEncodingException JavaDoc uee)
723       {
724          bytes = s.getBytes();
725       } // end catch
726
//</change>
727

728       // Decode
729
bytes = decode(bytes, 0, bytes.length);
730
731       // Check to see if it's gzip-compressed
732
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
733
if (bytes != null && bytes.length >= 4)
734       {
735
736          int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
737          if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head)
738          {
739             java.io.ByteArrayInputStream JavaDoc bais = null;
740             java.util.zip.GZIPInputStream JavaDoc gzis = null;
741             java.io.ByteArrayOutputStream JavaDoc baos = null;
742             byte[] buffer = new byte[2048];
743             int length = 0;
744
745             try
746             {
747                baos = new java.io.ByteArrayOutputStream JavaDoc();
748                bais = new java.io.ByteArrayInputStream JavaDoc(bytes);
749                gzis = new java.util.zip.GZIPInputStream JavaDoc(bais);
750
751                while ((length = gzis.read(buffer)) >= 0)
752                {
753                   baos.write(buffer, 0, length);
754                } // end while: reading input
755

756                // No error? Get new bytes.
757
bytes = baos.toByteArray();
758
759             } // end try
760
catch (java.io.IOException JavaDoc e)
761             {
762                // Just return originally-decoded bytes
763
} // end catch
764
finally
765             {
766                try
767                {
768                   baos.close();
769                }
770                catch (Exception JavaDoc e)
771                {
772                }
773                try
774                {
775                   gzis.close();
776                }
777                catch (Exception JavaDoc e)
778                {
779                }
780                try
781                {
782                   bais.close();
783                }
784                catch (Exception JavaDoc e)
785                {
786                }
787             } // end finally
788

789          } // end if: gzipped
790
} // end if: bytes.length >= 2
791

792       return bytes;
793    } // end decode
794

795    /**
796     * Attempts to decode Base64 data and deserialize a Java
797     * Object within. Returns <tt>null</tt> if there was an error.
798     *
799     * @param encodedObject The Base64 data to decode
800     * @return The decoded and deserialized object
801     * @since 1.5
802     */

803    public static Object JavaDoc decodeToObject(String JavaDoc encodedObject)
804    {
805       // Decode and gunzip if necessary
806
byte[] objBytes = decode(encodedObject);
807
808       java.io.ByteArrayInputStream JavaDoc bais = null;
809       java.io.ObjectInputStream JavaDoc ois = null;
810       Object JavaDoc obj = null;
811
812       try
813       {
814          bais = new java.io.ByteArrayInputStream JavaDoc(objBytes);
815          ois = new java.io.ObjectInputStream JavaDoc(bais);
816
817          obj = ois.readObject();
818       } // end try
819
catch (java.io.IOException JavaDoc e)
820       {
821          e.printStackTrace();
822          obj = null;
823       } // end catch
824
catch (java.lang.ClassNotFoundException JavaDoc e)
825       {
826          e.printStackTrace();
827          obj = null;
828       } // end catch
829
finally
830       {
831          try
832          {
833             bais.close();
834          }
835          catch (Exception JavaDoc e)
836          {
837          }
838          try
839          {
840             ois.close();
841          }
842          catch (Exception JavaDoc e)
843          {
844          }
845       } // end finally
846

847       return obj;
848    } // end decodeObject
849

850    /**
851     * Convenience method for encoding data to a file.
852     *
853     * @param dataToEncode byte array of data to encode in base64 form
854     * @param filename Filename for saving encoded data
855     * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
856     *
857     * @since 2.1
858     */

859    public static boolean encodeToFile(byte[] dataToEncode, String JavaDoc filename)
860    {
861       boolean success = false;
862       Base64.OutputStream bos = null;
863       try
864       {
865          bos = new Base64.OutputStream(new java.io.FileOutputStream JavaDoc(filename), Base64.ENCODE);
866          bos.write(dataToEncode);
867          success = true;
868       } // end try
869
catch (java.io.IOException JavaDoc e)
870       {
871
872          success = false;
873       } // end catch: IOException
874
finally
875       {
876          try
877          {
878             bos.close();
879          }
880          catch (Exception JavaDoc e)
881          {
882          }
883       } // end finally
884

885       return success;
886    } // end encodeToFile
887

888    /**
889     * Convenience method for decoding data to a file.
890     *
891     * @param dataToDecode Base64-encoded data as a string
892     * @param filename Filename for saving decoded data
893     * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
894     *
895     * @since 2.1
896     */

897    public static boolean decodeToFile(String JavaDoc dataToDecode, String JavaDoc filename)
898    {
899       boolean success = false;
900       Base64.OutputStream bos = null;
901       try
902       {
903          bos = new Base64.OutputStream(new java.io.FileOutputStream JavaDoc(filename), Base64.DECODE);
904          bos.write(dataToDecode.getBytes(PREFERRED_ENCODING));
905          success = true;
906       } // end try
907
catch (java.io.IOException JavaDoc e)
908       {
909          success = false;
910       } // end catch: IOException
911
finally
912       {
913          try
914          {
915             bos.close();
916          }
917          catch (Exception JavaDoc e)
918          {
919          }
920       } // end finally
921

922       return success;
923    } // end decodeToFile
924

925    /**
926     * Convenience method for reading a base64-encoded
927     * file and decoding it.
928     *
929     * @param filename Filename for reading encoded data
930     * @return decoded byte array or null if unsuccessful
931     *
932     * @since 2.1
933     */

934    public static byte[] decodeFromFile(String JavaDoc filename)
935    {
936       byte[] decodedData = null;
937       Base64.InputStream bis = null;
938       try
939       {
940          // Set up some useful variables
941
java.io.File JavaDoc file = new java.io.File JavaDoc(filename);
942          byte[] buffer = null;
943          int length = 0;
944          int numBytes = 0;
945
946          // Check for size of file
947
if (file.length() > Integer.MAX_VALUE)
948          {
949             throw new IllegalStateException JavaDoc("File is too big for this convenience method (" + file.length() + " bytes).");
950          } // end if: file too big for int index
951
buffer = new byte[(int)file.length()];
952
953          // Open a stream
954
bis = new Base64.InputStream(new java.io.BufferedInputStream JavaDoc(new java.io.FileInputStream JavaDoc(file)), Base64.DECODE);
955
956          // Read until done
957
while ((numBytes = bis.read(buffer, length, 4096)) >= 0)
958             length += numBytes;
959
960          // Save in a variable to return
961
decodedData = new byte[length];
962          System.arraycopy(buffer, 0, decodedData, 0, length);
963
964       } // end try
965
catch (java.io.IOException JavaDoc e)
966       {
967          throw new IllegalStateException JavaDoc("Error decoding from file " + filename);
968       } // end catch: IOException
969
finally
970       {
971          try
972          {
973             bis.close();
974          }
975          catch (Exception JavaDoc e)
976          {
977          }
978       } // end finally
979

980       return decodedData;
981    } // end decodeFromFile
982

983    /**
984     * Convenience method for reading a binary file
985     * and base64-encoding it.
986     *
987     * @param filename Filename for reading binary data
988     * @return base64-encoded string or null if unsuccessful
989     *
990     * @since 2.1
991     */

992    public static String JavaDoc encodeFromFile(String JavaDoc filename)
993    {
994       String JavaDoc encodedData = null;
995       Base64.InputStream bis = null;
996       try
997       {
998          // Set up some useful variables
999
java.io.File JavaDoc file = new java.io.File JavaDoc(filename);
1000         byte[] buffer = new byte[(int)(file.length() * 1.4)];
1001         int length = 0;
1002         int numBytes = 0;
1003
1004         // Open a stream
1005
bis = new Base64.InputStream(new java.io.BufferedInputStream JavaDoc(new java.io.FileInputStream JavaDoc(file)), Base64.ENCODE);
1006
1007         // Read until done
1008
while ((numBytes = bis.read(buffer, length, 4096)) >= 0)
1009            length += numBytes;
1010
1011         // Save in a variable to return
1012
encodedData = new String JavaDoc(buffer, 0, length, Base64.PREFERRED_ENCODING);
1013
1014      } // end try
1015
catch (java.io.IOException JavaDoc e)
1016      {
1017         throw new IllegalStateException JavaDoc("Error encoding from file " + filename);
1018      } // end catch: IOException
1019
finally
1020      {
1021         try
1022         {
1023            bis.close();
1024         }
1025         catch (Exception JavaDoc e)
1026         {
1027         }
1028      } // end finally
1029

1030      return encodedData;
1031   } // end encodeFromFile
1032

1033   /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
1034
1035   /**
1036    * A {@link Base64.InputStream} will read data from another
1037    * <tt>java.io.InputStream</tt>, given in the constructor,
1038    * and encode/decode to/from Base64 notation on the fly.
1039    *
1040    * @see Base64
1041    * @since 1.3
1042    */

1043   public static class InputStream extends java.io.FilterInputStream JavaDoc
1044   {
1045      private boolean encode; // Encoding or decoding
1046
private int position; // Current position in the buffer
1047
private byte[] buffer; // Small buffer holding converted data
1048
private int bufferLength; // Length of buffer (3 or 4)
1049
private int numSigBytes; // Number of meaningful bytes in the buffer
1050
private int lineLength;
1051      private boolean breakLines; // Break lines at less than 80 characters
1052

1053      /**
1054       * Constructs a {@link Base64.InputStream} in DECODE mode.
1055       *
1056       * @param in the <tt>java.io.InputStream</tt> from which to read data.
1057       * @since 1.3
1058       */

1059      public InputStream(java.io.InputStream JavaDoc in)
1060      {
1061         this(in, DECODE);
1062      } // end constructor
1063

1064      /**
1065       * Constructs a {@link Base64.InputStream} in
1066       * either ENCODE or DECODE mode.
1067       * <p>
1068       * Valid options:<pre>
1069       * ENCODE or DECODE: Encode or Decode as data is read.
1070       * DONT_BREAK_LINES: don't break lines at 76 characters
1071       * (only meaningful when encoding)
1072       * <i>Note: Technically, this makes your encoding non-compliant.</i>
1073       * </pre>
1074       * <p>
1075       * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1076       *
1077       *
1078       * @param in the <tt>java.io.InputStream</tt> from which to read data.
1079       * @param options Specified options
1080       * @see Base64#ENCODE
1081       * @see Base64#DECODE
1082       * @see Base64#DONT_BREAK_LINES
1083       * @since 2.0
1084       */

1085      public InputStream(java.io.InputStream JavaDoc in, int options)
1086      {
1087         super(in);
1088         this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1089         this.encode = (options & ENCODE) == ENCODE;
1090         this.bufferLength = encode ? 4 : 3;
1091         this.buffer = new byte[bufferLength];
1092         this.position = -1;
1093         this.lineLength = 0;
1094      } // end constructor
1095

1096      /**
1097       * Reads enough of the input stream to convert
1098       * to/from Base64 and returns the next byte.
1099       *
1100       * @return next byte
1101       * @since 1.3
1102       */

1103      public int read() throws java.io.IOException JavaDoc
1104      {
1105         // Do we need to get data?
1106
if (position < 0)
1107         {
1108            if (encode)
1109            {
1110               byte[] b3 = new byte[3];
1111               int numBinaryBytes = 0;
1112               for (int i = 0; i < 3; i++)
1113               {
1114                  try
1115                  {
1116                     int b = in.read();
1117
1118                     // If end of stream, b is -1.
1119
if (b >= 0)
1120                     {
1121                        b3[i] = (byte)b;
1122                        numBinaryBytes++;
1123                     } // end if: not end of stream
1124

1125                  } // end try: read
1126
catch (java.io.IOException JavaDoc e)
1127                  {
1128                     // Only a problem if we got no data at all.
1129
if (i == 0)
1130                        throw e;
1131
1132                  } // end catch
1133
} // end for: each needed input byte
1134

1135               if (numBinaryBytes > 0)
1136               {
1137                  encode3to4(b3, 0, numBinaryBytes, buffer, 0);
1138                  position = 0;
1139                  numSigBytes = 4;
1140               } // end if: got data
1141
else
1142               {
1143                  return -1;
1144               } // end else
1145
} // end if: encoding
1146

1147            // Else decoding
1148
else
1149            {
1150               byte[] b4 = new byte[4];
1151               int i = 0;
1152               for (i = 0; i < 4; i++)
1153               {
1154                  // Read four "meaningful" bytes:
1155
int b = 0;
1156                  do
1157                  {
1158                     b = in.read();
1159                  }
1160                  while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC);
1161
1162                  if (b < 0)
1163                     break; // Reads a -1 if end of stream
1164

1165                  b4[i] = (byte)b;
1166               } // end for: each needed input byte
1167

1168               if (i == 4)
1169               {
1170                  numSigBytes = decode4to3(b4, 0, buffer, 0);
1171                  position = 0;
1172               } // end if: got four characters
1173
else if (i == 0)
1174               {
1175                  return -1;
1176               } // end else if: also padded correctly
1177
else
1178               {
1179                  // Must have broken out from above.
1180
throw new java.io.IOException JavaDoc("Improperly padded Base64 input.");
1181               } // end
1182

1183            } // end else: decode
1184
} // end else: get data
1185

1186         // Got data?
1187
if (position >= 0)
1188         {
1189            // End of relevant data?
1190
if (/*!encode &&*/position >= numSigBytes)
1191               return -1;
1192
1193            if (encode && breakLines && lineLength >= MAX_LINE_LENGTH)
1194            {
1195               lineLength = 0;
1196               return '\n';
1197            } // end if
1198
else
1199            {
1200               lineLength++; // This isn't important when decoding
1201
// but throwing an extra "if" seems
1202
// just as wasteful.
1203

1204               int b = buffer[position++];
1205
1206               if (position >= bufferLength)
1207                  position = -1;
1208
1209               return b & 0xFF; // This is how you "cast" a byte that's
1210
// intended to be unsigned.
1211
} // end else
1212
} // end if: position >= 0
1213

1214         // Else error
1215
else
1216         {
1217            // When JDK1.4 is more accepted, use an assertion here.
1218
throw new java.io.IOException JavaDoc("Error in Base64 code reading stream.");
1219         } // end else
1220
} // end read
1221

1222      /**
1223       * Calls {@link #read()} repeatedly until the end of stream
1224       * is reached or <var>len</var> bytes are read.
1225       * Returns number of bytes read into array or -1 if
1226       * end of stream is encountered.
1227       *
1228       * @param dest array to hold values
1229       * @param off offset for array
1230       * @param len max number of bytes to read into array
1231       * @return bytes read into array or -1 if end of stream is encountered.
1232       * @since 1.3
1233       */

1234      public int read(byte[] dest, int off, int len) throws java.io.IOException JavaDoc
1235      {
1236         int i;
1237         int b;
1238         for (i = 0; i < len; i++)
1239         {
1240            b = read();
1241
1242            //if( b < 0 && i == 0 )
1243
// return -1;
1244

1245            if (b >= 0)
1246               dest[off + i] = (byte)b;
1247            else if (i == 0)
1248               return -1;
1249            else break; // Out of 'for' loop
1250
} // end for: each byte read
1251
return i;
1252      } // end read
1253

1254   } // end inner class InputStream
1255

1256   /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1257
1258   /**
1259    * A {@link Base64.OutputStream} will write data to another
1260    * <tt>java.io.OutputStream</tt>, given in the constructor,
1261    * and encode/decode to/from Base64 notation on the fly.
1262    *
1263    * @see Base64
1264    * @since 1.3
1265    */

1266   public static class OutputStream extends java.io.FilterOutputStream JavaDoc
1267   {
1268      private boolean encode;
1269      private int position;
1270      private byte[] buffer;
1271      private int bufferLength;
1272      private int lineLength;
1273      private boolean breakLines;
1274      private byte[] b4; // Scratch used in a few places
1275
private boolean suspendEncoding;
1276
1277      /**
1278       * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1279       *
1280       * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1281       * @since 1.3
1282       */

1283      public OutputStream(java.io.OutputStream JavaDoc out)
1284      {
1285         this(out, ENCODE);
1286      } // end constructor
1287

1288      /**
1289       * Constructs a {@link Base64.OutputStream} in
1290       * either ENCODE or DECODE mode.
1291       * <p>
1292       * Valid options:<pre>
1293       * ENCODE or DECODE: Encode or Decode as data is read.
1294       * DONT_BREAK_LINES: don't break lines at 76 characters
1295       * (only meaningful when encoding)
1296       * <i>Note: Technically, this makes your encoding non-compliant.</i>
1297       * </pre>
1298       * <p>
1299       * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1300       *
1301       * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1302       * @param options Specified options.
1303       * @see Base64#ENCODE
1304       * @see Base64#DECODE
1305       * @see Base64#DONT_BREAK_LINES
1306       * @since 1.3
1307       */

1308      public OutputStream(java.io.OutputStream JavaDoc out, int options)
1309      {
1310         super(out);
1311         this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1312         this.encode = (options & ENCODE) == ENCODE;
1313         this.bufferLength = encode ? 3 : 4;
1314         this.buffer = new byte[bufferLength];
1315         this.position = 0;
1316         this.lineLength = 0;
1317         this.suspendEncoding = false;
1318         this.b4 = new byte[4];
1319      } // end constructor
1320

1321      /**
1322       * Writes the byte to the output stream after
1323       * converting to/from Base64 notation.
1324       * When encoding, bytes are buffered three
1325       * at a time before the output stream actually
1326       * gets a write() call.
1327       * When decoding, bytes are buffered four
1328       * at a time.
1329       *
1330       * @param theByte the byte to write
1331       * @since 1.3
1332       */

1333      public void write(int theByte) throws java.io.IOException JavaDoc
1334      {
1335         // Encoding suspended?
1336
if (suspendEncoding)
1337         {
1338            super.out.write(theByte);
1339            return;
1340         } // end if: supsended
1341

1342         // Encode?
1343
if (encode)
1344         {
1345            buffer[position++] = (byte)theByte;
1346            if (position >= bufferLength) // Enough to encode.
1347
{
1348               out.write(encode3to4(b4, buffer, bufferLength));
1349
1350               lineLength += 4;
1351               if (breakLines && lineLength >= MAX_LINE_LENGTH)
1352               {
1353                  out.write(NEW_LINE);
1354                  lineLength = 0;
1355               } // end if: end of line
1356

1357               position = 0;
1358            } // end if: enough to output
1359
} // end if: encoding
1360

1361         // Else, Decoding
1362
else
1363         {
1364            // Meaningful Base64 character?
1365
if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC)
1366            {
1367               buffer[position++] = (byte)theByte;
1368               if (position >= bufferLength) // Enough to output.
1369
{
1370                  int len = Base64.decode4to3(buffer, 0, b4, 0);
1371                  out.write(b4, 0, len);
1372                  //out.write( Base64.decode4to3( buffer ) );
1373
position = 0;
1374               } // end if: enough to output
1375
} // end if: meaningful base64 character
1376
else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC)
1377            {
1378               throw new java.io.IOException JavaDoc("Invalid character in Base64 data.");
1379            } // end else: not white space either
1380
} // end else: decoding
1381
} // end write
1382

1383      /**
1384       * Calls {@link #write(int)} repeatedly until <var>len</var>
1385       * bytes are written.
1386       *
1387       * @param theBytes array from which to read bytes
1388       * @param off offset for array
1389       * @param len max number of bytes to read into array
1390       * @since 1.3
1391       */

1392      public void write(byte[] theBytes, int off, int len) throws java.io.IOException JavaDoc
1393      {
1394         // Encoding suspended?
1395
if (suspendEncoding)
1396         {
1397            super.out.write(theBytes, off, len);
1398            return;
1399         } // end if: supsended
1400

1401         for (int i = 0; i < len; i++)
1402         {
1403            write(theBytes[off + i]);
1404         } // end for: each byte written
1405

1406      } // end write
1407

1408      /**
1409       * Method added by PHIL. [Thanks, PHIL. -Rob]
1410       * This pads the buffer without closing the stream.
1411       */

1412      public void flushBase64() throws java.io.IOException JavaDoc
1413      {
1414         if (position > 0)
1415         {
1416            if (encode)
1417            {
1418               out.write(encode3to4(b4, buffer, position));
1419               position = 0;
1420            } // end if: encoding
1421
else
1422            {
1423               throw new java.io.IOException JavaDoc("Base64 input not properly padded.");
1424            } // end else: decoding
1425
} // end if: buffer partially full
1426

1427      } // end flush
1428

1429      /**
1430       * Flushes and closes (I think, in the superclass) the stream.
1431       *
1432       * @since 1.3
1433       */

1434      public void close() throws java.io.IOException JavaDoc
1435      {
1436         // 1. Ensure that pending characters are written
1437
flushBase64();
1438
1439         // 2. Actually close the stream
1440
// Base class both flushes and closes.
1441
super.close();
1442
1443         buffer = null;
1444         out = null;
1445      } // end close
1446

1447      /**
1448       * Suspends encoding of the stream.
1449       * May be helpful if you need to embed a piece of
1450       * base640-encoded data in a stream.
1451       *
1452       * @since 1.5.1
1453       */

1454      public void suspendEncoding() throws java.io.IOException JavaDoc
1455      {
1456         flushBase64();
1457         this.suspendEncoding = true;
1458      } // end suspendEncoding
1459

1460      /**
1461       * Resumes encoding of the stream.
1462       * May be helpful if you need to embed a piece of
1463       * base640-encoded data in a stream.
1464       *
1465       * @since 1.5.1
1466       */

1467      public void resumeEncoding()
1468      {
1469         this.suspendEncoding = false;
1470      } // end resumeEncoding
1471

1472   } // end inner class OutputStream
1473

1474} // end class Base64
1475
Popular Tags