01: /*
02: * QuotedPrintableEncoder.java
03: *
04: * Copyright (C) 2002 Peter Graves
05: * $Id: QuotedPrintableEncoder.java,v 1.1.1.1 2002/09/24 16:09:55 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 java.io.UnsupportedEncodingException;
25: import org.armedbear.j.FastStringBuffer;
26: import org.armedbear.j.Log;
27:
28: public final class QuotedPrintableEncoder {
29: public static String encode(String input, String characterEncoding,
30: String separator) {
31: if (input.length() == 0)
32: return input;
33: byte[] bytes;
34: try {
35: bytes = input.getBytes(characterEncoding);
36: } catch (UnsupportedEncodingException e) {
37: Log.error(e);
38: bytes = input.getBytes();
39: }
40: FastStringBuffer sb = new FastStringBuffer();
41: int outputLength = 0;
42: for (int i = 0; i < bytes.length; i++) {
43: byte b = bytes[i];
44: if ((b < ' ' && b != '\t') || b == 127 || b == '=') {
45: sb.append(encode(b));
46: outputLength += 3;
47: } else if (outputLength == 0 && b == 'F') {
48: if (i + 4 < bytes.length && bytes[i + 1] == 'r'
49: && bytes[i + 2] == 'o' && bytes[i + 3] == 'm'
50: && bytes[i + 4] == ' ') {
51: // Need to encode the 'F'.
52: sb.append(encode(b));
53: outputLength += 3;
54: } else {
55: // 'F' but not "From ". Don't encode it.
56: sb.append((char) (b < 0 ? b + 256 : b));
57: ++outputLength;
58: }
59: } else if (outputLength == 0 && b == '.') {
60: sb.append(encode(b));
61: outputLength += 3;
62: } else {
63: sb.append((char) (b < 0 ? b + 256 : b));
64: ++outputLength;
65: }
66: if (outputLength >= 73) {
67: // Soft line break.
68: sb.append('=');
69: sb.append(separator);
70: outputLength = 0;
71: }
72: }
73: // Check for whitespace at end of line.
74: if (sb.length() > 0) {
75: char c = sb.charAt(sb.length() - 1);
76: if (c == ' ' || c == '\t') {
77: sb.append('=');
78: sb.append(separator);
79: }
80: }
81: return sb.toString();
82: }
83:
84: private static String encode(byte b) {
85: int n = b;
86: if (n < 0)
87: n += 256;
88: FastStringBuffer sb = new FastStringBuffer('=');
89: sb.append(Integer.toString(n, 16));
90: return sb.toString().toUpperCase();
91: }
92: }
|