/**
* Create a JDOM element, protecting the data with encoding if needed
*/
public static Element protectedElement(final String name, final String s) {
final Element e = new Element(name);
int badCount = 0;
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (Character.isISOControl(c) && !Character.isWhitespace(c)) {
badCount++;
}
}
if ((1.0 * badCount) / (1.0 * s.length()) > 0.1) {
e.setAttribute("encoding", "base64");
final Base64 b64 = new Base64();
e.addContent(new String(b64.encode(s.getBytes())));
} else if (badCount > 0) {
e.setAttribute("encoding", "quoted-printable");
final QuotedPrintableCodec qp = new QuotedPrintableCodec();
e.addContent(new String(qp.encode(s.getBytes())));
} else {
e.addContent(s);
}
return e;
}
protected List<_BridgeMessageContent> extractContent(Part p) throws MessagingException, IOException {
if (p.isMimeType("multipart/*")) {
log.info("Found multipart content, extracting");
List<_BridgeMessageContent> contents = new ArrayList<>();
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
contents.addAll(extractContent(mp.getBodyPart(i)));
}
return contents;
}
if (p.isMimeType("message/rfc822")) {
log.info("Found nested content, extracting");
return extractContent((Part) p.getContent());
}
String content = p.getContent().toString();
String[] encodings = p.getHeader("Content-Transfer-Encoding");
String encoding = (encodings != null && encodings.length > 0) ? encodings[0] : null;
if (StringUtils.equalsIgnoreCase("quoted-printable", encoding)) {
try {
// TODO actually extract the charset properly
// TODO read RFC to know default charset
log.info("Transfer encoding is {}, decoding", encoding);
content = new String(QuotedPrintableCodec.decodeQuotedPrintable(content.getBytes()));
} catch (DecoderException e) {
log.warn("Content transfer encoding is set to {} but enable to decode: {}", encoding, e.getMessage());
}
}
if (p.isMimeType(MimeTypeUtils.TEXT_PLAIN_VALUE)) {
log.info("Found plain text content");
return Collections.singletonList(new BridgeMessageTextContent(content, encoding));
}
if (p.isMimeType(MimeTypeUtils.TEXT_HTML_VALUE)) {
log.info("Found HTML content");
return Collections.singletonList(new BridgeMessageHtmlContent(content, encoding));
}
return Collections.emptyList();
}
private String encodcAsQuotedPrintable( String normalizedHtml )
throws EncoderException
{
return new QuotedPrintableCodec( ).encode( normalizedHtml );
}