datasource/Cached_Content_Loader: added caching content loader
[metux-java.git] / util / Base64.java
blobaf3b5805c74f44924c48f14646534ab021e3b7c9
2 package org.de.metux.util;
4 /**
5 * Encodes and decodes to and from Base64 notation.
7 * <p>
8 * Change Log:
9 * </p>
10 * <ul>
11 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
12 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
13 * where last buffer being read, if not completely full, was not returned.</li>
14 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
15 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
16 * </ul>
18 * <p>
19 * I am placing this code in the Public Domain. Do with it as you will.
20 * This software comes with no guarantees or warranties but with
21 * plenty of well-wishing instead!
22 * Please visit <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a>
23 * periodically to check for updates or to contribute improvements.
24 * </p>
26 * @author Robert Harder
27 * @author rob@iharder.net
28 * @version 1.3.4
30 public class Base64
33 /** Specify encoding (value is <tt>true</tt>). */
34 public final static boolean ENCODE = true;
37 /** Specify decoding (value is <tt>false</tt>). */
38 public final static boolean DECODE = false;
41 /** Maximum line length (76) of Base64 output. */
42 private final static int MAX_LINE_LENGTH = 76;
45 /** The equals sign (=) as a byte. */
46 private final static byte EQUALS_SIGN = (byte)'=';
49 /** The new line character (\n) as a byte. */
50 private final static byte NEW_LINE = (byte)'\n';
53 /** The 64 valid Base64 values. */
54 private final static byte[] ALPHABET =
56 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
57 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
58 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
59 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
60 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
61 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
62 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
63 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
64 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
65 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
68 /**
69 * Translates a Base64 value to either its 6-bit reconstruction value
70 * or a negative number indicating some other meaning.
71 **/
72 private final static byte[] DECODABET =
74 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
75 -5,-5, // Whitespace: Tab and Linefeed
76 -9,-9, // Decimal 11 - 12
77 -5, // Whitespace: Carriage Return
78 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
79 -9,-9,-9,-9,-9, // Decimal 27 - 31
80 -5, // Whitespace: Space
81 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
82 62, // Plus sign at decimal 43
83 -9,-9,-9, // Decimal 44 - 46
84 63, // Slash at decimal 47
85 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
86 -9,-9,-9, // Decimal 58 - 60
87 -1, // Equals sign at decimal 61
88 -9,-9,-9, // Decimal 62 - 64
89 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
90 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
91 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
92 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
93 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
94 -9,-9,-9,-9 // Decimal 123 - 126
95 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
96 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
97 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
98 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
99 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
100 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
101 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
102 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
103 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
104 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
107 // Unused.
108 // private final static byte BAD_ENCODING = -9; // Indicates error in encoding
109 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
110 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
113 /** Defeats instantiation. */
114 private Base64(){}
116 /* ******** E N C O D I N G M E T H O D S ******** */
120 * Encodes the first three bytes of array <var>threeBytes</var>
121 * and returns a four-byte array in Base64 notation.
123 * @param threeBytes the array to convert
124 * @return four byte array in Base64 notation.
125 * @since 1.3
127 // private static byte[] encode3to4( byte[] threeBytes )
128 // { return encode3to4( threeBytes, 3 );
129 // } // end encodeToBytes
130 // Is unused and private.
134 * Encodes up to the first three bytes of array <var>threeBytes</var>
135 * and returns a four-byte array in Base64 notation.
136 * The actual number of significant bytes in your array is
137 * given by <var>numSigBytes</var>.
138 * The array <var>threeBytes</var> needs only be as big as
139 * <var>numSigBytes</var>.
141 * @param threeBytes the array to convert
142 * @param numSigBytes the number of significant bytes in your array
143 * @return four byte array in Base64 notation.
144 * @since 1.3
146 private static byte[] encode3to4( byte[] threeBytes, int numSigBytes )
147 { byte[] dest = new byte[4];
148 encode3to4( threeBytes, 0, numSigBytes, dest, 0 );
149 return dest;
155 * Encodes up to three bytes of the array <var>source</var>
156 * and writes the resulting four Base64 bytes to <var>destination</var>.
157 * The source and destination arrays can be manipulated
158 * anywhere along their length by specifying
159 * <var>srcOffset</var> and <var>destOffset</var>.
160 * This method does not check to make sure your arrays
161 * are large enough to accomodate <var>srcOffset</var> + 3 for
162 * the <var>source</var> array or <var>destOffset</var> + 4 for
163 * the <var>destination</var> array.
164 * The actual number of significant bytes in your array is
165 * given by <var>numSigBytes</var>.
167 * @param source the array to convert
168 * @param srcOffset the index where conversion begins
169 * @param numSigBytes the number of significant bytes in your array
170 * @param destination the array to hold the conversion
171 * @param destOffset the index where output will be put
172 * @return the <var>destination</var> array
173 * @since 1.3
175 private static byte[] encode3to4(
176 byte[] source, int srcOffset, int numSigBytes,
177 byte[] destination, int destOffset )
179 // 1 2 3
180 // 01234567890123456789012345678901 Bit position
181 // --------000000001111111122222222 Array position from threeBytes
182 // --------| || || || | Six bit groups to index ALPHABET
183 // >>18 >>12 >> 6 >> 0 Right shift necessary
184 // 0x3f 0x3f 0x3f Additional AND
186 // Create buffer with zero-padding if there are only one or two
187 // significant bytes passed in the array.
188 // We have to shift left 24 in order to flush out the 1's that appear
189 // when Java treats a value as negative that is cast from a byte to an int.
190 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
191 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
192 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
194 switch( numSigBytes )
196 case 3:
197 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
198 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
199 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
200 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
201 return destination;
203 case 2:
204 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
205 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
206 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
207 destination[ destOffset + 3 ] = EQUALS_SIGN;
208 return destination;
210 case 1:
211 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
212 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
213 destination[ destOffset + 2 ] = EQUALS_SIGN;
214 destination[ destOffset + 3 ] = EQUALS_SIGN;
215 return destination;
217 default:
218 return destination;
219 } // end switch
220 } // end encode3to4
223 * Serializes an object and returns the Base64-encoded
224 * version of that serialized object. If the object
225 * cannot be serialized or there is another error,
226 * the method will return <tt>null</tt>.
228 * @param serializableObject The object to encode
229 * @return The Base64-encoded object
230 * @since 1.4
232 public static String encodeObject( java.io.Serializable serializableObject )
234 return encodeObject( serializableObject, true );
235 } // end encodeObject
238 * Serializes an object and returns the Base64-encoded
239 * version of that serialized object. If the object
240 * cannot be serialized or there is another error,
241 * the method will return <tt>null</tt>.
243 * @param serializableObject The object to encode
244 * @param breakLines Break lines at 80 characters or less.
245 * @return The Base64-encoded object
246 * @since 1.4
248 public static String encodeObject( java.io.Serializable serializableObject, boolean breakLines )
250 java.io.ByteArrayOutputStream baos = null;
251 java.io.OutputStream b64os = null;
252 java.io.ObjectOutputStream oos = null;
256 baos = new java.io.ByteArrayOutputStream();
257 b64os = new Base64.OutputStream( baos, Base64.ENCODE, breakLines );
258 oos = new java.io.ObjectOutputStream( b64os );
260 oos.writeObject( serializableObject );
261 } // end try
262 catch( java.io.IOException e )
264 e.printStackTrace();
265 return null;
266 } // end catch
267 finally
269 try{ oos.close(); } catch( Exception e ){}
270 try{ b64os.close(); } catch( Exception e ){}
271 try{ baos.close(); } catch( Exception e ){}
272 } // end finally
274 return new String( baos.toByteArray() );
275 } // end encode
279 * Encodes a byte array into Base64 notation.
280 * Equivalen to calling
281 * <code>encodeBytes( source, 0, source.length )</code>
283 * @param source The data to convert
284 * @since 1.4
286 public static String encodeBytes( byte[] source )
288 return encodeBytes( source, true );
289 } // end encodeBytes
292 * Encodes a byte array into Base64 notation.
293 * Equivalen to calling
294 * <code>encodeBytes( source, 0, source.length )</code>
296 * @param source The data to convert
297 * @param breakLines Break lines at 80 characters or less.
298 * @since 1.4
300 public static String encodeBytes( byte[] source, boolean breakLines )
302 return encodeBytes( source, 0, source.length, breakLines );
303 } // end encodeBytes
307 * Encodes a byte array into Base64 notation.
309 * @param source The data to convert
310 * @param off Offset in array where conversion should begin
311 * @param len Length of data to convert
312 * @since 1.4
314 public static String encodeBytes( byte[] source, int off, int len )
316 return encodeBytes( source, off, len, true );
317 } // end encodeBytes
321 * Encodes a byte array into Base64 notation.
323 * @param source The data to convert
324 * @param off Offset in array where conversion should begin
325 * @param len Length of data to convert
326 * @param breakLines Break lines at 80 characters or less.
327 * @since 1.4
329 public static String encodeBytes( byte[] source, int off, int len, boolean breakLines )
331 int len43 = len * 4 / 3;
332 byte[] outBuff = new byte[ ( len43 ) // Main 4:3
333 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
334 + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
335 int d = 0;
336 int e = 0;
337 int len2 = len - 2;
338 int lineLength = 0;
339 for( ; d < len2; d+=3, e+=4 )
341 encode3to4( source, d+off, 3, outBuff, e );
343 lineLength += 4;
344 if( breakLines && lineLength == MAX_LINE_LENGTH )
346 outBuff[e+4] = NEW_LINE;
347 e++;
348 lineLength = 0;
349 } // end if: end of line
350 } // en dfor: each piece of array
352 if( d < len )
354 encode3to4( source, d+off, len - d, outBuff, e );
355 e += 4;
356 } // end if: some padding needed
358 return new String( outBuff, 0, e );
359 } // end encodeBytes
363 * Encodes a string in Base64 notation with line breaks
364 * after every 75 Base64 characters.
366 * @param s the string to encode
367 * @return the encoded string
368 * @since 1.3
370 public static String encodeString( String s )
372 return encodeString( s, true );
373 } // end encodeString
376 * Encodes a string in Base64 notation with line breaks
377 * after every 75 Base64 characters.
379 * @param s the string to encode
380 * @param breakLines Break lines at 80 characters or less.
381 * @return the encoded string
382 * @since 1.3
384 public static String encodeString( String s, boolean breakLines )
386 return encodeBytes( s.getBytes(), breakLines );
387 } // end encodeString
392 /* ******** D E C O D I N G M E T H O D S ******** */
396 * Decodes the first four bytes of array <var>fourBytes</var>
397 * and returns an array up to three bytes long with the
398 * decoded values.
400 * @param fourBytes the array with Base64 content
401 * @return array with decoded values
402 * @since 1.3
404 private static byte[] decode4to3( byte[] fourBytes )
406 byte[] outBuff1 = new byte[3];
407 int count = decode4to3( fourBytes, 0, outBuff1, 0 );
408 byte[] outBuff2 = new byte[ count ];
410 for( int i = 0; i < count; i++ )
411 outBuff2[i] = outBuff1[i];
413 return outBuff2;
420 * Decodes four bytes from array <var>source</var>
421 * and writes the resulting bytes (up to three of them)
422 * to <var>destination</var>.
423 * The source and destination arrays can be manipulated
424 * anywhere along their length by specifying
425 * <var>srcOffset</var> and <var>destOffset</var>.
426 * This method does not check to make sure your arrays
427 * are large enough to accomodate <var>srcOffset</var> + 4 for
428 * the <var>source</var> array or <var>destOffset</var> + 3 for
429 * the <var>destination</var> array.
430 * This method returns the actual number of bytes that
431 * were converted from the Base64 encoding.
434 * @param source the array to convert
435 * @param srcOffset the index where conversion begins
436 * @param destination the array to hold the conversion
437 * @param destOffset the index where output will be put
438 * @return the number of decoded bytes converted
439 * @since 1.3
441 private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
443 // Example: Dk==
444 if( source[ srcOffset + 2] == EQUALS_SIGN )
446 // Two ways to do the same thing. Don't know which way I like best.
447 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
448 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
449 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
450 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
452 destination[ destOffset ] = (byte)( outBuff >>> 16 );
453 return 1;
456 // Example: DkL=
457 else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
459 // Two ways to do the same thing. Don't know which way I like best.
460 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
461 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
462 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
463 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
464 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
465 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
467 destination[ destOffset ] = (byte)( outBuff >>> 16 );
468 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
469 return 2;
472 // Example: DkLE
473 else
475 try{
476 // Two ways to do the same thing. Don't know which way I like best.
477 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
478 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
479 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
480 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
481 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
482 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
483 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
484 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
487 destination[ destOffset ] = (byte)( outBuff >> 16 );
488 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
489 destination[ destOffset + 2 ] = (byte)( outBuff );
491 return 3;
492 }catch( Exception e){
493 System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
494 System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
495 System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
496 System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
497 return -1;
498 } //e nd catch
500 } // end decodeToBytes
505 * Decodes data from Base64 notation.
507 * @param s the string to decode
508 * @return the decoded data
509 * @since 1.4
511 public static byte[] decode( String s )
512 throws DecodeException
514 byte[] bytes = s.getBytes();
515 return decode( bytes, 0, bytes.length );
516 } // end decode
520 * Decodes data from Base64 notation and
521 * returns it as a string.
522 * Equivlaent to calling
523 * <code>new String( decode( s ) )</code>
525 * @param s the strind to decode
526 * @return The data as a string
527 * @since 1.4
529 public static String decodeToString( String s )
530 throws DecodeException
531 { return new String( decode( s ) );
532 } // end decodeToString
536 * Attempts to decode Base64 data and deserialize a Java
537 * Object within. Returns <tt>null if there was an error.
539 * @param encodedObject The Base64 data to decode
540 * @return The decoded and deserialized object
541 * @since 1.4
543 public static Object decodeToObject( String encodedObject )
544 throws DecodeException
546 byte[] objBytes = decode( encodedObject );
548 java.io.ByteArrayInputStream bais = null;
549 java.io.ObjectInputStream ois = null;
553 bais = new java.io.ByteArrayInputStream( objBytes );
554 ois = new java.io.ObjectInputStream( bais );
556 return ois.readObject();
557 } // end try
558 catch( java.io.IOException e )
560 e.printStackTrace();
561 return null;
562 } // end catch
563 catch( java.lang.ClassNotFoundException e )
565 e.printStackTrace();
566 return null;
567 } // end catch
568 finally
570 try{ bais.close(); } catch( Exception e ){}
571 try{ ois.close(); } catch( Exception e ){}
572 } // end finally
573 } // end decodeObject
575 public static class DecodeException extends Exception
577 DecodeException(String e)
579 super(e);
584 * Decodes Base64 content in byte array format and returns
585 * the decoded byte array.
587 * @param source The Base64 encoded data
588 * @param off The offset of where to begin decoding
589 * @param len The length of characters to decode
590 * @return decoded data
591 * @since 1.3
593 public static byte[] decode( byte[] source, int off, int len )
594 throws DecodeException
596 int len34 = len * 3 / 4;
597 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
598 int outBuffPosn = 0;
600 byte[] b4 = new byte[4];
601 int b4Posn = 0;
602 int i = 0;
603 byte sbiCrop = 0;
604 byte sbiDecode = 0;
605 for( i = 0; i < len; i++ )
607 sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
608 sbiDecode = DECODABET[ sbiCrop ];
610 if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
612 if( sbiDecode >= EQUALS_SIGN_ENC )
614 b4[ b4Posn++ ] = sbiCrop;
615 if( b4Posn > 3 )
617 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
618 b4Posn = 0;
620 // If that was the equals sign, break out of 'for' loop
621 if( sbiCrop == EQUALS_SIGN )
622 break;
623 } // end if: quartet built
625 } // end if: equals sign or better
627 } // end if: white space, equals sign or better
628 else
629 throw new DecodeException("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
630 } // each input character
632 byte[] out = new byte[ outBuffPosn ];
633 System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
634 return out;
635 } // end decode
640 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
645 * A {@link Base64#InputStream} will read data from another
646 * {@link java.io.InputStream}, given in the constructor,
647 * and encode/decode to/from Base64 notation on the fly.
649 * @see Base64
650 * @see java.io.FilterInputStream
651 * @since 1.3
653 public static class InputStream extends java.io.FilterInputStream
655 private boolean encode; // Encoding or decoding
656 private int position; // Current position in the buffer
657 private byte[] buffer; // Small buffer holding converted data
658 private int bufferLength; // Length of buffer (3 or 4)
659 private int numSigBytes; // Number of meaningful bytes in the buffer
660 private int lineLength;
661 private boolean breakLines; // Break lines at less than 80 characters
665 * Constructs a {@link Base64#InputStream} in DECODE mode.
667 * @param in the {@link java.io.InputStream} from which to read data.
668 * @since 1.3
670 public InputStream( java.io.InputStream in )
672 this( in, Base64.DECODE );
673 } // end constructor
677 * Constructs a {@link Base64#InputStream} in
678 * either ENCODE or DECODE mode.
680 * @param in the {@link java.io.InputStream} from which to read data.
681 * @param encode Conversion direction
682 * @see Base64#ENCODE
683 * @see Base64#DECODE
684 * @since 1.3
686 public InputStream( java.io.InputStream in, boolean encode )
688 this( in, encode, true );
689 } // end constructor
693 * Constructs a {@link Base64#InputStream} in
694 * either ENCODE or DECODE mode.
696 * @param in the {@link java.io.InputStream} from which to read data.
697 * @param encode Conversion direction
698 * @param breakLines Break lines at less than 80 characters.
699 * @see Base64#ENCODE
700 * @see Base64#DECODE
701 * @since 1.3
703 public InputStream( java.io.InputStream in, boolean encode, boolean breakLines )
705 super( in );
706 this.breakLines = breakLines;
707 this.encode = encode;
708 this.bufferLength = encode ? 4 : 3;
709 this.buffer = new byte[ bufferLength ];
710 this.position = -1;
711 this.lineLength = 0;
712 } // end constructor
715 * Reads enough of the input stream to convert
716 * to/from Base64 and returns the next byte.
718 * @return next byte
719 * @since 1.3
721 public int read() throws java.io.IOException
723 // Do we need to get data?
724 if( position < 0 )
726 if( encode )
728 byte[] b3 = new byte[3];
729 int numBinaryBytes = 0;
730 for( int i = 0; i < 3; i++ )
734 int b = in.read();
736 // If end of stream, b is -1.
737 if( b >= 0 )
739 b3[i] = (byte)b;
740 numBinaryBytes++;
741 } // end if: not end of stream
743 } // end try: read
744 catch( java.io.IOException e )
746 // Only a problem if we got no data at all.
747 if( i == 0 )
748 throw e;
750 } // end catch
751 } // end for: each needed input byte
753 if( numBinaryBytes > 0 )
755 encode3to4( b3, 0, numBinaryBytes, buffer, 0 );
756 position = 0;
757 numSigBytes = 4;
758 } // end if: got data
759 else
761 return -1;
762 } // end else
763 } // end if: encoding
765 // Else decoding
766 else
768 byte[] b4 = new byte[4];
769 int i = 0;
770 for( i = 0; i < 4; i++ )
772 // Read four "meaningful" bytes:
773 int b = 0;
774 do{ b = in.read(); }
775 while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC );
777 if( b < 0 )
778 break; // Reads a -1 if end of stream
780 b4[i] = (byte)b;
781 } // end for: each needed input byte
783 if( i == 4 )
785 numSigBytes = decode4to3( b4, 0, buffer, 0 );
786 position = 0;
787 } // end if: got four characters
788 else if( i == 0 ){
789 return -1;
790 } // end else if: also padded correctly
791 else
793 // Must have broken out from above.
794 throw new java.io.IOException( "Improperly padded Base64 input." );
795 } // end
797 } // end else: decode
798 } // end else: get data
800 // Got data?
801 if( position >= 0 )
803 // End of relevant data?
804 if( /*!encode &&*/ position >= numSigBytes )
805 return -1;
807 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
809 lineLength = 0;
810 return '\n';
811 } // end if
812 else
814 lineLength++; // This isn't important when decoding
815 // but throwing an extra "if" seems
816 // just as wasteful.
818 int b = buffer[ position++ ];
820 if( position >= bufferLength )
821 position = -1;
823 return b & 0xFF; // This is how you "cast" a byte that's
824 // intended to be unsigned.
825 } // end else
826 } // end if: position >= 0
828 // Else error
829 else
831 // When JDK1.4 is more accepted, use an assertion here.
832 throw new java.io.IOException( "Error in Base64 code reading stream." );
833 } // end else
834 } // end read
838 * Calls {@link #read} repeatedly until the end of stream
839 * is reached or <var>len</var> bytes are read.
840 * Returns number of bytes read into array or -1 if
841 * end of stream is encountered.
843 * @param dest array to hold values
844 * @param off offset for array
845 * @param len max number of bytes to read into array
846 * @return bytes read into array or -1 if end of stream is encountered.
847 * @since 1.3
849 public int read( byte[] dest, int off, int len ) throws java.io.IOException
851 int i;
852 int b;
853 for( i = 0; i < len; i++ )
855 b = read();
857 //if( b < 0 && i == 0 )
858 // return -1;
860 if( b >= 0 )
861 dest[off + i] = (byte)b;
862 else if( i == 0 )
863 return -1;
864 else
865 break; // Out of 'for' loop
866 } // end for: each byte read
867 return i;
868 } // end read
870 } // end inner class InputStream
877 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
882 * A {@link Base64#OutputStream} will write data to another
883 * {@link java.io.OutputStream}, given in the constructor,
884 * and encode/decode to/from Base64 notation on the fly.
886 * @see Base64
887 * @see java.io.FilterOutputStream
888 * @since 1.3
890 public static class OutputStream extends java.io.FilterOutputStream
892 private boolean encode;
893 private int position;
894 private byte[] buffer;
895 private int bufferLength;
896 private int lineLength;
897 private boolean breakLines;
901 * Constructs a {@link Base64#OutputStream} in ENCODE mode.
903 * @param out the {@link java.io.OutputStream} to which data will be written.
904 * @since 1.3
906 public OutputStream( java.io.OutputStream out )
908 this( out, Base64.ENCODE );
909 } // end constructor
913 * Constructs a {@link Base64#OutputStream} in
914 * either ENCODE or DECODE mode.
916 * @param out the {@link java.io.OutputStream} to which data will be written.
917 * @param encode Conversion direction
918 * @see Base64#ENCODE
919 * @see Base64#DECODE
920 * @since 1.3
922 public OutputStream( java.io.OutputStream out, boolean encode )
924 this( out, encode, true );
925 } // end constructor
929 * Constructs a {@link Base64#OutputStream} in
930 * either ENCODE or DECODE mode.
932 * @param out the {@link java.io.OutputStream} to which data will be written.
933 * @param encode Conversion direction
934 * @param breakLines Break lines to be less than 80 characters.
935 * @see Base64#ENCODE
936 * @see Base64#DECODE
937 * @since 1.3
939 public OutputStream( java.io.OutputStream out, boolean encode, boolean breakLines )
941 super( out );
942 this.breakLines = breakLines;
943 this.encode = encode;
944 this.bufferLength = encode ? 3 : 4;
945 this.buffer = new byte[ bufferLength ];
946 this.position = 0;
947 this.lineLength = 0;
948 } // end constructor
952 * Writes the byte to the output stream after
953 * converting to/from Base64 notation.
954 * When encoding, bytes are buffered three
955 * at a time before the output stream actually
956 * gets a write() call.
957 * When decoding, bytes are buffered four
958 * at a time.
960 * @param theByte the byte to write
961 * @since 1.3
963 public void write(int theByte) throws java.io.IOException
965 if( encode )
967 buffer[ position++ ] = (byte)theByte;
968 if( position >= bufferLength ) // Enough to encode.
970 out.write( Base64.encode3to4( buffer, bufferLength ) );
972 lineLength += 4;
973 if( breakLines && lineLength >= MAX_LINE_LENGTH )
975 out.write( NEW_LINE );
976 lineLength = 0;
977 } // end if: end of line
979 position = 0;
980 } // end if: enough to output
981 } // end if: encoding
983 // Else, Decoding
984 else
986 // Meaningful Base64 character?
987 if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC )
989 buffer[ position++ ] = (byte)theByte;
990 if( position >= bufferLength ) // Enough to output.
992 out.write( Base64.decode4to3( buffer ) );
993 position = 0;
994 } // end if: enough to output
995 } // end if: meaningful base64 character
996 else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC )
998 throw new java.io.IOException( "Invalid character in Base64 data." );
999 } // end else: not white space either
1000 } // end else: decoding
1001 } // end write
1006 * Calls {@link #write} repeatedly until <var>len</var>
1007 * bytes are written.
1009 * @param theBytes array from which to read bytes
1010 * @param off offset for array
1011 * @param len max number of bytes to read into array
1012 * @since 1.3
1014 public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
1016 for( int i = 0; i < len; i++ )
1018 write( theBytes[ off + i ] );
1019 } // end for: each byte written
1021 } // end write
1025 * Appropriately pads Base64 notation when encoding
1026 * or throws an exception if Base64 input is not
1027 * properly padded when decoding.
1029 * @since 1.3
1031 public void flush() throws java.io.IOException
1033 super.flush();
1035 if( position > 0 )
1037 if( encode )
1039 out.write( Base64.encode3to4( buffer, position ) );
1040 position = 0;
1041 } // end if: encoding
1042 else
1044 throw new java.io.IOException( "Base64 input not properly padded." );
1045 } // end else: decoding
1046 } // end if: buffer partially full
1048 out.flush();
1049 } // end flush
1052 /**
1053 * Flushes and closes (I think, in the superclass) the stream.
1055 * @since 1.3
1057 public void close() throws java.io.IOException
1059 super.close();
1060 //this.flush();
1062 out.close();
1064 buffer = null;
1065 out = null;
1066 } // end close
1068 } // end inner class OutputStream
1071 } // end class Base64