1 21 22 package org.armedbear.j.mail; 23 24 import gnu.regexp.RE; 25 import gnu.regexp.REMatch; 26 import gnu.regexp.UncheckedRE; 27 import java.io.UnsupportedEncodingException ; 28 import org.armedbear.j.FastStringBuffer; 29 import org.armedbear.j.Log; 30 import org.armedbear.j.Utilities; 31 32 public final class RFC2047 33 { 34 private static final RE prefixRE = new UncheckedRE("=\\?[^?]+\\?[bq]\\?"); 35 36 public static String decode(String encoded) 37 { 38 if (encoded == null) 39 return null; 40 if (encoded.indexOf("=?") < 0) 42 return encoded; 43 REMatch match = prefixRE.getMatch(encoded.toLowerCase()); 44 if (match == null) { 45 Log.error("RFC2047.decode prefix is null"); 46 Log.error("encoded = |" + encoded + "|"); 47 return encoded; 48 } 49 String prefix = match.toString(); 50 int index = match.getStartIndex(); 51 String charset = prefix.substring(2, prefix.length()-3); 52 String encoding = Utilities.getEncodingFromCharset(charset); 53 FastStringBuffer sb = new FastStringBuffer(); 54 sb.append(encoded.substring(0, index)); 55 String remaining = encoded.substring(index); 56 while (true) { 57 int begin = prefix.length(); 58 int end = remaining.indexOf("?=", begin); 59 if (end < 0) { 60 sb.append(remaining); 62 Log.error("RFC2047.decode error"); 63 Log.error("encoded = |" + encoded + "|"); 64 Log.error("remaining = |" + remaining + "|"); 65 return sb.toString(); 66 } 67 byte[] bytes = null; 68 if (prefix.endsWith("?b?")) 69 bytes = Base64Decoder.decode(remaining.substring(begin, end)); 70 else if (prefix.endsWith("?q?")) 71 bytes = QuotedPrintableDecoder.decode(remaining.substring(begin, end)); 72 if (bytes == null) { 73 Log.error("RFC2047.decode error"); 74 Log.error("encoded = |" + encoded + "|"); 75 return encoded; 76 } 77 try { 78 sb.append(new String (bytes, encoding)); 79 } 80 catch (UnsupportedEncodingException e) { 81 Log.error(e); 82 return encoded; 83 } 84 remaining = remaining.substring(end+2); 85 index = remaining.toLowerCase().indexOf(prefix); 86 if (index < 0) { 87 sb.append(remaining); 88 break; 89 } 90 sb.append(remaining.substring(0, index)); 91 remaining = remaining.substring(index); 92 } 93 return sb.toString(); 94 } 95 } 96 | Popular Tags |