01: /*
02: * QuotedPrintableDecoder.java
03: *
04: * Copyright (C) 2000-2002 Peter Graves
05: * $Id: QuotedPrintableDecoder.java,v 1.1.1.1 2002/09/24 16:10:03 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
21:
22: package org.armedbear.j.mail;
23:
24: import org.armedbear.j.ByteBuffer;
25:
26: public final class QuotedPrintableDecoder {
27: public static byte[] decode(String encoded) {
28: ByteBuffer bb = new ByteBuffer();
29: int limit = encoded.length();
30: int i = 0;
31: while (i < limit) {
32: char c = encoded.charAt(i);
33: if (c == '=') {
34: if (i + 1 < limit && encoded.charAt(i + 1) == '\n') {
35: // Soft line break.
36: i += 2;
37: continue;
38: }
39: if (i + 2 < limit) {
40: char c1 = encoded.charAt(i + 1);
41: char c2 = encoded.charAt(i + 2);
42: if (c1 == '\r' && c2 == '\n') {
43: // Soft line break.
44: i += 3;
45: continue;
46: }
47: int hi = decodeHex(c1);
48: if (hi >= 0) {
49: int lo = decodeHex(c2);
50: if (lo >= 0) {
51: byte b = (byte) ((hi << 4) + lo);
52: bb.append(b);
53: i += 3;
54: continue;
55: }
56: }
57: }
58: }
59: // Not encoded.
60: bb.append((byte) c);
61: ++i;
62: }
63: byte[] toBeReturned = new byte[bb.length()];
64: System
65: .arraycopy(bb.getBytes(), 0, toBeReturned, 0, bb
66: .length());
67: return toBeReturned;
68: }
69:
70: private static int decodeHex(char c) {
71: if (c >= '0' && c <= '9')
72: return c - '0';
73: else if (c >= 'A' && c <= 'F')
74: return c - 'A' + 10;
75: else if (c >= 'a' && c <= 'f')
76: return c - 'a' + 10;
77: // Error!
78: return -1;
79: }
80: }
|