KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > nava > informa > utils > Base64Decoder


1 /*
2  * Created on 26 juin 2004
3  */

4 package de.nava.informa.utils;
5
6 import java.io.IOException JavaDoc;
7 import java.io.FilterInputStream JavaDoc;
8 import java.io.*;
9
10 /**
11  * A class to decode Base64 streams and strings.
12  * See RFC 1521 section 5.2 for details of the Base64 algorithm.
13  *
14  * This class can be used for decoding strings:
15  *
16  * String encoded = "d2VibWFzdGVyOnRyeTJndWVTUw";
17  * String decoded = Base64Decoder.decode(encoded);
18  *
19  * or for decoding streams:
20  *
21  * InputStream in = new Base64Decoder(System.in);
22  *
23  * @author Jason Hunter, Copyright 2000
24  * @version 1.0, 2000/06/11
25  */

26 class Base64Decoder extends FilterInputStream JavaDoc {
27
28   private static final char[] chars = {
29     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
30     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
31     'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
32     'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
33     'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
34     'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
35     '8', '9', '+', '/'
36   };
37
38   // A mapping between char values and six-bit integers
39
private static final int[] ints = new int[128];
40   static {
41     for (int i = 0; i < 64; i++) {
42       ints[chars[i]] = i;
43     }
44   }
45
46   private int charCount;
47   private int carryOver;
48
49   /**
50    * Constructs a new Base64 decoder that reads input from the given
51    * InputStream.
52    *
53    * @param in the input stream
54    */

55   public Base64Decoder(InputStream JavaDoc in) {
56     super(in);
57   }
58
59   /**
60    * Returns the next decoded character from the stream, or -1 if
61    * end of stream was reached.
62    *
63    * @return the decoded character, or -1 if the end of the
64    * input stream is reached
65    * @exception IOException if an I/O error occurs
66    */

67   public int read() throws IOException JavaDoc {
68     // Read the next non-whitespace character
69
int x;
70     do {
71       x = in.read();
72       if (x == -1) {
73         return -1;
74       }
75     } while (Character.isWhitespace((char)x));
76     charCount++;
77
78     // The '=' sign is just padding
79
if (x == '=') {
80       return -1; // effective end of stream
81
}
82
83     // Convert from raw form to 6-bit form
84
x = ints[x];
85
86     // Calculate which character we're decoding now
87
int mode = (charCount - 1) % 4;
88
89     // First char save all six bits, go for another
90
if (mode == 0) {
91       carryOver = x & 63;
92       return read();
93     }
94     // Second char use previous six bits and first two new bits,
95
// save last four bits
96
else if (mode == 1) {
97       int decoded = ((carryOver << 2) + (x >> 4)) & 255;
98       carryOver = x & 15;
99       return decoded;
100     }
101     // Third char use previous four bits and first four new bits,
102
// save last two bits
103
else if (mode == 2) {
104       int decoded = ((carryOver << 4) + (x >> 2)) & 255;
105       carryOver = x & 3;
106       return decoded;
107     }
108     // Fourth char use previous two bits and all six new bits
109
else if (mode == 3) {
110       int decoded = ((carryOver << 6) + x) & 255;
111       return decoded;
112     }
113     return -1; // can't actually reach this line
114
}
115
116   /**
117    * Reads decoded data into an array of bytes and returns the actual
118    * number of bytes read, or -1 if end of stream was reached.
119    *
120    * @param buf the buffer into which the data is read
121    * @param off the start offset of the data
122    * @param len the maximum number of bytes to read
123    * @return the actual number of bytes read, or -1 if the end of the
124    * input stream is reached
125    * @exception IOException if an I/O error occurs
126    */

127   public int read(byte[] b, int off, int len) throws IOException JavaDoc {
128     // This could of course be optimized
129
int i;
130     for (i = 0; i < len; i++) {
131       int x = read();
132       if (x == -1 && i == 0) { // an immediate -1 returns -1
133
return -1;
134       }
135       else if (x == -1) { // a later -1 returns the chars read so far
136
break;
137       }
138       b[off + i] = (byte) x;
139     }
140     return i;
141   }
142
143   /**
144    * Returns the decoded form of the given encoded string.
145    *
146    * @param encoded the string to decode
147    * @return the decoded form of the encoded string
148    */

149   public static String JavaDoc decode(String JavaDoc encoded) {
150     byte[] bytes = null;
151     try {
152       bytes = encoded.getBytes("8859_1");
153     }
154     catch (UnsupportedEncodingException ignored) { }
155
156     Base64Decoder bin = new Base64Decoder(
157                        new ByteArrayInputStream(bytes));
158     
159     ByteArrayOutputStream out =
160       new ByteArrayOutputStream((int) (bytes.length * 0.67));
161
162     try {
163       byte[] buf = new byte[4 * 1024]; // 4K buffer
164
int bytesRead;
165       while ((bytesRead = bin.read(buf)) != -1) {
166         out.write(buf, 0, bytesRead);
167       }
168       out.close();
169
170       return out.toString("8859_1");
171     }
172     catch (IOException JavaDoc ignored) {
173       return null;
174     }
175   }
176
177   /*
178   public static void main(String[] args) throws Exception {
179     if (args.length != 1) {
180       System.err.println("Usage: java Base64Decoder fileToDecode");
181     }
182
183     Base64Decoder decoder = null;
184     try {
185       decoder = new Base64Decoder(
186                 new BufferedInputStream(
187                 new FileInputStream(args[0])));
188       byte[] buf = new byte[4 * 1024]; // 4K buffer
189       int bytesRead;
190       while ((bytesRead = decoder.read(buf)) != -1) {
191         System.out.write(buf, 0, bytesRead);
192       }
193     }
194     finally {
195       if (decoder != null) decoder.close();
196     }
197   }
198   */

199 }
200
Popular Tags