Example usage for org.springframework.integration.mail ImapMailReceiver ImapMailReceiver

List of usage examples for org.springframework.integration.mail ImapMailReceiver ImapMailReceiver

Introduction

In this page you can find the example usage for org.springframework.integration.mail ImapMailReceiver ImapMailReceiver.

Prototype

public ImapMailReceiver(String url) 

Source Link

Usage

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

@PostConstruct
public void setupChannelAdapters() throws URISyntaxException {
    final List<DepositEmailConfiguration> depositEmailConfigurations = getConfiguration()
            .getDepositEmailAccounts();//from  www  .  j  a  v a 2 s.c o m

    if ((depositEmailConfigurations == null) || (depositEmailConfigurations.isEmpty())) {
        return;
    }

    for (final DepositEmailConfiguration depositEmailConfiguration : depositEmailConfigurations) {
        final PeriodicTrigger trigger = new PeriodicTrigger(depositEmailConfiguration.getPollingPeriod(),
                TimeUnit.MILLISECONDS);
        trigger.setInitialDelay(5000L);

        AbstractMailReceiver mailReceiver = null;

        final URI emailAccountURI = depositEmailConfiguration.getAccountURI();
        if (StringUtils.equals(emailAccountURI.getScheme(), "pop3")) {
            mailReceiver = new Pop3MailReceiver(emailAccountURI.toString());
        } else if (StringUtils.equals(emailAccountURI.getScheme(), "imap")) {
            mailReceiver = new ImapMailReceiver(emailAccountURI.toString());
            ((ImapMailReceiver) mailReceiver).setShouldMarkMessagesAsRead(true);
        } else {
            throw new IllegalArgumentException("Invalid email account URI: " + emailAccountURI);
        }

        mailReceiver.setBeanFactory(beanFactory);
        mailReceiver.setBeanName("rsb-email-ms-" + emailAccountURI.getHost() + emailAccountURI.hashCode());
        mailReceiver.setShouldDeleteMessages(true);
        mailReceiver.setMaxFetchSize(1);
        mailReceiver.afterPropertiesSet();
        final MailReceivingMessageSource fileMessageSource = new MailReceivingMessageSource(mailReceiver);
        final HeaderSettingMessageSourceWrapper<javax.mail.Message> messageSource = new HeaderSettingMessageSourceWrapper<javax.mail.Message>(
                fileMessageSource, EMAIL_CONFIG_HEADER_NAME, depositEmailConfiguration);

        final SourcePollingChannelAdapter channelAdapter = new SourcePollingChannelAdapter();
        channelAdapter.setBeanFactory(beanFactory);
        channelAdapter.setBeanName("rsb-email-ca-" + emailAccountURI.getHost() + emailAccountURI.hashCode());
        channelAdapter.setOutputChannel(emailDepositChannel);
        channelAdapter.setSource(messageSource);
        channelAdapter.setTrigger(trigger);
        channelAdapter.afterPropertiesSet();
        channelAdapter.start();

        getLogger().info("Started channel adapter: " + channelAdapter);

        channelAdapters.add(channelAdapter);
    }
}

From source file:io.lavagna.service.MailTicketService.java

private MailReceiver getImapMailReceiver(ProjectMailTicketConfigData config) {
    String sanitizedUsername = sanitizeUsername(config.getInboundUser());
    String inboxFolder = getInboxFolder(config);

    String url = config.getInboundProtocol() + "://" + sanitizedUsername + ":" + config.getInboundPassword()
            + "@" + config.getInboundServer() + ":" + config.getInboundPort() + "/" + inboxFolder.toLowerCase();

    ImapMailReceiver receiver = new ImapMailReceiver(url);
    receiver.setShouldMarkMessagesAsRead(true);
    receiver.setShouldDeleteMessages(false);

    Properties mailProperties = new Properties();
    if (config.getInboundProtocol().equals("imaps")) {
        mailProperties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        mailProperties.setProperty("mail.pop3.socketFactory.fallback", "false");
    }//from w  w w .j a  v a2  s.  c  o m
    mailProperties.setProperty("mail.store.protocol", config.getInboundProtocol());
    mailProperties.putAll(config.generateInboundProperties());
    receiver.setJavaMailProperties(mailProperties);

    receiver.afterPropertiesSet();

    return receiver;
}

From source file:org.springframework.integration.mail.config.MailReceiverFactoryBean.java

