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

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

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

问题

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.ReceivedDateTerm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl implements MailService {

    @Value("${mail.host}")
    private String host;

    @Value("${mail.id}")
    private String mailBoxId;

    @Value("${mail.password}")
    private String password;

    @Value("${mail.protocol}")
    private String protocol;

    @Value("${mail.socketfactory}")
    private String socketfactory;

    @Value("${mail.fallback}")
    private String fallback;

    @Value("${mail.port}")
    private String port;

    @Value("${mail.savepath}")
    private String savepath;

    @Value("${submission.fields}")
    private String fields;

    @Value("${mail.endidentifier}")
    private String mailEndIdentifier;

    @Autowired
    private EmailRequestRepository emailRequestRepository;

    @Autowired
    private CoreWorkflowService coreWorkflowService;

    public void readFromSharedInbox() {    
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.socketFactory.class", socketfactory);
        props.setProperty("mail.imaps.socketFactory.fallback", fallback);
        props.setProperty("mail.imaps.port", port);
        props.setProperty("mail.imaps.socketFactory.port", port);

        Session session = Session.getDefaultInstance(props, null);
        try {
            Store store = session.getStore(protocol);
            store.connect(host, mailBoxId, password);

            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);

            ReceivedDateTerm receivedDateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
            FlagTerm seenTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message[] todaysMessages = inbox.search(receivedDateTerm);
            Message[] foundMessages = inbox.search(seenTerm, todaysMessages);

            List<EmailRequest> emailRequestList = new ArrayList<>();
            for (int i = 0; i < foundMessages.length; i++) {
                Message message = foundMessages[i];
                String subject = message.getSubject();
                String content = message.getContent().toString();
                String contentType = message.getContentType();
                Address[] froms = message.getFrom();
                String sender = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
                Date receiveDate = message.getReceivedDate();

                // store attachment file name, separated by comma
                StringBuilder attachFiles = new StringBuilder();
                if (contentType.contains("multipart")) {
                    // content may contain attachments
                    MimeMultipart multiPart = (MimeMultipart) message.getContent();
                    content = getTextFromMimeMultipart(multiPart);

                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // this part is attachment
                            String fileName = part.getFileName();
                            if (attachFiles.length() > 0) {
                                attachFiles.append(",");
                                attachFiles.append(fileName);
                            } else {
                                attachFiles.append(fileName);
                            }
                            System.out.println(fileName);
                        }
                    }
                    message.writeTo(new FileOutputStream(new File(savepath + sanitizeFileName(subject) + ".eml")));
                }
                System.out.println("Content type: " + contentType);
                EmailRequest emailRequest = EmailRequest.builder().emailReceiveDate(receiveDate).subjectEmail(subject)
                        .emailContent(content).fromEmail(sender).toEmail(mailBoxId).isMailProcessed(false).build();
                emailRequestList.add(emailRequest);
            }
            inbox.close(false);
            store.close();
            System.out.println("reading done!");
            emailRequestRepository.saveAll(emailRequestList);
            System.out.println("Email data saved successfully in the db table");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String sanitizeFileName(String subject) {
        return subject.replaceAll("[:\\\\/*?|<>]", "_");    
    }

    private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws IOException, MessagingException {

        int count = mimeMultipart.getCount();
        if (count == 0)
            throw new MessagingException("Multipart with no body parts not supported.");
        boolean multipartAlt = new ContentType(mimeMultipart.getContentType()).match("multipart/alternative");
        if (multipartAlt)
            // alternatives appear in an order of increasing
            // faithfulness to the original content. Customize as req'd.
            return getTextFromBodyPart(mimeMultipart.getBodyPart(count - 1));
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            result.append(getTextFromBodyPart(bodyPart));
        }
        return result.toString();
    }

    private String getTextFromBodyPart(BodyPart bodyPart) throws IOException, MessagingException {

        String result = "";
        if (bodyPart.isMimeType("text/plain")) {
            result = (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("text/html")) {
            result = (String) bodyPart.getContent();
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result = getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
        }
        return result;
    }

    @Override
    public void readMailDetailsFromDb() {
        EmailRequest email = new EmailRequest();
        email.setIsMailProcessed(false);
        Example<EmailRequest> whereClause = Example.of(email);
        List<EmailRequest> findAll = emailRequestRepository.findAll(whereClause);

        Map<String, Object> processVariables = null;
        for (EmailRequest email : findAll) {
            System.out.println(email.getSubjectEmail() + " : " + email.getEmailId());
            processVariables = EmailParserUtil.parse(fields, email.getEmailContent(), mailEndIdentifier);
            // workflow service
            try {
                Workflow startWorkflow = coreWorkflowService.startWorkflow(Constants.SUBMISSION_PROCESS_ID, Constants.MAIL, processVariables);
                startWorkflow.toString();
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }

            // update mail
            email.setMailProcessedOn(LocalDateTime.now());
            email.setIsMailProcessed(true);
            emailRequestRepository.save(email);
        }
    }

}

