1 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 { 30 public static String encode(String input, String characterEncoding, 31 String separator) 32 { 33 if (input.length() == 0) 34 return input; 35 byte[] bytes; 36 try { 37 bytes = input.getBytes(characterEncoding); 38 } 39 catch (UnsupportedEncodingException e) { 40 Log.error(e); 41 bytes = input.getBytes(); 42 } 43 FastStringBuffer sb = new FastStringBuffer(); 44 int outputLength = 0; 45 for (int i = 0; i < bytes.length; i++) { 46 byte b = bytes[i]; 47 if ((b < ' ' && b != '\t') || b == 127 || b == '=') { 48 sb.append(encode(b)); 49 outputLength += 3; 50 } else if (outputLength == 0 && b == 'F') { 51 if (i+4 < bytes.length && 52 bytes[i+1] == 'r' && 53 bytes[i+2] == 'o' && 54 bytes[i+3] == 'm' && 55 bytes[i+4] == ' ') { 56 sb.append(encode(b)); 58 outputLength += 3; 59 } else { 60 sb.append((char) (b < 0 ? b+256 : b)); 62 ++outputLength; 63 } 64 } else if (outputLength == 0 && b == '.') { 65 sb.append(encode(b)); 66 outputLength += 3; 67 } else { 68 sb.append((char) (b < 0 ? b+256 : b)); 69 ++outputLength; 70 } 71 if (outputLength >= 73) { 72 sb.append('='); 74 sb.append(separator); 75 outputLength = 0; 76 } 77 } 78 if (sb.length() > 0) { 80 char c = sb.charAt(sb.length()-1); 81 if (c == ' ' || c == '\t') { 82 sb.append('='); 83 sb.append(separator); 84 } 85 } 86 return sb.toString(); 87 } 88 89 private static String encode(byte b) 90 { 91 int n = b; 92 if (n < 0) 93 n += 256; 94 FastStringBuffer sb = new FastStringBuffer('='); 95 sb.append(Integer.toString(n, 16)); 96 return sb.toString().toUpperCase(); 97 } 98 } 99 | Popular Tags |