001: /* ========================================================================
002: * JCommon : a free general purpose class library for the Java(tm) platform
003: * ========================================================================
004: *
005: * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
006: *
007: * Project Info: http://www.jfree.org/jcommon/index.html
008: *
009: * This library is free software; you can redistribute it and/or modify it
010: * under the terms of the GNU Lesser General Public License as published by
011: * the Free Software Foundation; either version 2.1 of the License, or
012: * (at your option) any later version.
013: *
014: * This library is distributed in the hope that it will be useful, but
015: * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017: * License for more details.
018: *
019: * You should have received a copy of the GNU Lesser General Public
020: * License along with this library; if not, write to the Free Software
021: * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
022: * USA.
023: *
024: * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
025: * in the United States and other countries.]
026: *
027: * -------------------------------------
028: * AbstractElementDefinitionHandler.java
029: * -------------------------------------
030: * (C)opyright 2003-2005, by Thomas Morgner and Contributors.
031: *
032: * Original Author: Kevin Kelley <kelley@ruralnet.net> -
033: * 30718 Rd. 28, La Junta, CO, 81050 USA.
034: *
035: * $Id: Base64.java,v 1.4 2005/10/18 13:33:53 mungady Exp $
036: *
037: * Changes
038: * -------------------------
039: * 23.09.2003 : Initial version
040: *
041: */
042: package org.jfree.xml.util;
043:
044: import java.io.BufferedInputStream;
045: import java.io.BufferedOutputStream;
046: import java.io.BufferedReader;
047: import java.io.BufferedWriter;
048: import java.io.ByteArrayOutputStream;
049: import java.io.CharArrayWriter;
050: import java.io.File;
051: import java.io.FileInputStream;
052: import java.io.FileOutputStream;
053: import java.io.FileReader;
054: import java.io.FileWriter;
055: import java.io.InputStream;
056: import java.io.OutputStream;
057: import java.io.Reader;
058: import java.io.Writer;
059:
060: /**
061: * Provides encoding of raw bytes to base64-encoded characters, and
062: * decoding of base64 characters to raw bytes.
063: * date: 06 August 1998
064: * modified: 14 February 2000
065: * modified: 22 September 2000
066: *
067: * @author Kevin Kelley (kelley@ruralnet.net)
068: * @version 1.3
069: */
070: public class Base64 {
071:
072: private Base64() {
073: }
074:
075: /**
076: * returns an array of base64-encoded characters to represent the
077: * passed data array.
078: *
079: * @param data the array of bytes to encode
080: * @return base64-coded character array.
081: */
082: public static char[] encode(final byte[] data) {
083: final char[] out = new char[((data.length + 2) / 3) * 4];
084:
085: //
086: // 3 bytes encode to 4 chars. Output is always an even
087: // multiple of 4 characters.
088: //
089: for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
090: boolean quad = false;
091: boolean trip = false;
092:
093: int val = (0xFF & data[i]);
094: val <<= 8;
095: if ((i + 1) < data.length) {
096: val |= (0xFF & data[i + 1]);
097: trip = true;
098: }
099: val <<= 8;
100: if ((i + 2) < data.length) {
101: val |= (0xFF & data[i + 2]);
102: quad = true;
103: }
104: out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
105: val >>= 6;
106: out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
107: val >>= 6;
108: out[index + 1] = alphabet[val & 0x3F];
109: val >>= 6;
110: out[index + 0] = alphabet[val & 0x3F];
111: }
112: return out;
113: }
114:
115: /**
116: * Decodes a BASE-64 encoded stream to recover the original
117: * data. White space before and after will be trimmed away,
118: * but no other manipulation of the input will be performed.
119: *
120: * As of version 1.2 this method will properly handle input
121: * containing junk characters (newlines and the like) rather
122: * than throwing an error. It does this by pre-parsing the
123: * input and generating from that a count of VALID input
124: * characters.
125: *
126: * @param data the character data.
127: *
128: * @return The decoded data.
129: */
130: public static byte[] decode(final char[] data) {
131: // as our input could contain non-BASE64 data (newlines,
132: // whitespace of any sort, whatever) we must first adjust
133: // our count of USABLE data so that...
134: // (a) we don't misallocate the output array, and
135: // (b) think that we miscalculated our data length
136: // just because of extraneous throw-away junk
137:
138: int tempLen = data.length;
139: for (int ix = 0; ix < data.length; ix++) {
140: if ((data[ix] > 255) || codes[data[ix]] < 0) {
141: --tempLen; // ignore non-valid chars and padding
142: }
143: }
144: // calculate required length:
145: // -- 3 bytes for every 4 valid base64 chars
146: // -- plus 2 bytes if there are 3 extra base64 chars,
147: // or plus 1 byte if there are 2 extra.
148:
149: int len = (tempLen / 4) * 3;
150: if ((tempLen % 4) == 3) {
151: len += 2;
152: }
153: if ((tempLen % 4) == 2) {
154: len += 1;
155: }
156:
157: final byte[] out = new byte[len];
158:
159: int shift = 0; // # of excess bits stored in accum
160: int accum = 0; // excess bits
161: int index = 0;
162:
163: // we now go through the entire array (NOT using the 'tempLen' value)
164: for (int ix = 0; ix < data.length; ix++) {
165: final int value = (data[ix] > 255) ? -1 : codes[data[ix]];
166:
167: if (value >= 0) { // skip over non-code
168: accum <<= 6; // bits shift up by 6 each time thru
169: shift += 6; // loop, with new bits being put in
170: accum |= value; // at the bottom.
171: if (shift >= 8) { // whenever there are 8 or more shifted in,
172: shift -= 8; // write them out (from the top, leaving any
173: out[index++] = // excess at the bottom for next iteration.
174: (byte) ((accum >> shift) & 0xff);
175: }
176: }
177: // we will also have skipped processing a padding null byte ('=') here;
178: // these are used ONLY for padding to an even length and do not legally
179: // occur as encoded data. for this reason we can ignore the fact that
180: // no index++ operation occurs in that special case: the out[] array is
181: // initialized to all-zero bytes to start with and that works to our
182: // advantage in this combination.
183: }
184:
185: // if there is STILL something wrong we just have to throw up now!
186: if (index != out.length) {
187: throw new Error("Miscalculated data length (wrote " + index
188: + " instead of " + out.length + ")");
189: }
190:
191: return out;
192: }
193:
194: //
195: // code characters for values 0..63
196: //
197: private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
198: .toCharArray();
199:
200: //
201: // lookup table for converting base64 characters to value in range 0..63
202: //
203: private static byte[] codes = new byte[256];
204:
205: static {
206: for (int i = 0; i < 256; i++) {
207: codes[i] = -1;
208: }
209: for (int i = 'A'; i <= 'Z'; i++) {
210: codes[i] = (byte) (i - 'A');
211: }
212: for (int i = 'a'; i <= 'z'; i++) {
213: codes[i] = (byte) (26 + i - 'a');
214: }
215: for (int i = '0'; i <= '9'; i++) {
216: codes[i] = (byte) (52 + i - '0');
217: }
218: codes['+'] = 62;
219: codes['/'] = 63;
220: }
221:
222: ///////////////////////////////////////////////////
223: // remainder (main method and helper functions) is
224: // for testing purposes only, feel free to clip it.
225: ///////////////////////////////////////////////////
226:
227: /**
228: * Entry point.
229: *
230: * @param args the command line arguments.
231: */
232: public static void main(final String[] args) {
233: boolean decode = false;
234:
235: if (args.length == 0) {
236: System.out
237: .println("usage: java Base64 [-d[ecode]] filename");
238: System.exit(0);
239: }
240: for (int i = 0; i < args.length; i++) {
241: if ("-decode".equalsIgnoreCase(args[i])) {
242: decode = true;
243: } else if ("-d".equalsIgnoreCase(args[i])) {
244: decode = true;
245: }
246: }
247:
248: final String filename = args[args.length - 1];
249: final File file = new File(filename);
250: if (!file.exists()) {
251: System.out.println("Error: file '" + filename
252: + "' doesn't exist!");
253: System.exit(0);
254: }
255:
256: if (decode) {
257: final char[] encoded = readChars(file);
258: final byte[] decoded = decode(encoded);
259: writeBytes(file, decoded);
260: } else {
261: final byte[] decoded = readBytes(file);
262: final char[] encoded = encode(decoded);
263: writeChars(file, encoded);
264: }
265: }
266:
267: private static byte[] readBytes(final File file) {
268: final ByteArrayOutputStream baos = new ByteArrayOutputStream();
269: try {
270: final InputStream fis = new FileInputStream(file);
271: final InputStream is = new BufferedInputStream(fis);
272:
273: int count;
274: final byte[] buf = new byte[16384];
275: while ((count = is.read(buf)) != -1) {
276: if (count > 0) {
277: baos.write(buf, 0, count);
278: }
279: }
280: is.close();
281: } catch (Exception e) {
282: e.printStackTrace();
283: }
284:
285: return baos.toByteArray();
286: }
287:
288: private static char[] readChars(final File file) {
289: final CharArrayWriter caw = new CharArrayWriter();
290: try {
291: final Reader fr = new FileReader(file);
292: final Reader in = new BufferedReader(fr);
293: int count;
294: final char[] buf = new char[16384];
295: while ((count = in.read(buf)) != -1) {
296: if (count > 0) {
297: caw.write(buf, 0, count);
298: }
299: }
300: in.close();
301: } catch (Exception e) {
302: e.printStackTrace();
303: }
304:
305: return caw.toCharArray();
306: }
307:
308: private static void writeBytes(final File file, final byte[] data) {
309: try {
310: final OutputStream fos = new FileOutputStream(file);
311: final OutputStream os = new BufferedOutputStream(fos);
312: os.write(data);
313: os.close();
314: } catch (Exception e) {
315: e.printStackTrace();
316: }
317: }
318:
319: private static void writeChars(final File file, final char[] data) {
320: try {
321: final Writer fos = new FileWriter(file);
322: final Writer os = new BufferedWriter(fos);
323: os.write(data);
324: os.close();
325: } catch (Exception e) {
326: e.printStackTrace();
327: }
328: }
329: ///////////////////////////////////////////////////
330: // end of test code.
331: ///////////////////////////////////////////////////
332:
333: }
|