英文:
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("${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 recieveDate = 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().emailRecieveDate(recieveDate).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 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 emaeil : findAll) {
System.out.println(emaeil.getSubjectEmail() + " : " + 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论