private MailReceiver createReceiver() {
    this.verifyProtocol();
    boolean isPop3 = this.protocol.toLowerCase().startsWith("pop3");
    boolean isImap = this.protocol.toLowerCase().startsWith("imap");
    Assert.isTrue(isPop3 || isImap, "the store URI must begin with 'pop3' or 'imap'");
    AbstractMailReceiver receiver = isPop3 ? new Pop3MailReceiver(this.storeUri)
            : new ImapMailReceiver(this.storeUri);
    if (this.session != null) {
        Assert.isNull(this.javaMailProperties,
                "JavaMail Properties are not allowed when a Session has been provided.");
        Assert.isNull(this.authenticator,
                "A JavaMail Authenticator is not allowed when a Session has been provied.");
        receiver.setSession(this.session);
    }/*from  w  w w .j av a  2 s. c om*/
    if (this.searchTermStrategy != null) {
        Assert.isTrue(isImap, "searchTermStrategy is only allowed with imap");
        ((ImapMailReceiver) receiver).setSearchTermStrategy(this.searchTermStrategy);
    }
    if (this.javaMailProperties != null) {
        receiver.setJavaMailProperties(this.javaMailProperties);
    }
    if (this.authenticator != null) {
        receiver.setJavaMailAuthenticator(this.authenticator);
    }
    if (this.shouldDeleteMessages != null) {
        // always set the value if configured explicitly
        // otherwise, the default is true for POP3 but false for IMAP
        receiver.setShouldDeleteMessages(this.shouldDeleteMessages);
    }
    receiver.setMaxFetchSize(this.maxFetchSize);
    receiver.setSelectorExpression(selectorExpression);

    if (isPop3) {
        if (this.isShouldMarkMessagesAsRead() && this.logger.isWarnEnabled()) {
            logger.warn("Setting 'should-mark-messages-as-read' to 'true' while using POP3 has no effect");
        }
    } else if (isImap) {
        ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(this.shouldMarkMessagesAsRead);
    }
    if (this.beanFactory != null) {
        receiver.setBeanFactory(this.beanFactory);
    }
    receiver.afterPropertiesSet();
    return receiver;
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleWithServerCustomSearch() throws Exception {
    ImapMailReceiver receiver = new ImapMailReceiver(
            "imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX");
    receiver.setSearchTermStrategy((supportedFlags, folder) -> {
        try {//from   ww w  .  j  a  v  a  2s.  c  o m
            FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz"));
            return new AndTerm(fromTerm, new FlagTerm(new Flags(Flag.SEEN), false));
        } catch (AddressException e) {
            throw new RuntimeException(e);
        }
    });
    testIdleWithServerGuts(receiver, false);
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleWithServerDefaultSearch() throws Exception {
    ImapMailReceiver receiver = new ImapMailReceiver(
            "imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX");
    testIdleWithServerGuts(receiver, false);
    assertTrue(imapIdleServer.assertReceived("searchWithUserFlag"));
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleWithMessageMapping() throws Exception {
    ImapMailReceiver receiver = new ImapMailReceiver(
            "imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX");
    receiver.setHeaderMapper(new DefaultMailHeaderMapper());
    testIdleWithServerGuts(receiver, true);
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleWithServerDefaultSearchSimple() throws Exception {
    ImapMailReceiver receiver = new ImapMailReceiver(
            "imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX");
    receiver.setSimpleContent(true);//from   w ww. j  a v a 2s  . co  m
    testIdleWithServerGuts(receiver, false, true);
    assertTrue(imapIdleServer.assertReceived("searchWithUserFlag"));
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleWithMessageMappingSimple() throws Exception {
    ImapMailReceiver receiver = new ImapMailReceiver(
            "imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX");
    receiver.setSimpleContent(true);/*from   ww w .  j  av  a 2  s. com*/
    receiver.setHeaderMapper(new DefaultMailHeaderMapper());
    testIdleWithServerGuts(receiver, true, true);
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@SuppressWarnings("resource")
@Test//from  w w w  .  j  av a2  s.  c  om
public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);

    ImapMailReceiver receiver = new ImapMailReceiver("imap:foo");
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    final IMAPFolder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    given(folder.isOpen()).willReturn(false).willReturn(true);
    given(folder.exists()).willReturn(true);

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    Field storeField = AbstractMailReceiver.class.getDeclaredField("store");
    storeField.setAccessible(true);
    Store store = mock(Store.class);
    given(store.isConnected()).willReturn(true);
    given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
    storeField.set(receiver, store);

    willAnswer(invocation -> folder).given(receiver).getFolder();

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2);
    willAnswer(invocation -> {
        /*
         * Return the message from first invocation of waitForMessages()
         * and in receive(); then return false in the next call to
         * waitForMessages() so we enter idle(); counter will be reset
         * to 1 in the mocked idle().
         */
        if (shouldFindMessagesCounter.decrementAndGet() >= 0) {
            return messages;
        } else {
            return new Message[0];
        }
    }).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    willAnswer(invocation -> {
        Thread.sleep(5000);
        shouldFindMessagesCounter.set(1);
        return null;
    }).given(folder).idle();

    adapter.start();

    /*
     * Idle takes 5 seconds; if all is well, we should receive the first message
     * before then.
     */
    assertNotNull(channel.receive(3000));
    // We should not receive any more until the next idle elapses
    assertNull(channel.receive(3000));
    assertNotNull(channel.receive(6000));
    adapter.stop();
    context.close();
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@SuppressWarnings("resource")
@Test//from   w ww .  j  av a 2s  .co m
public void testInitialIdleDelayWhenRecentIsSupported() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);

    ImapMailReceiver receiver = new ImapMailReceiver("imap:foo");
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    final IMAPFolder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.RECENT));
    given(folder.isOpen()).willReturn(false).willReturn(true);
    given(folder.exists()).willReturn(true);

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    Field storeField = AbstractMailReceiver.class.getDeclaredField("store");
    storeField.setAccessible(true);
    Store store = mock(Store.class);
    given(store.isConnected()).willReturn(true);
    given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
    storeField.set(receiver, store);

    willAnswer(invocation -> folder).given(receiver).getFolder();

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    willAnswer(invocation -> messages).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    final CountDownLatch idles = new CountDownLatch(2);
    willAnswer(invocation -> {
        idles.countDown();
        Thread.sleep(5000);
        return null;
    }).given(folder).idle();

    adapter.start();

    /*
     * Idle takes 5 seconds; since this server supports RECENT, we should
     * not receive any early messages.
     */
    assertNull(channel.receive(3000));
    assertNotNull(channel.receive(5000));
    assertTrue(idles.await(5, TimeUnit.SECONDS));
    adapter.stop();
    context.close();
}