PageRenderTime 75ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-core/src/main/java/org/silverpeas/util/mail/MSGExtractor.java

https://github.com/SilverTeamWork/Silverpeas-Core
Java | 206 lines | 159 code | 17 blank | 30 comment | 19 complexity | 27ed54983be584e0f365e128890a8816 MD5 | raw file
Possible License(s): AGPL-3.0
  1. /*
  2. * Copyright (C) 2000 - 2013 Silverpeas
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU Affero General Public License as
  6. * published by the Free Software Foundation, either version 3 of the
  7. * License, or (at your option) any later version.
  8. *
  9. * As a special exception to the terms and conditions of version 3.0 of
  10. * the GPL, you may redistribute this Program in connection with Free/Libre
  11. * Open Source Software ("FLOSS") applications as described in Silverpeas's
  12. * FLOSS exception. You should have recieved a copy of the text describing
  13. * the FLOSS exception, and it is also available here:
  14. * "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package org.silverpeas.util.mail;
  25. import com.silverpeas.converter.DocumentFormatConverterProvider;
  26. import org.silverpeas.util.EncodeHelper;
  27. import com.stratelia.silverpeas.silvertrace.SilverTrace;
  28. import org.silverpeas.util.FileRepositoryManager;
  29. import org.silverpeas.util.exception.SilverpeasException;
  30. import java.io.ByteArrayInputStream;
  31. import java.io.ByteArrayOutputStream;
  32. import java.io.File;
  33. import java.io.IOException;
  34. import java.io.InputStream;
  35. import java.io.UnsupportedEncodingException;
  36. import java.text.ParseException;
  37. import java.text.SimpleDateFormat;
  38. import java.util.ArrayList;
  39. import java.util.Calendar;
  40. import java.util.Date;
  41. import java.util.List;
  42. import java.util.Locale;
  43. import javax.mail.Address;
  44. import javax.mail.internet.InternetAddress;
  45. import org.apache.commons.io.FileUtils;
  46. import org.apache.commons.lang3.CharEncoding;
  47. import org.apache.commons.lang3.StringUtils;
  48. import org.apache.poi.hsmf.MAPIMessage;
  49. import org.apache.poi.hsmf.datatypes.AttachmentChunks;
  50. import org.apache.poi.hsmf.datatypes.Chunks;
  51. import org.apache.poi.hsmf.datatypes.RecipientChunks;
  52. import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
  53. import org.silverpeas.util.Charsets;
  54. import static com.silverpeas.converter.DocumentFormat.*;
  55. public class MSGExtractor implements MailExtractor {
  56. private MAPIMessage message;
  57. public MSGExtractor(File file) throws ExtractorException {
  58. try {
  59. message = new MAPIMessage(file.getPath());
  60. } catch (IOException e) {
  61. throw new ExtractorException("MSGExtractor.constructor", SilverpeasException.ERROR, "", e);
  62. }
  63. message.setReturnNullOnMissingChunk(true);
  64. }
  65. public MSGExtractor(InputStream file) throws ExtractorException {
  66. init(file);
  67. }
  68. private void init(InputStream file) throws ExtractorException {
  69. try {
  70. message = new MAPIMessage(file);
  71. } catch (IOException e) {
  72. throw new ExtractorException("MSGExtractor.init", SilverpeasException.ERROR, "", e);
  73. }
  74. message.setReturnNullOnMissingChunk(true);
  75. }
  76. @Override
  77. public Mail getMail() throws Exception {
  78. Mail mail = new Mail();
  79. try {
  80. if (message.getMessageDate() != null) {
  81. mail.setDate(message.getMessageDate().getTime());
  82. } else {
  83. mail.setDate(extractDateOfReception());
  84. }
  85. } catch (ChunkNotFoundException e) {
  86. SilverTrace.warn("util", "MSGExtractor.getMail()", "", e);
  87. }
  88. try {
  89. mail.setSubject(message.getSubject());
  90. } catch (ChunkNotFoundException e) {
  91. SilverTrace.warn("util", "MSGExtractor.getMail()", "", e);
  92. }
  93. Chunks mainChunks = message.getMainChunks();
  94. InternetAddress from = new InternetAddress(mainChunks.emailFromChunk.getValue(),
  95. mainChunks.displayFromChunk.getValue());
  96. mail.setFrom(from);
  97. String[] toNames = StringUtils.split(message.getDisplayTo(), ';');
  98. mail.setTo(getInChunks(toNames).toArray(new Address[toNames.length]));
  99. String[] ccNames = StringUtils.split(message.getDisplayCC(), ';');
  100. List<InternetAddress> ccAddresses = getInChunks(ccNames);
  101. if (ccAddresses != null && !ccAddresses.isEmpty()) {
  102. mail.setCc(getInChunks(ccNames).toArray(new Address[ccNames.length]));
  103. }
  104. try {
  105. String body = message.getHtmlBody();
  106. if (body == null) {
  107. body = getRtfText(message.getRtfBody());
  108. if (body == null) {
  109. body = EncodeHelper.javaStringToHtmlParagraphe(message.getTextBody());
  110. }
  111. }
  112. mail.setBody(body);
  113. } catch (ChunkNotFoundException e) {
  114. SilverTrace.warn("util", "MSGExtractor.getMail()", "", e);
  115. }
  116. return mail;
  117. }
  118. private List<InternetAddress> getInChunks(String[] names) throws UnsupportedEncodingException {
  119. List<InternetAddress> result = new ArrayList<InternetAddress>(names.length);
  120. for (String name : names) {
  121. InternetAddress address = getInChunks(name.trim());
  122. if (address != null) {
  123. result.add(address);
  124. }
  125. }
  126. return result;
  127. }
  128. private InternetAddress getInChunks(String name) throws UnsupportedEncodingException {
  129. RecipientChunks[] recipientChunks = message.getRecipientDetailsChunks();
  130. for (RecipientChunks recipient : recipientChunks) {
  131. if (name.equals(recipient.getRecipientName())) {
  132. InternetAddress address =
  133. new InternetAddress(recipient.getRecipientEmailAddress(), recipient.getRecipientName());
  134. return address;
  135. }
  136. }
  137. return null;
  138. }
  139. private Date extractDateOfReception() throws ParseException {
  140. if (message.getMainChunks().messageHeaders != null) {
  141. String chunkContent = message.getMainChunks().messageHeaders.getValue();
  142. int dateIdx = chunkContent.indexOf("Date: ");
  143. if (dateIdx >= 0) {
  144. chunkContent = chunkContent.substring(dateIdx + 6, chunkContent.indexOf('\n', dateIdx))
  145. .replaceAll("[\r\n]", "");
  146. return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH).parse(
  147. chunkContent);
  148. }
  149. }
  150. return null;
  151. }
  152. /**
  153. * Gets readable string from RTF text.
  154. *
  155. * @param rtfText
  156. * @return
  157. * @throws Exception
  158. */
  159. private String getRtfText(String rtfText) {
  160. try {
  161. ByteArrayOutputStream htmlText = new ByteArrayOutputStream();
  162. DocumentFormatConverterProvider.getToHTMLConverter().convert(
  163. new ByteArrayInputStream(rtfText.getBytes(Charsets.UTF_8)), inFormat(rtf), htmlText,
  164. inFormat(html));
  165. return htmlText.toString(CharEncoding.UTF_8);
  166. } catch (Exception e) {
  167. SilverTrace.warn("util", "MSGExtractor.getRtfText()", "CANT_CONVERT_RTF_TO_HMTL_BODY", e);
  168. }
  169. return null;
  170. }
  171. @Override
  172. public List<MailAttachment> getAttachments() throws Exception {
  173. AttachmentChunks[] attachmentChunks = message.getAttachmentFiles();
  174. List<MailAttachment> mailAttachments = new ArrayList<MailAttachment>(attachmentChunks.length);
  175. for (AttachmentChunks attachment : attachmentChunks) {
  176. byte[] data = attachment.attachData.getValue();
  177. String fileName = attachment.attachLongFileName.getValue();
  178. MailAttachment mailAttachment = new MailAttachment(fileName);
  179. String dir = FileRepositoryManager.getTemporaryPath() + "mail" + Calendar.getInstance().
  180. getTimeInMillis();
  181. File file = new File(dir, fileName);
  182. FileUtils.writeByteArrayToFile(file, data);
  183. mailAttachment.setPath(file.getAbsolutePath());
  184. mailAttachment.setSize(file.length());
  185. mailAttachments.add(mailAttachment);
  186. }
  187. return mailAttachments;
  188. }
  189. }