source: branches/2.2/jabberit_messenger/java_source/src/nu/fw/jeti/util/Base64.java @ 3102

Revision 3102, 25.7 KB checked in by amuller, 14 years ago (diff)

Ticket #986 - Efetuado merge para o Branch 2.2( atualizacao do modulo)

  • Property svn:executable set to *
Line 
1package nu.fw.jeti.util;
2
3/**
4 * Encodes and decodes to and from Base64 notation.
5 *
6 * <p>
7 * Change Log:
8 * </p>
9 * <ul>
10 *  <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
11 *   some convenience methods for reading and writing to and from files.</li>
12 *  <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
13 *   with other encodings (like EBCDIC).</li>
14 *  <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
15 *   encoded data was a single byte.</li>
16 *  <li>v2.0 - I got rid of methods that used booleans to set options.
17 *   Now everything is more consolidated and cleaner. The code now detects
18 *   when data that's being decoded is gzip-compressed and will decompress it
19 *   automatically. Generally things are cleaner. You'll probably have to
20 *   change some method calls that you were making to support the new
21 *   options format (<tt>int</tt>s that you "OR" together).</li>
22 *  <li>v1.5.1 - Fixed bug when decompressing and decoding to a             
23 *   byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.     
24 *   Added the ability to "suspend" encoding in the Output Stream so       
25 *   you can turn on and off the encoding if you need to embed base64       
26 *   data in an otherwise "normal" stream (like an XML file).</li> 
27 *  <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
28 *      This helps when using GZIP streams.
29 *      Added the ability to GZip-compress objects before encoding them.</li>
30 *  <li>v1.4 - Added helper methods to read/write files.</li>
31 *  <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
32 *  <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
33 *      where last buffer being read, if not completely full, was not returned.</li>
34 *  <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
35 *  <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
36 * </ul>
37 *
38 * <p>
39 * I am placing this code in the Public Domain. Do with it as you will.
40 * This software comes with no guarantees or warranties but with
41 * plenty of well-wishing instead!
42 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
43 * periodically to check for updates or to contribute improvements.
44 * </p>
45 *
46 * @author Robert Harder
47 * @author rob@iharder.net
48 * @version 2.1
49 */
50public class Base64
51{
52   
53/* ********  P U B L I C   F I E L D S  ******** */   
54   
55   
56    /** No options specified. Value is zero. */
57    public final static int NO_OPTIONS = 0;
58   
59    /** Specify encoding. */
60    public final static int ENCODE = 1;
61   
62   
63    /** Specify decoding. */
64    public final static int DECODE = 0;
65   
66   
67    /** Specify that data should be gzip-compressed. */
68    public final static int GZIP = 2;
69   
70   
71    /** Don't break lines when encoding (violates strict Base64 specification) */
72    public final static int DONT_BREAK_LINES = 8;
73   
74   
75/* ********  P R I V A T E   F I E L D S  ******** */ 
76   
77   
78    /** Maximum line length (76) of Base64 output. */
79    private final static int MAX_LINE_LENGTH = 76;
80   
81   
82    /** The equals sign (=) as a byte. */
83    private final static byte EQUALS_SIGN = (byte)'=';
84   
85   
86    /** The new line character (\n) as a byte. */
87    private final static byte NEW_LINE = (byte)'\n';
88   
89   
90    /** Preferred encoding. */
91    private final static String PREFERRED_ENCODING = "UTF-8";
92   
93   
94    /** The 64 valid Base64 values. */
95    private final static byte[] ALPHABET;
96    private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
97    {
98        (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
99        (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
100        (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
101        (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
102        (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
103        (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
104        (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
105        (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
106        (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
107        (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
108    };
109   
110    /** Determine which ALPHABET to use. */
111    static
112    {
113        byte[] __bytes;
114        try
115        {
116            __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING );
117        }   // end try
118        catch (java.io.UnsupportedEncodingException use)
119        {
120            __bytes = _NATIVE_ALPHABET; // Fall back to native encoding
121        }   // end catch
122        ALPHABET = __bytes;
123    }   // end static
124   
125   
126    /**
127     * Translates a Base64 value to either its 6-bit reconstruction value
128     * or a negative number indicating some other meaning.
129     **/
130    private final static byte[] DECODABET =
131    {   
132        -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8
133        -5,-5,                                      // Whitespace: Tab and Linefeed
134        -9,-9,                                      // Decimal 11 - 12
135        -5,                                         // Whitespace: Carriage Return
136        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26
137        -9,-9,-9,-9,-9,                             // Decimal 27 - 31
138        -5,                                         // Whitespace: Space
139        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42
140        62,                                         // Plus sign at decimal 43
141        -9,-9,-9,                                   // Decimal 44 - 46
142        63,                                         // Slash at decimal 47
143        52,53,54,55,56,57,58,59,60,61,              // Numbers zero through nine
144        -9,-9,-9,                                   // Decimal 58 - 60
145        -1,                                         // Equals sign at decimal 61
146        -9,-9,-9,                                      // Decimal 62 - 64
147        0,1,2,3,4,5,6,7,8,9,10,11,12,13,            // Letters 'A' through 'N'
148        14,15,16,17,18,19,20,21,22,23,24,25,        // Letters 'O' through 'Z'
149        -9,-9,-9,-9,-9,-9,                          // Decimal 91 - 96
150        26,27,28,29,30,31,32,33,34,35,36,37,38,     // Letters 'a' through 'm'
151        39,40,41,42,43,44,45,46,47,48,49,50,51,     // Letters 'n' through 'z'
152        -9,-9,-9,-9                                 // Decimal 123 - 126
153        /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 127 - 139
154        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152
155        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165
156        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178
157        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191
158        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204
159        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217
160        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230
161        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243
162        -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 */
163    };
164   
165    // I think I end up not using the BAD_ENCODING indicator.
166    //private final static byte BAD_ENCODING    = -9; // Indicates error in encoding
167    private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
168    private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
169
170   
171    /** Defeats instantiation. */
172    private Base64(){}
173   
174   
175   
176/* ********  E N C O D I N G   M E T H O D S  ******** */   
177   
178   
179   
180   
181    /**
182     * Encodes up to three bytes of the array <var>source</var>
183     * and writes the resulting four Base64 bytes to <var>destination</var>.
184     * The source and destination arrays can be manipulated
185     * anywhere along their length by specifying
186     * <var>srcOffset</var> and <var>destOffset</var>.
187     * This method does not check to make sure your arrays
188     * are large enough to accomodate <var>srcOffset</var> + 3 for
189     * the <var>source</var> array or <var>destOffset</var> + 4 for
190     * the <var>destination</var> array.
191     * The actual number of significant bytes in your array is
192     * given by <var>numSigBytes</var>.
193     *
194     * @param source the array to convert
195     * @param srcOffset the index where conversion begins
196     * @param numSigBytes the number of significant bytes in your array
197     * @param destination the array to hold the conversion
198     * @param destOffset the index where output will be put
199     * @return the <var>destination</var> array
200     * @since 1.3
201     */
202    private static byte[] encode3to4(
203     byte[] source, int srcOffset, int numSigBytes,
204     byte[] destination, int destOffset )
205    {
206        //           1         2         3 
207        // 01234567890123456789012345678901 Bit position
208        // --------000000001111111122222222 Array position from threeBytes
209        // --------|    ||    ||    ||    | Six bit groups to index ALPHABET
210        //          >>18  >>12  >> 6  >> 0  Right shift necessary
211        //                0x3f  0x3f  0x3f  Additional AND
212       
213        // Create buffer with zero-padding if there are only one or two
214        // significant bytes passed in the array.
215        // We have to shift left 24 in order to flush out the 1's that appear
216        // when Java treats a value as negative that is cast from a byte to an int.
217        int inBuff =   ( numSigBytes > 0 ? ((source[ srcOffset     ] << 24) >>>  8) : 0 )
218                     | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
219                     | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
220
221        switch( numSigBytes )
222        {
223            case 3:
224                destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];
225                destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
226                destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>>  6) & 0x3f ];
227                destination[ destOffset + 3 ] = ALPHABET[ (inBuff       ) & 0x3f ];
228                return destination;
229               
230            case 2:
231                destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];
232                destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
233                destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>>  6) & 0x3f ];
234                destination[ destOffset + 3 ] = EQUALS_SIGN;
235                return destination;
236               
237            case 1:
238                destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];
239                destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
240                destination[ destOffset + 2 ] = EQUALS_SIGN;
241                destination[ destOffset + 3 ] = EQUALS_SIGN;
242                return destination;
243               
244            default:
245                return destination;
246        }   // end switch
247    }   // end encode3to4
248   
249   
250   
251    /**
252     * Encodes a byte array into Base64 notation.
253     * Does not GZip-compress data.
254     *
255     * @param source The data to convert
256     * @since 1.4
257     */
258    public static String encodeBytes( byte[] source )
259    {
260        return encodeBytes( source, 0, source.length, NO_OPTIONS );
261    }   // end encodeBytes
262   
263
264
265    /**
266     * Encodes a byte array into Base64 notation.
267     * <p>
268     * Valid options:<pre>
269     *   GZIP: gzip-compresses object before encoding it.
270     *   DONT_BREAK_LINES: don't break lines at 76 characters
271     *     <i>Note: Technically, this makes your encoding non-compliant.</i>
272     * </pre>
273     * <p>
274     * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
275     * <p>
276     * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
277     *
278     *
279     * @param source The data to convert
280     * @param options Specified options
281     * @see Base64#GZIP
282     * @see Base64#DONT_BREAK_LINES
283     * @since 2.0
284     */
285    public static String encodeBytes( byte[] source, int options )
286    {   
287        return encodeBytes( source, 0, source.length, options );
288    }   // end encodeBytes
289   
290   
291    /**
292     * Encodes a byte array into Base64 notation.
293     * Does not GZip-compress data.
294     *
295     * @param source The data to convert
296     * @param off Offset in array where conversion should begin
297     * @param len Length of data to convert
298     * @since 1.4
299     */
300    public static String encodeBytes( byte[] source, int off, int len )
301    {
302        return encodeBytes( source, off, len, NO_OPTIONS );
303    }   // end encodeBytes
304   
305   
306
307    /**
308     * Encodes a byte array into Base64 notation.
309     * <p>
310     * Valid options:<pre>
311     *   GZIP: gzip-compresses object before encoding it.
312     *   DONT_BREAK_LINES: don't break lines at 76 characters
313     *     <i>Note: Technically, this makes your encoding non-compliant.</i>
314     * </pre>
315     * <p>
316     * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
317     * <p>
318     * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
319     *
320     *
321     * @param source The data to convert
322     * @param off Offset in array where conversion should begin
323     * @param len Length of data to convert
324     * @param options Specified options
325     * @see Base64#GZIP
326     * @see Base64#DONT_BREAK_LINES
327     * @since 2.0
328     */
329    public static String encodeBytes( byte[] source, int off, int len, int options )
330    {
331        // Isolate options
332        int dontBreakLines = ( options & DONT_BREAK_LINES );
333        int gzip           = ( options & GZIP   );
334       
335        // Compress?
336        if( gzip == GZIP )
337        {
338                /*
339            java.io.ByteArrayOutputStream  baos  = null;
340            java.util.zip.GZIPOutputStream gzos  = null;
341            Base64.OutputStream            b64os = null;
342           
343   
344            try
345            {
346                // GZip -> Base64 -> ByteArray
347                baos = new java.io.ByteArrayOutputStream();
348                b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
349                gzos  = new java.util.zip.GZIPOutputStream( b64os );
350           
351                gzos.write( source, off, len );
352                gzos.close();
353            }   // end try
354            catch( java.io.IOException e )
355            {
356                e.printStackTrace();
357                return null;
358            }   // end catch
359            finally
360            {
361                try{ gzos.close();  } catch( Exception e ){}
362                try{ b64os.close(); } catch( Exception e ){}
363                try{ baos.close();  } catch( Exception e ){}
364            }   // end finally
365
366            // Return value according to relevant encoding.
367            try
368            {
369                return new String( baos.toByteArray(), PREFERRED_ENCODING );
370            }   // end try
371            catch (java.io.UnsupportedEncodingException uue)
372            {
373                return new String( baos.toByteArray() );
374            }   // end catch
375            */
376                return null;
377        }   // end if: compress
378       
379        // Else, don't compress. Better not to use streams at all then.
380        else
381        {
382            // Convert option to boolean in way that code likes it.
383            boolean breakLines = dontBreakLines == 0;
384           
385            int    len43   = len * 4 / 3;
386            byte[] outBuff = new byte[   ( len43 )                      // Main 4:3
387                                       + ( (len % 3) > 0 ? 4 : 0 )      // Account for padding
388                                       + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines     
389            int d = 0;
390            int e = 0;
391            int len2 = len - 2;
392            int lineLength = 0;
393            for( ; d < len2; d+=3, e+=4 )
394            {
395                encode3to4( source, d+off, 3, outBuff, e );
396
397                lineLength += 4;
398                if( breakLines && lineLength == MAX_LINE_LENGTH )
399                {   
400                    outBuff[e+4] = NEW_LINE;
401                    e++;
402                    lineLength = 0;
403                }   // end if: end of line
404            }   // en dfor: each piece of array
405
406            if( d < len )
407            {
408                encode3to4( source, d+off, len - d, outBuff, e );
409                e += 4;
410            }   // end if: some padding needed
411
412           
413            // Return value according to relevant encoding.
414            try
415            {
416                return new String( outBuff, 0, e, PREFERRED_ENCODING );
417            }   // end try
418            catch (java.io.UnsupportedEncodingException uue)
419            {
420                return new String( outBuff, 0, e );
421            }   // end catch
422           
423        }   // end else: don't compress
424       
425    }   // end encodeBytes
426   
427
428   
429   
430   
431/* ********  D E C O D I N G   M E T H O D S  ******** */
432   
433   
434    /**
435     * Decodes four bytes from array <var>source</var>
436     * and writes the resulting bytes (up to three of them)
437     * to <var>destination</var>.
438     * The source and destination arrays can be manipulated
439     * anywhere along their length by specifying
440     * <var>srcOffset</var> and <var>destOffset</var>.
441     * This method does not check to make sure your arrays
442     * are large enough to accomodate <var>srcOffset</var> + 4 for
443     * the <var>source</var> array or <var>destOffset</var> + 3 for
444     * the <var>destination</var> array.
445     * This method returns the actual number of bytes that
446     * were converted from the Base64 encoding.
447     *
448     *
449     * @param source the array to convert
450     * @param srcOffset the index where conversion begins
451     * @param destination the array to hold the conversion
452     * @param destOffset the index where output will be put
453     * @return the number of decoded bytes converted
454     * @since 1.3
455     */
456    private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
457    {
458        // Example: Dk==
459        if( source[ srcOffset + 2] == EQUALS_SIGN )
460        {
461            // Two ways to do the same thing. Don't know which way I like best.
462            //int outBuff =   ( ( DECODABET[ source[ srcOffset    ] ] << 24 ) >>>  6 )
463            //              | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
464            int outBuff =   ( ( DECODABET[ source[ srcOffset    ] ] & 0xFF ) << 18 )
465                          | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
466           
467            destination[ destOffset ] = (byte)( outBuff >>> 16 );
468            return 1;
469        }
470       
471        // Example: DkL=
472        else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
473        {
474            // Two ways to do the same thing. Don't know which way I like best.
475            //int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] << 24 ) >>>  6 )
476            //              | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
477            //              | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
478            int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] & 0xFF ) << 18 )
479                          | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
480                          | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) <<  6 );
481           
482            destination[ destOffset     ] = (byte)( outBuff >>> 16 );
483            destination[ destOffset + 1 ] = (byte)( outBuff >>>  8 );
484            return 2;
485        }
486       
487        // Example: DkLE
488        else
489        {
490            try{
491            // Two ways to do the same thing. Don't know which way I like best.
492            //int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] << 24 ) >>>  6 )
493            //              | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
494            //              | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
495            //              | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
496            int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] & 0xFF ) << 18 )
497                          | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
498                          | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) <<  6)
499                          | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF )      );
500
501           
502            destination[ destOffset     ] = (byte)( outBuff >> 16 );
503            destination[ destOffset + 1 ] = (byte)( outBuff >>  8 );
504            destination[ destOffset + 2 ] = (byte)( outBuff       );
505
506            return 3;
507            }catch( Exception e){
508                System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset     ] ]  ) );
509                System.out.println(""+source[srcOffset+1]+  ": " + ( DECODABET[ source[ srcOffset + 1 ] ]  ) );
510                System.out.println(""+source[srcOffset+2]+  ": " + ( DECODABET[ source[ srcOffset + 2 ] ]  ) );
511                System.out.println(""+source[srcOffset+3]+  ": " + ( DECODABET[ source[ srcOffset + 3 ] ]  ) );
512                return -1;
513            }   //e nd catch
514        }
515    }   // end decodeToBytes
516   
517   
518   
519   
520    /**
521     * Very low-level access to decoding ASCII characters in
522     * the form of a byte array. Does not support automatically
523     * gunzipping or any other "fancy" features.
524     *
525     * @param source The Base64 encoded data
526     * @param off    The offset of where to begin decoding
527     * @param len    The length of characters to decode
528     * @return decoded data
529     * @since 1.3
530     */
531    public static byte[] decode( byte[] source, int off, int len )
532    {
533        int    len34   = len * 3 / 4;
534        byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
535        int    outBuffPosn = 0;
536       
537        byte[] b4        = new byte[4];
538        int    b4Posn    = 0;
539        int    i         = 0;
540        byte   sbiCrop   = 0;
541        byte   sbiDecode = 0;
542        for( i = off; i < off+len; i++ )
543        {
544            sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
545            sbiDecode = DECODABET[ sbiCrop ];
546           
547            if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
548            {
549                if( sbiDecode >= EQUALS_SIGN_ENC )
550                {
551                    b4[ b4Posn++ ] = sbiCrop;
552                    if( b4Posn > 3 )
553                    {
554                        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
555                        b4Posn = 0;
556                       
557                        // If that was the equals sign, break out of 'for' loop
558                        if( sbiCrop == EQUALS_SIGN )
559                            break;
560                    }   // end if: quartet built
561                   
562                }   // end if: equals sign or better
563               
564            }   // end if: white space, equals sign or better
565            else
566            {
567                System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
568                return null;
569            }   // end else:
570        }   // each input character
571                                   
572        byte[] out = new byte[ outBuffPosn ];
573        System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
574        return out;
575    }   // end decode
576   
577   
578   
579   
580    /**
581     * Decodes data from Base64 notation, automatically
582     * detecting gzip-compressed data and decompressing it.
583     *
584     * @param s the string to decode
585     * @return the decoded data
586     * @since 1.4
587     */
588    public static byte[] decode( String s )
589    {   
590        byte[] bytes;
591        try
592        {
593            bytes = s.getBytes( PREFERRED_ENCODING );
594        }   // end try
595        catch( java.io.UnsupportedEncodingException uee )
596        {
597            bytes = s.getBytes();
598        }   // end catch
599                //</change>
600       
601        // Decode
602        bytes = decode( bytes, 0, bytes.length );
603       
604       
605        // Check to see if it's gzip-compressed
606        // GZIP Magic Two-Byte Number: 0x8b1f (35615)
607        if( bytes != null && bytes.length >= 4 )
608        {
609           
610            int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);       
611            if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
612            {
613                java.io.ByteArrayInputStream  bais = null;
614                java.util.zip.GZIPInputStream gzis = null;
615                java.io.ByteArrayOutputStream baos = null;
616                byte[] buffer = new byte[2048];
617                int    length = 0;
618
619                try
620                {
621                    baos = new java.io.ByteArrayOutputStream();
622                    bais = new java.io.ByteArrayInputStream( bytes );
623                    gzis = new java.util.zip.GZIPInputStream( bais );
624
625                    while( ( length = gzis.read( buffer ) ) >= 0 )
626                    {
627                        baos.write(buffer,0,length);
628                    }   // end while: reading input
629
630                    // No error? Get new bytes.
631                    bytes = baos.toByteArray();
632
633                }   // end try
634                catch( java.io.IOException e )
635                {
636                    // Just return originally-decoded bytes
637                }   // end catch
638                finally
639                {
640                    try{ baos.close(); } catch( Exception e ){}
641                    try{ gzis.close(); } catch( Exception e ){}
642                    try{ bais.close(); } catch( Exception e ){}
643                }   // end finally
644
645            }   // end if: gzipped
646        }   // end if: bytes.length >= 2
647       
648        return bytes;
649    }   // end decode
650
651
652   
653
654       
655}   // end class Base64
Note: See TracBrowser for help on using the repository browser.