*
* @param body the string to decode.
* @return the decoded string.
*/
public static String decodeEncodedWords(String body) {
CharArrayBuffer sb = new CharArrayBuffer(128);
int p1 = 0;
int p2 = 0;
try {
/*
* Encoded words in headers have the form
* =?charset?enc?Encoded word?= where enc is either 'Q' or 'q' for
* quoted printable and 'B' and 'b' for Base64
*/
while (p2 < body.length()) {
/*
* Find beginning of first encoded word
*/
p1 = body.indexOf("=?", p2);
if (p1 == -1) {
/*
* None found. Emit the rest of the header and exit.
*/
sb.append(body.substring(p2));
break;
}
/*
* p2 points to the previously found end marker or the start
* of the entire header text. Append the text between that
* marker and the one pointed to by p1.
*/
if (p1 - p2 > 0) {
sb.append(body.substring(p2, p1));
}
/*
* Find the first and second '?':s after the marker pointed to
* by p1.
*/
int t1 = body.indexOf('?', p1 + 2);
int t2 = t1 != -1 ? body.indexOf('?', t1 + 1) : -1;
/*
* Find this words end marker.
*/
p2 = t2 != -1 ? body.indexOf("?=", t2 + 1) : -1;
if (p2 == -1) {
if (t2 != -1 && (body.length() - 1 == t2 || body.charAt(t2 + 1) == '=')) {
/*
* Treat "=?charset?enc?" and "=?charset?enc?=" as
* empty strings.
*/
p2 = t2;
} else {
/*
* No end marker was found. Append the rest of the
* header and exit.
*/
sb.append(body.substring(p1));
break;
}
}
/*
* [p1+2, t1] -> charset
* [t1+1, t2] -> encoding
* [t2+1, p2] -> encoded word
*/
String decodedWord = null;
if (t2 == p2) {
/*
* The text is empty
*/
decodedWord = "";
} else {
String mimeCharset = body.substring(p1 + 2, t1);
String enc = body.substring(t1 + 1, t2);
String encodedWord = body.substring(t2 + 1, p2);
/*
* Convert the MIME charset to a corresponding Java one.
*/
String charset = CharsetUtil.toJavaCharset(mimeCharset);
if (charset == null) {
decodedWord = body.substring(p1, p2 + 2);
if (log.isWarnEnabled()) {
log.warn("MIME charset '" + mimeCharset
+ "' in header field doesn't have a "
+"corresponding Java charset");
}
} else if (!CharsetUtil.isDecodingSupported(charset)) {
decodedWord = body.substring(p1, p2 + 2);
if (log.isWarnEnabled()) {
log.warn("Current JDK doesn't support decoding "
+ "of charset '" + charset
+ "' (MIME charset '"
+ mimeCharset + "')");
}
} else {
if (enc.equalsIgnoreCase("Q")) {
decodedWord = DecoderUtil.decodeQ(encodedWord, charset);
} else if (enc.equalsIgnoreCase("B")) {
decodedWord = DecoderUtil.decodeB(encodedWord, charset);
} else {
decodedWord = encodedWord;
if (log.isWarnEnabled()) {
log.warn("Warning: Unknown encoding in "
+ "header field '" + enc + "'");
}
}
}
}
p2 += 2;
sb.append(decodedWord);
}
} catch (Throwable t) {
log.error("Decoding header field body '" + body + "'", t);
}
return sb.toString();
}