MimeUtility { public static String decodeText(String text) throws UnsupportedEncodingException { if (!text.contains(ENCODED_TOKEN_MARKER)) { return text; } int offset = 0; int endOffset = text.length(); int startWhiteSpace = -1; int endWhiteSpace = -1; StringBuilder decodedText = new StringBuilder(text.length()); boolean previousTokenEncoded = false; while (offset < endOffset) { char ch = text.charAt(offset); if (LINEAR_WHITESPACE.indexOf(ch) != -1) { startWhiteSpace = offset; while (offset < endOffset) { ch = text.charAt(offset); if (LINEAR_WHITESPACE.indexOf(ch) != -1) { offset++; } else { endWhiteSpace = offset; break; } } } else { int wordStart = offset; while (offset < endOffset) { ch = text.charAt(offset); if (LINEAR_WHITESPACE.indexOf(ch) == -1) { offset++; } else { break; } } String word = text.substring(wordStart, offset); if (word.startsWith(ENCODED_TOKEN_MARKER)) { try { String decodedWord = decodeWord(word); if (!previousTokenEncoded && startWhiteSpace != -1) { decodedText.append(text.substring(startWhiteSpace, endWhiteSpace)); startWhiteSpace = -1; } previousTokenEncoded = true; decodedText.append(decodedWord); continue; } catch (ParseException e) { } } if (startWhiteSpace != -1) { decodedText.append(text.substring(startWhiteSpace, endWhiteSpace)); startWhiteSpace = -1; } previousTokenEncoded = false; decodedText.append(word); } } return decodedText.toString(); } private  MimeUtility(); static String decodeText(String text);  }
@Test(expected=UnsupportedEncodingException.class) public void decodeInvalidEncoding() throws Exception { MimeUtility.decodeText("=?invalid?B?xyz-?="); }