KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > w3c > tools > codec > Base64Encoder


1 /*
2  * Copyright © World Wide Web Consortium, (Massachusetts Institute of Technology,
3  * Institut National de Recherche en Informatique et en Automatique, Keio University).
4  * All Rights Reserved. http://www.w3.org/Consortium/Legal/
5  */

6 package org.w3c.tools.codec;
7
8 import java.io.ByteArrayInputStream JavaDoc;
9 import java.io.ByteArrayOutputStream JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.io.OutputStream JavaDoc;
13 import java.io.UnsupportedEncodingException JavaDoc;
14
15 /**
16  * BASE64 encoder implementation.
17  * This object takes as parameter an input stream and an output stream. It
18  * encodes the input stream, using the BASE64 encoding rules, as defined
19  * in <a HREF="http://ds.internic.net/rfc/rfc1521.txt">MIME specification</a>
20  * and emit the resulting data to the output stream.
21  * @see org.w3c.tools.codec.Base64Decoder
22  */

23 public class Base64Encoder
24 {
25     private static final int BUFFER_SIZE = 1024;
26     private static byte encoding[] =
27         {
28             (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', // 0-7
29
(byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', // 8-15
30
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', // 16-23
31
(byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', // 24-31
32
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', // 32-39
33
(byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', // 40-47
34
(byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', // 48-55
35
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/', // 56-63
36
(byte) '=' // 64
37
};
38
39     InputStream JavaDoc in = null;
40     OutputStream JavaDoc out = null;
41     boolean stringp = false;
42
43     private final int get1(byte buf[], int off)
44     {
45         return (buf[off] & 0xfc) >> 2;
46     }
47
48     private final int get2(byte buf[], int off)
49     {
50         return ((buf[off] & 0x3) << 4) | ((buf[off + 1] & 0xf0) >>> 4);
51     }
52
53     private final int get3(byte buf[], int off)
54     {
55         return ((buf[off + 1] & 0x0f) << 2) | ((buf[off + 2] & 0xc0) >>> 6);
56     }
57
58     private static final int get4(byte buf[], int off)
59     {
60         return buf[off + 2] & 0x3f;
61     }
62
63     /**
64      * Process the data: encode the input stream to the output stream.
65      * This method runs through the input stream, encoding it to the output
66      * stream.
67      * @exception IOException If we weren't able to access the input stream or
68      * the output stream.
69      */

70     public void process() throws IOException JavaDoc
71     {
72         byte buffer[] = new byte[BUFFER_SIZE];
73         int got = -1;
74         int off = 0;
75         int count = 0;
76         while ((got = in.read(buffer, off, BUFFER_SIZE - off)) > 0)
77         {
78             if (got >= 3)
79             {
80                 got += off;
81                 off = 0;
82                 while (off + 3 <= got)
83                 {
84                     int c1 = get1(buffer, off);
85                     int c2 = get2(buffer, off);
86                     int c3 = get3(buffer, off);
87                     int c4 = get4(buffer, off);
88                     switch (count)
89                     {
90                         case 73 :
91                             out.write(encoding[c1]);
92                             out.write(encoding[c2]);
93                             out.write(encoding[c3]);
94                             out.write('\n');
95                             out.write(encoding[c4]);
96                             count = 1;
97                             break;
98                         case 74 :
99                             out.write(encoding[c1]);
100                             out.write(encoding[c2]);
101                             out.write('\n');
102                             out.write(encoding[c3]);
103                             out.write(encoding[c4]);
104                             count = 2;
105                             break;
106                         case 75 :
107                             out.write(encoding[c1]);
108                             out.write('\n');
109                             out.write(encoding[c2]);
110                             out.write(encoding[c3]);
111                             out.write(encoding[c4]);
112                             count = 3;
113                             break;
114                         case 76 :
115                             out.write('\n');
116                             out.write(encoding[c1]);
117                             out.write(encoding[c2]);
118                             out.write(encoding[c3]);
119                             out.write(encoding[c4]);
120                             count = 4;
121                             break;
122                         default :
123                             out.write(encoding[c1]);
124                             out.write(encoding[c2]);
125                             out.write(encoding[c3]);
126                             out.write(encoding[c4]);
127                             count += 4;
128                             break;
129                     }
130                     off += 3;
131                 }
132                 // Copy remaining bytes to beginning of buffer:
133
for (int i = 0; i < 3; i++)
134                     buffer[i] = (i < got - off) ? buffer[off + i] : ((byte) 0);
135                 off = got - off;
136             }
137             else
138             {
139                 // Total read amount is less then 3 bytes:
140
off += got;
141             }
142         }
143         // Manage the last bytes, from 0 to off:
144
switch (off)
145         {
146             case 1 :
147                 out.write(encoding[get1(buffer, 0)]);
148                 out.write(encoding[get2(buffer, 0)]);
149                 out.write('=');
150                 out.write('=');
151                 break;
152             case 2 :
153                 out.write(encoding[get1(buffer, 0)]);
154                 out.write(encoding[get2(buffer, 0)]);
155                 out.write(encoding[get3(buffer, 0)]);
156                 out.write('=');
157         }
158         return;
159     }
160
161     /**
162      * Encode the content of this encoder, as a string.
163      * This methods encode the String content, that was provided at creation
164      * time, following the BASE64 rules, as specified in the rfc1521.
165      * @return A String, reprenting the encoded content of the input String.
166      */

167     public String JavaDoc processString()
168     {
169         if (!stringp)
170             throw new RuntimeException JavaDoc(
171                 this.getClass().getName()
172                     + "[processString]"
173                     + "invalid call (not a String)");
174         try
175         {
176             process();
177         }
178         catch (IOException JavaDoc e)
179         {
180         }
181         return ((ByteArrayOutputStream JavaDoc) out).toString();
182     }
183
184     /**
185      * Create a new Base64 encoder, to encode the given string.
186      * @param input The String to be encoded.
187      */

188     public Base64Encoder(String JavaDoc input)
189     {
190         byte bytes[];
191         try
192         {
193             bytes = input.getBytes("ISO-8859-1");
194         }
195         catch (UnsupportedEncodingException JavaDoc ex)
196         {
197             throw new RuntimeException JavaDoc(
198                 this.getClass().getName()
199                     + "[Constructor] Unable to convert"
200                     + "properly char to bytes");
201         }
202         this.stringp = true;
203         this.in = new ByteArrayInputStream JavaDoc(bytes);
204         this.out = new ByteArrayOutputStream JavaDoc();
205     }
206
207     /**
208      * Create a new Base64 encoder, encoding input to output.
209      * @param in The input stream to be encoded.
210      * @param out The output stream, to write encoded data to.
211      */

212     public Base64Encoder(InputStream JavaDoc in, OutputStream JavaDoc out)
213     {
214         this.in = in;
215         this.out = out;
216         this.stringp = false;
217     }
218
219     /**
220      * Testing the encoder.
221      * Run with one argument, prints the encoded version of it.
222      */

223     public static void main(String JavaDoc args[])
224     {
225         if (args.length != 1)
226         {
227             System.out.println("Base64Encoder <string>");
228             System.exit(0);
229         }
230         Base64Encoder b = new Base64Encoder(args[0]);
231         System.out.println("[" + b.processString() + "]");
232         // joe:eoj -> am9lOmVvag==
233
// 12345678:87654321 -> MTIzNDU2Nzg6ODc2NTQzMjE=
234
}
235 }
236
Popular Tags