0
votes

I'm using spring boot 2.2.4-RELEASE and spring integration 5.2.3 and I'm using the IntegrationFlow and DSL because I need to configure several IMAP servers.

So I wrote this code:

String flowId = MAIL_IN_FLOW_ID_PREFIX+cpd.getIndirizzoMail();
if( flowContext.getRegistrationById(flowId) != null ) {
    flowContext.remove(flowId);
}
ImapIdleChannelAdapterSpec imapIdleChannelAdapterSpec = Mail.imapIdleAdapter(connectionUrl.toString())
    .javaMailProperties(javaMailProperties)
    .shouldDeleteMessages(deleteMessages)
    .shouldMarkMessagesAsRead(markMessagesRead)
    .autoStartup(true)
    .autoCloseFolder(false)
    .id(confMailIn.getHost()+"_adapter")
    .selector(selectFunction);
IntegrationFlow flowIdle = IntegrationFlows.from(imapIdleChannelAdapterSpec)
    .handle(msgHandler)
    .get();
flowContext.registration(flowIdle).id(flowId).register();

where msgHandler is

@Component
public class MailMessageHandler implements MessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(MailMessageHandler.class.getName());
    @Autowired
    private IConfigCasPostaleSvc ccps;
    @Autowired
    private IGestioneMailSvc gestioneMailSvc;
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        MimeMessage mimeMessage = (MimeMessage) message.getPayload();
        if( logger.isDebugEnabled() ) {

            try {
                mimeMessage.getAllHeaders().asIterator().forEachRemaining(header->{
                    logger.debug("Header name {} header value {}", header.getName(), header.getValue());
                });
            } catch (javax.mail.MessagingException e) {
                logger.error("Errore nella lettura degli header", e);
            }
        }
        try {
            //Recupero i dati del messaggio
            MimeMessageParser parser = new MimeMessageParser(mimeMessage);
            parser = parser.parse();
            String mailId = mimeMessage.getMessageID();
            String oggettoMail = parser.getSubject();
            Date receivedDate = mimeMessage.getReceivedDate();
            List<DataSource> allegatiMail = parser.getAttachmentList();

            String corpoMail = parser.getHtmlContent();
            if( !StringUtils.hasText(corpoMail) ) {
                if( logger.isDebugEnabled() ) {
                    logger.debug("Nessun contenuto HTML nella mail; recupero il contenuto plain/text");
                }
                corpoMail = parser.getPlainContent();
            }
            MailInDto datiMail = new MailInDto();
            datiMail.setAllegatiMail(allegatiMail);
            datiMail.setIdMail(mailId);
            datiMail.setOggettoMail(oggettoMail);
            datiMail.setDataRicezioneMail(receivedDate);
            datiMail.setAllegatiMail(allegatiMail);
            datiMail.setCorpoMail(corpoMail);
            List<Address> destinatari = parser.getTo();
            for (Address to:destinatari) {

                String destinatario = to.toString();
                if( to instanceof InternetAddress ){
                    destinatario = ((InternetAddress)to).getAddress();
                }
                //Considero solo i destinatari che sono censiti nelle nostre tabelle
                Optional<ConfigurazioneCasellaPostaleDto> configurazioneCasellaPostale = ccps.getConfigurazioneCasellaPostale(destinatario);
                if( configurazioneCasellaPostale.isPresent() ) {
                    ConfigurazioneCasellaPostaleDto ccpd = configurazioneCasellaPostale.get();
                    //Indico l'UUID del documentale che contiene tutti i messaggi mail della casella postale
                    datiMail.setParentIdFolder(ccpd.getCasellaPostale().getIdFolderDocumentale());
                    //Posso salvare
                    datiMail.setIdCasellaPostale(ccpd.getCasellaPostale().getPk());
                    this.gestioneMailSvc.storeReceivedMail(datiMail, parser);
                }else {
                    if( logger.isDebugEnabled() ) {
                        logger.debug("Nessuna configurazione casella postale trovata per il destinatario {}", destinatario);
                    }
                }
            }
        }catch (Exception e) {

            throw new MessagingException("Errore nella gestione del messaggio "+message, e); 
        }
    }
}

By setting .autoCloseFolder(false) I'm able in handling the MimeMessage in the handler component but I have some questions.

  1. By the documentation when I use .autoCloseFolder(false) I read:

When configured to false, the folder is not closed automatically after a fetch. It is the target application's responsibility to close it using the IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE header from the message produced by this channel adapter.

I can't figure if and what I should do in order to tell the framework to close the folder

  1. Sometimes I get the error folder closed exception. I can't understand the reason
  2. I'm not sure if by using a singleton component as msgHandler I'm doing the right thing. Sure I have all local variables and I always make query to DB but I'm wondering if this is a correct approach

May anybody give me any suggestion?

Thank you

Angelo

EDIT -- STACKTRACE

Here there is the closed folder stacktrace

2020-02-11 18:40:01,688 206505 [task-scheduler-2] WARN o.s.i.mail.ImapIdleChannelAdapter - Failed to execute IDLE task. Will attempt to resubmit in 10000 milliseconds. java.lang.IllegalStateException: Failure in 'idle' task. Will resubmit. at org.springframework.integration.mail.ImapIdleChannelAdapter$IdleTask.run(ImapIdleChannelAdapter.java:295) at org.springframework.integration.mail.ImapIdleChannelAdapter$ReceivingTask.run(ImapIdleChannelAdapter.java:249) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:830) Caused by: javax.mail.MessagingException: Folder is closed at org.springframework.integration.mail.ImapMailReceiver.searchForNewMessages(ImapMailReceiver.java:226) at org.springframework.integration.mail.ImapMailReceiver.waitForNewMessages(ImapMailReceiver.java:189) at org.springframework.integration.mail.ImapIdleChannelAdapter$IdleTask.run(ImapIdleChannelAdapter.java:277) ... 10 common frames omitted

1

1 Answers

0
votes

I think you get "folder closed exception" when you call that flowContext.remove(flowId);, but there is yet some process in your MailMessageHandler trying to read MimeMessage.

To close the folder manually you need to get access to the StaticMessageHeaderAccessor.getCloseableResource(message) and call its close().