这是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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.ReceivedDateTerm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
@Service
public class MailServiceImpl implements MailService {
@Value(&quot;${mail.host}&quot;)
private String host;
@Value(&quot;${mail.id}&quot;)
private String mailBoxId;
@Value(&quot;${mail.password}&quot;)
private String password;
@Value(&quot;${mail.protocol}&quot;)
private String protocol;
@Value(&quot;${mail.socketfactory}&quot;)
private String socketfactory;
@Value(&quot;${mail.fallback}&quot;)
private String fallback;
@Value(&quot;${mail.port}&quot;)
private String port;
@Value(&quot;${mail.savepath}&quot;)
private String savepath;
@Value(&quot;${submission.fields}&quot;)
private String fields;
@Value(&quot;${mail.endidentifier}&quot;)
private String mailEndIdentifier;
@Autowired
private EmailRequestRepository emailRequestRepository;
@Autowired
private CoreWorkflowService coreWorkflowService;
public void readFromSharedInbox() {	
Properties props = new Properties();
props.setProperty(&quot;mail.store.protocol&quot;, protocol);
props.setProperty(&quot;mail.imaps.socketFactory.class&quot;, socketfactory);
props.setProperty(&quot;mail.imaps.socketFactory.fallback&quot;, fallback);
props.setProperty(&quot;mail.imaps.port&quot;, port);
props.setProperty(&quot;mail.imaps.socketFactory.port&quot;, port);
Session session = Session.getDefaultInstance(props, null);
try {
Store store = session.getStore(protocol);
store.connect(host, mailBoxId, password);
Folder inbox = store.getFolder(&quot;INBOX&quot;);
inbox.open(Folder.READ_WRITE);
ReceivedDateTerm receivedDateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
FlagTerm seenTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] todaysMessages = inbox.search(receivedDateTerm);
Message[] foundMessages = inbox.search(seenTerm, todaysMessages);
List&lt;EmailRequest&gt; emailRequestList = new ArrayList&lt;&gt;();
for (int i = 0; i &lt; foundMessages.length; i++) {
Message message = foundMessages[i];
String subject = message.getSubject();
String content = message.getContent().toString();
String contentType = message.getContentType();
Address[] froms = message.getFrom();
String sender = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
Date recieveDate = message.getReceivedDate();
// store attachment file name, separated by comma
StringBuilder attachFiles=new StringBuilder();
if (contentType.contains(&quot;multipart&quot;)) {
// content may contain attachments
MimeMultipart multiPart = (MimeMultipart) message.getContent();
content = getTextFromMimeMultipart(multiPart);
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount &lt; numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
if (attachFiles.length() &gt; 0) {
attachFiles.append(&quot;,&quot;);
attachFiles.append(fileName);
} else {
attachFiles.append(fileName);
}
System.out.println(fileName);
}
}
message.writeTo(new FileOutputStream(new File(savepath + sanitizeFileName(subject) + &quot;.eml&quot;)));
}
System.out.println(&quot;Content type: &quot; + contentType);
EmailRequest emailRequest = EmailRequest.builder().emailRecieveDate(recieveDate).subjectEmail(subject)
.emailContent(content).fromEmail(sender).toEmail(mailBoxId).isMailProcessed(false).build();
emailRequestList.add(emailRequest);
}
inbox.close(false);
store.close();
System.out.println(&quot;reading done!&quot;);
emailRequestRepository.saveAll(emailRequestList);
System.out.println(&quot;Email data saved successfully in db table&quot;);
} catch (Exception e) {
e.printStackTrace();
}
}
private String sanitizeFileName(String subject) {
return subject.replaceAll(&quot;[:\\\\/*?|&lt;&gt;]&quot;, &quot;_&quot;);	
}
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws IOException, MessagingException {
int count = mimeMultipart.getCount();
if (count == 0)
throw new MessagingException(&quot;Multipart with no body parts not supported.&quot;);
boolean multipartAlt = new ContentType(mimeMultipart.getContentType()).match(&quot;multipart/alternative&quot;);
if (multipartAlt)
// alternatives appear in an order of increasing
// faithfulness to the original content. Customize as req&#39;d.
return getTextFromBodyPart(mimeMultipart.getBodyPart(count - 1));
StringBuilder result = new StringBuilder();
for (int i = 0; i &lt; count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
result.append(getTextFromBodyPart(bodyPart));
}
return result.toString();
}
private String getTextFromBodyPart(BodyPart bodyPart) throws IOException, MessagingException {
String result = &quot;&quot;;
if (bodyPart.isMimeType(&quot;text/plain&quot;)) {
result = (String) bodyPart.getContent();
} else if (bodyPart.isMimeType(&quot;text/html&quot;)) {
result = (String) bodyPart.getContent();
} else if (bodyPart.getContent() instanceof MimeMultipart) {
result = getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
}
return result;
}
@Override
public void readMailDetailsFromDb() {
EmailRequest email = new EmailRequest();
email.setIsMailProcessed(false);
Example&lt;EmailRequest&gt; whereClause = Example.of(email);
List&lt;EmailRequest&gt; findAll = emailRequestRepository.findAll(whereClause);
Map&lt;String, Object&gt; processVariables = null;
for (EmailRequest emaeil : findAll) {
System.out.println(emaeil.getSubjectEmail() + &quot; : &quot; + emaeil.getEmailId());
processVariables = EmailParserUtil.parse(fields, emaeil.getEmailContent(), mailEndIdentifier);
// workflow service
try {
Workflow startWorkflow = coreWorkflowService.startWorkflow(Constants.SUBMISSION_PROCESS_ID, Constants.MAIL, processVariables);
startWorkflow.toString();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
// update mail
emaeil.setMailProcessedOn(LocalDateTime.now() )  ;
emaeil.setIsMailProcessed(true)  ;
emailRequestRepository.save(emaeil) ;
}
}
}

This is MailService Class

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

答案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:

确定