如何将这个邮件方法拆分成两部分,而不影响其功能。

huangapple go评论96阅读模式
英文:

How to break this Mail Method in two parts without breaking its functionality

问题

以下是您的代码的翻译部分:

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.time.LocalDateTime;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Properties;
  11. import javax.mail.Address;
  12. import javax.mail.BodyPart;
  13. import javax.mail.Flags;
  14. import javax.mail.Folder;
  15. import javax.mail.Message;
  16. import javax.mail.MessagingException;
  17. import javax.mail.Part;
  18. import javax.mail.Session;
  19. import javax.mail.Store;
  20. import javax.mail.internet.ContentType;
  21. import javax.mail.internet.InternetAddress;
  22. import javax.mail.internet.MimeBodyPart;
  23. import javax.mail.internet.MimeMultipart;
  24. import javax.mail.search.ComparisonTerm;
  25. import javax.mail.search.FlagTerm;
  26. import javax.mail.search.ReceivedDateTerm;
  27. import org.springframework.beans.factory.annotation.Autowired;
  28. import org.springframework.beans.factory.annotation.Value;
  29. import org.springframework.data.domain.Example;
  30. import org.springframework.stereotype.Service;
  31. @Service
  32. public class MailServiceImpl implements MailService {
  33. @Value("${mail.host}")
  34. private String host;
  35. @Value("${mail.id}")
  36. private String mailBoxId;
  37. @Value("${mail.password}")
  38. private String password;
  39. @Value("${mail.protocol}")
  40. private String protocol;
  41. @Value("${mail.socketfactory}")
  42. private String socketfactory;
  43. @Value("${mail.fallback}")
  44. private String fallback;
  45. @Value("${mail.port}")
  46. private String port;
  47. @Value("${mail.savepath}")
  48. private String savepath;
  49. @Value("${submission.fields}")
  50. private String fields;
  51. @Value("${mail.endidentifier}")
  52. private String mailEndIdentifier;
  53. @Autowired
  54. private EmailRequestRepository emailRequestRepository;
  55. @Autowired
  56. private CoreWorkflowService coreWorkflowService;
  57. public void readFromSharedInbox() {
  58. Properties props = new Properties();
  59. props.setProperty("mail.store.protocol", protocol);
  60. props.setProperty("mail.imaps.socketFactory.class", socketfactory);
  61. props.setProperty("mail.imaps.socketFactory.fallback", fallback);
  62. props.setProperty("mail.imaps.port", port);
  63. props.setProperty("mail.imaps.socketFactory.port", port);
  64. Session session = Session.getDefaultInstance(props, null);
  65. try {
  66. Store store = session.getStore(protocol);
  67. store.connect(host, mailBoxId, password);
  68. Folder inbox = store.getFolder("INBOX");
  69. inbox.open(Folder.READ_WRITE);
  70. ReceivedDateTerm receivedDateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
  71. FlagTerm seenTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
  72. Message[] todaysMessages = inbox.search(receivedDateTerm);
  73. Message[] foundMessages = inbox.search(seenTerm, todaysMessages);
  74. List<EmailRequest> emailRequestList = new ArrayList<>();
  75. for (int i = 0; i < foundMessages.length; i++) {
  76. Message message = foundMessages[i];
  77. String subject = message.getSubject();
  78. String content = message.getContent().toString();
  79. String contentType = message.getContentType();
  80. Address[] froms = message.getFrom();
  81. String sender = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
  82. Date receiveDate = message.getReceivedDate();
  83. // store attachment file name, separated by comma
  84. StringBuilder attachFiles = new StringBuilder();
  85. if (contentType.contains("multipart")) {
  86. // content may contain attachments
  87. MimeMultipart multiPart = (MimeMultipart) message.getContent();
  88. content = getTextFromMimeMultipart(multiPart);
  89. int numberOfParts = multiPart.getCount();
  90. for (int partCount = 0; partCount < numberOfParts; partCount++) {
  91. MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
  92. if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
  93. // this part is attachment
  94. String fileName = part.getFileName();
  95. if (attachFiles.length() > 0) {
  96. attachFiles.append(",");
  97. attachFiles.append(fileName);
  98. } else {
  99. attachFiles.append(fileName);
  100. }
  101. System.out.println(fileName);
  102. }
  103. }
  104. message.writeTo(new FileOutputStream(new File(savepath + sanitizeFileName(subject) + ".eml")));
  105. }
  106. System.out.println("Content type: " + contentType);
  107. EmailRequest emailRequest = EmailRequest.builder().emailReceiveDate(receiveDate).subjectEmail(subject)
  108. .emailContent(content).fromEmail(sender).toEmail(mailBoxId).isMailProcessed(false).build();
  109. emailRequestList.add(emailRequest);
  110. }
  111. inbox.close(false);
  112. store.close();
  113. System.out.println("reading done!");
  114. emailRequestRepository.saveAll(emailRequestList);
  115. System.out.println("Email data saved successfully in the db table");
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. private String sanitizeFileName(String subject) {
  121. return subject.replaceAll("[:\\\\/*?|<>]", "_");
  122. }
  123. private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws IOException, MessagingException {
  124. int count = mimeMultipart.getCount();
  125. if (count == 0)
  126. throw new MessagingException("Multipart with no body parts not supported.");
  127. boolean multipartAlt = new ContentType(mimeMultipart.getContentType()).match("multipart/alternative");
  128. if (multipartAlt)
  129. // alternatives appear in an order of increasing
  130. // faithfulness to the original content. Customize as req'd.
  131. return getTextFromBodyPart(mimeMultipart.getBodyPart(count - 1));
  132. StringBuilder result = new StringBuilder();
  133. for (int i = 0; i < count; i++) {
  134. BodyPart bodyPart = mimeMultipart.getBodyPart(i);
  135. result.append(getTextFromBodyPart(bodyPart));
  136. }
  137. return result.toString();
  138. }
  139. private String getTextFromBodyPart(BodyPart bodyPart) throws IOException, MessagingException {
  140. String result = "";
  141. if (bodyPart.isMimeType("text/plain")) {
  142. result = (String) bodyPart.getContent();
  143. } else if (bodyPart.isMimeType("text/html")) {
  144. result = (String) bodyPart.getContent();
  145. } else if (bodyPart.getContent() instanceof MimeMultipart) {
  146. result = getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
  147. }
  148. return result;
  149. }
  150. @Override
  151. public void readMailDetailsFromDb() {
  152. EmailRequest email = new EmailRequest();
  153. email.setIsMailProcessed(false);
  154. Example<EmailRequest> whereClause = Example.of(email);
  155. List<EmailRequest> findAll = emailRequestRepository.findAll(whereClause);
  156. Map<String, Object> processVariables = null;
  157. for (EmailRequest email : findAll) {
  158. System.out.println(email.getSubjectEmail() + " : " + email.getEmailId());
  159. processVariables = EmailParserUtil.parse(fields, email.getEmailContent(), mailEndIdentifier);
  160. // workflow service
  161. try {
  162. Workflow startWorkflow = coreWorkflowService.startWorkflow(Constants.SUBMISSION_PROCESS_ID, Constants.MAIL, processVariables);
  163. startWorkflow.toString();
  164. } catch (IllegalAccessException | InvocationTargetException e) {
  165. e.printStackTrace();
  166. }
  167. // update mail
  168. email.setMailProcessedOn(LocalDateTime.now());
  169. email.setIsMailProcessed(true);
  170. emailRequestRepository.save(email);
  171. }
  172. }
  173. }

这是MailService接口

英文:

如何将这个邮件方法拆分成两部分,而不影响其功能。I have write a readFromSharedInbox() method. When I am checking the code with sonarLint i am getting this error "Refractor this method to reduce its cognitive complexity". So i want to break this method in two parts. But i am not able to do so.I am trying to create a method to read the mail from inbox.
My Code look like this

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.time.LocalDateTime;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Properties;
  11. import javax.mail.Address;
  12. import javax.mail.BodyPart;
  13. import javax.mail.Flags;
  14. import javax.mail.Folder;
  15. import javax.mail.Message;
  16. import javax.mail.MessagingException;
  17. import javax.mail.Part;
  18. import javax.mail.Session;
  19. import javax.mail.Store;
  20. import javax.mail.internet.ContentType;
  21. import javax.mail.internet.InternetAddress;
  22. import javax.mail.internet.MimeBodyPart;
  23. import javax.mail.internet.MimeMultipart;
  24. import javax.mail.search.ComparisonTerm;
  25. import javax.mail.search.FlagTerm;
  26. import javax.mail.search.ReceivedDateTerm;
  27. import org.springframework.beans.factory.annotation.Autowired;
  28. import org.springframework.beans.factory.annotation.Value;
  29. import org.springframework.data.domain.Example;
  30. import org.springframework.stereotype.Service;
  31. @Service
  32. public class MailServiceImpl implements MailService {
  33. @Value(&quot;${mail.host}&quot;)
  34. private String host;
  35. @Value(&quot;${mail.id}&quot;)
  36. private String mailBoxId;
  37. @Value(&quot;${mail.password}&quot;)
  38. private String password;
  39. @Value(&quot;${mail.protocol}&quot;)
  40. private String protocol;
  41. @Value(&quot;${mail.socketfactory}&quot;)
  42. private String socketfactory;
  43. @Value(&quot;${mail.fallback}&quot;)
  44. private String fallback;
  45. @Value(&quot;${mail.port}&quot;)
  46. private String port;
  47. @Value(&quot;${mail.savepath}&quot;)
  48. private String savepath;
  49. @Value(&quot;${submission.fields}&quot;)
  50. private String fields;
  51. @Value(&quot;${mail.endidentifier}&quot;)
  52. private String mailEndIdentifier;
  53. @Autowired
  54. private EmailRequestRepository emailRequestRepository;
  55. @Autowired
  56. private CoreWorkflowService coreWorkflowService;
  57. public void readFromSharedInbox() {
  58. Properties props = new Properties();
  59. props.setProperty(&quot;mail.store.protocol&quot;, protocol);
  60. props.setProperty(&quot;mail.imaps.socketFactory.class&quot;, socketfactory);
  61. props.setProperty(&quot;mail.imaps.socketFactory.fallback&quot;, fallback);
  62. props.setProperty(&quot;mail.imaps.port&quot;, port);
  63. props.setProperty(&quot;mail.imaps.socketFactory.port&quot;, port);
  64. Session session = Session.getDefaultInstance(props, null);
  65. try {
  66. Store store = session.getStore(protocol);
  67. store.connect(host, mailBoxId, password);
  68. Folder inbox = store.getFolder(&quot;INBOX&quot;);
  69. inbox.open(Folder.READ_WRITE);
  70. ReceivedDateTerm receivedDateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
  71. FlagTerm seenTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
  72. Message[] todaysMessages = inbox.search(receivedDateTerm);
  73. Message[] foundMessages = inbox.search(seenTerm, todaysMessages);
  74. List&lt;EmailRequest&gt; emailRequestList = new ArrayList&lt;&gt;();
  75. for (int i = 0; i &lt; foundMessages.length; i++) {
  76. Message message = foundMessages[i];
  77. String subject = message.getSubject();
  78. String content = message.getContent().toString();
  79. String contentType = message.getContentType();
  80. Address[] froms = message.getFrom();
  81. String sender = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
  82. Date recieveDate = message.getReceivedDate();
  83. // store attachment file name, separated by comma
  84. StringBuilder attachFiles=new StringBuilder();
  85. if (contentType.contains(&quot;multipart&quot;)) {
  86. // content may contain attachments
  87. MimeMultipart multiPart = (MimeMultipart) message.getContent();
  88. content = getTextFromMimeMultipart(multiPart);
  89. int numberOfParts = multiPart.getCount();
  90. for (int partCount = 0; partCount &lt; numberOfParts; partCount++) {
  91. MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
  92. if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
  93. // this part is attachment
  94. String fileName = part.getFileName();
  95. if (attachFiles.length() &gt; 0) {
  96. attachFiles.append(&quot;,&quot;);
  97. attachFiles.append(fileName);
  98. } else {
  99. attachFiles.append(fileName);
  100. }
  101. System.out.println(fileName);
  102. }
  103. }
  104. message.writeTo(new FileOutputStream(new File(savepath + sanitizeFileName(subject) + &quot;.eml&quot;)));
  105. }
  106. System.out.println(&quot;Content type: &quot; + contentType);
  107. EmailRequest emailRequest = EmailRequest.builder().emailRecieveDate(recieveDate).subjectEmail(subject)
  108. .emailContent(content).fromEmail(sender).toEmail(mailBoxId).isMailProcessed(false).build();
  109. emailRequestList.add(emailRequest);
  110. }
  111. inbox.close(false);
  112. store.close();
  113. System.out.println(&quot;reading done!&quot;);
  114. emailRequestRepository.saveAll(emailRequestList);
  115. System.out.println(&quot;Email data saved successfully in db table&quot;);
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. private String sanitizeFileName(String subject) {
  121. return subject.replaceAll(&quot;[:\\\\/*?|&lt;&gt;]&quot;, &quot;_&quot;);
  122. }
  123. private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws IOException, MessagingException {
  124. int count = mimeMultipart.getCount();
  125. if (count == 0)
  126. throw new MessagingException(&quot;Multipart with no body parts not supported.&quot;);
  127. boolean multipartAlt = new ContentType(mimeMultipart.getContentType()).match(&quot;multipart/alternative&quot;);
  128. if (multipartAlt)
  129. // alternatives appear in an order of increasing
  130. // faithfulness to the original content. Customize as req&#39;d.
  131. return getTextFromBodyPart(mimeMultipart.getBodyPart(count - 1));
  132. StringBuilder result = new StringBuilder();
  133. for (int i = 0; i &lt; count; i++) {
  134. BodyPart bodyPart = mimeMultipart.getBodyPart(i);
  135. result.append(getTextFromBodyPart(bodyPart));
  136. }
  137. return result.toString();
  138. }
  139. private String getTextFromBodyPart(BodyPart bodyPart) throws IOException, MessagingException {
  140. String result = &quot;&quot;;
  141. if (bodyPart.isMimeType(&quot;text/plain&quot;)) {
  142. result = (String) bodyPart.getContent();
  143. } else if (bodyPart.isMimeType(&quot;text/html&quot;)) {
  144. result = (String) bodyPart.getContent();
  145. } else if (bodyPart.getContent() instanceof MimeMultipart) {
  146. result = getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
  147. }
  148. return result;
  149. }
  150. @Override
  151. public void readMailDetailsFromDb() {
  152. EmailRequest email = new EmailRequest();
  153. email.setIsMailProcessed(false);
  154. Example&lt;EmailRequest&gt; whereClause = Example.of(email);
  155. List&lt;EmailRequest&gt; findAll = emailRequestRepository.findAll(whereClause);
  156. Map&lt;String, Object&gt; processVariables = null;
  157. for (EmailRequest emaeil : findAll) {
  158. System.out.println(emaeil.getSubjectEmail() + &quot; : &quot; + emaeil.getEmailId());
  159. processVariables = EmailParserUtil.parse(fields, emaeil.getEmailContent(), mailEndIdentifier);
  160. // workflow service
  161. try {
  162. Workflow startWorkflow = coreWorkflowService.startWorkflow(Constants.SUBMISSION_PROCESS_ID, Constants.MAIL, processVariables);
  163. startWorkflow.toString();
  164. } catch (IllegalAccessException | InvocationTargetException e) {
  165. e.printStackTrace();
  166. }
  167. // update mail
  168. emaeil.setMailProcessedOn(LocalDateTime.now() ) ;
  169. emaeil.setIsMailProcessed(true) ;
  170. emailRequestRepository.save(emaeil) ;
  171. }
  172. }
  173. }

This is MailService Class

  1. import java.lang.reflect.InvocationTargetException;
  2. public interface MailService {
  3. public void readFromSharedInbox();
  4. public void readMailDetailsFromDb() throws IllegalAccessException, InvocationTargetException;
  5. }

答案1

得分: 1

你可以使用你的集成开发环境(IDE)来进行这样的操作。

你选择代码的一部分,右键点击它,然后通过将代码提取到一个新的私有方法中进行重构。

例如,你可以在“for”语句上执行这个操作。

或者在“if (contentType.contains("multipart"))”部分使用一个名为“manageMultipart”的方法。

英文:

You can use your IDE for things like that.

You select a part of your code, right click on it and refactor it by extracting the code in a new private method.

For exemple, you can do this on the "for" statement.

Or the "if (contentType.contains("multipart"))" part with a manageMultipart method.

huangapple
  • 本文由 发表于 2020年7月31日 13:21:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63186190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定