Example usage for javax.mail Folder isOpen

List of usage examples for javax.mail Folder isOpen

Introduction

In this page you can find the example usage for javax.mail Folder isOpen.

Prototype

public abstract boolean isOpen();

Source Link

Document

Indicates whether this Folder is in the 'open' state.

Usage

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

public void getMessage(cfImapConnection imapConnection, String rootFolder, long messageID, String _attachURI,
        String _attachDIR) throws cfmRunTimeException {
    try {/* ww w  .jav  a  2 s.co m*/
        Folder folderToList;

        if (rootFolder == null || rootFolder.length() == 0)
            folderToList = imapConnection.mailStore.getDefaultFolder();
        else
            folderToList = imapConnection.mailStore.getFolder(rootFolder);

        if ((folderToList.getType() & Folder.HOLDS_MESSAGES) != 0) {

            if (!folderToList.isOpen())
                folderToList.open(Folder.READ_ONLY);

            boolean bResult = false;
            if (folderToList instanceof UIDFolder)
                bResult = extractMessage(((UIDFolder) folderToList).getMessageByUID(messageID), messageID,
                        _attachURI, _attachDIR);
            else
                bResult = extractMessage(folderToList.getMessage((int) messageID), messageID, _attachURI,
                        _attachDIR);

            if (!bResult)
                imapConnection.setStatus(false, "Message does not exist");
            else
                imapConnection.setStatus(true, "");

            folderToList.close(false);
        }

    } catch (Exception E) {
        imapConnection.setStatus(false, E.getMessage());
    }
}

From source file:com.ikon.util.MailUtils.java

/**
 * Test IMAP connection//from   w w  w.j  av  a2  s . co  m
 */
public static void testConnection(MailAccount ma) throws IOException {
    log.debug("testConnection({})", ma);
    Session session = Session.getDefaultInstance(getProperties());
    Store store = null;
    Folder folder = null;

    try {
        store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());
        folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        folder.close(false);
    } catch (NoSuchProviderException e) {
        throw new IOException(e.getMessage());
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        // Try to close folder
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }

        // Try to close store
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }
    }

    log.debug("testConnection: void");
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Moves given {@link GmailMessage}'s to {@link ImapGmailLabel.TRASH} folder.
 *
 * @param gmailMessages {@link GmailMessage} message(s)
 * @throws GmailException if unable to move {@link GmailMessage}'s to
 * the Trash Folder/*from w ww.j  a va2 s  .  co m*/
 */
public void moveToTrash(final GmailMessage[] gmailMessages) {
    if (gmailMessages == null || gmailMessages.length <= 0) {
        LOG.warn("ImapGmailClient requires GmailMessage(s) to move" + " to move messages to trash folder");
        return;
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        List<Message> markedMsgList = new ArrayList<Message>();
        for (GmailMessage gmailMessage : gmailMessages) {
            // get only messages that match to the specified message number
            Message message = folder.getMessage(gmailMessage.getMessageNumber());
            message.setFlag(Flags.Flag.SEEN, true);
            // mark message as delete
            message.setFlag(Flags.Flag.DELETED, true);
            markedMsgList.add(message);
        }

        Folder trash = getFolder(ImapGmailLabel.TRASH.getName(), store);
        if (folder.getURLName().equals(trash.getURLName())) {
            LOG.warn("ImapGmailClient trying to move GmailMessage(s) within"
                    + " same folder(ImapGmailLabel.TRASH.getName())");
        }
        // move the marked messages to trash folder
        if (!markedMsgList.isEmpty()) {
            folder.copyMessages(markedMsgList.toArray(new Message[0]), trash);
        }
    } catch (Exception e) {
        throw new GmailException("ImapGmailClient failed moving GmailMessage(s)" + " to trash folder: " + e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public Folder openFolder(Folder jxFolder) throws MailException {
    try {//from w ww .jav a  2  s.com
        if (jxFolder.isOpen()) {
            return jxFolder;
        }

        jxFolder.open(Folder.READ_WRITE);

        return jxFolder;
    } catch (MessagingException me) {
        throw new MailException(me);
    }
}

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

@Test
public void testNullMessages() throws Exception {
    Message message1 = mock(Message.class);
    Message message2 = mock(Message.class);
    final Message[] messages1 = new Message[] { null, null, message1 };
    final Message[] messages2 = new Message[] { message2 };
    final SearchTermStrategy searchTermStrategy = mock(SearchTermStrategy.class);
    class TestReceiver extends ImapMailReceiver {

        private boolean firstDone;

        TestReceiver() {/*from   ww  w  .  j  ava2  s . com*/
            setSearchTermStrategy(searchTermStrategy);
        }

        @Override
        protected Folder getFolder() {
            Folder folder = mock(Folder.class);
            given(folder.isOpen()).willReturn(true);
            try {
                given(folder.getMessages()).willReturn(!this.firstDone ? messages1 : messages2);
            } catch (MessagingException e) {
            }
            return folder;
        }

        @Override
        public Message[] receive() throws MessagingException {
            Message[] messages = searchForNewMessages();
            this.firstDone = true;
            return messages;
        }

    }
    ImapMailReceiver receiver = new TestReceiver();
    Message[] received = (Message[]) receiver.receive();
    assertEquals(1, received.length);
    assertSame(message1, received[0]);
    received = (Message[]) receiver.receive();
    assertEquals(1, received.length);
    assertSame(messages2, received);
    assertSame(message2, received[0]);
}

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

private Folder testAttachmentsGuts(final ImapMailReceiver receiver) throws MessagingException, IOException {
    Store store = mock(Store.class);
    Folder folder = mock(Folder.class);
    given(folder.exists()).willReturn(true);
    given(folder.isOpen()).willReturn(true);

    Message message = new MimeMessage(null, new ClassPathResource("test.mail").getInputStream());
    given(folder.search((SearchTerm) Mockito.any())).willReturn(new Message[] { message });
    given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    DirectFieldAccessor df = new DirectFieldAccessor(receiver);
    df.setPropertyValue("store", store);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();/*from   w  ww.j ava  2 s .c  o  m*/

    return folder;
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void closeFolder(Folder jxFolder, boolean expunge) throws MailException {

    try {//from  w ww .  j ava  2  s .c o  m
        if ((jxFolder == null) || !jxFolder.isOpen()) {
            return;
        }

        if (expunge) {
            jxFolder.expunge();
        }

        jxFolder.close(expunge);
    } catch (MessagingException me) {
        throw new MailException(me);
    }
}

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

@Test // see INT-1801
public void testImapLifecycleForRaceCondition() throws Exception {

    for (int i = 0; i < 1000; i++) {
        final ImapMailReceiver receiver = new ImapMailReceiver("imap://foo");
        Store store = mock(Store.class);
        Folder folder = mock(Folder.class);
        given(folder.exists()).willReturn(true);
        given(folder.isOpen()).willReturn(true);
        given(folder.search((SearchTerm) Mockito.any())).willReturn(new Message[] {});
        given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
        given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));

        DirectFieldAccessor df = new DirectFieldAccessor(receiver);
        df.setPropertyValue("store", store);
        receiver.setBeanFactory(mock(BeanFactory.class));
        receiver.afterPropertiesSet();/*from www  .ja  v a2 s . c o m*/

        new Thread(() -> {
            try {
                receiver.receive();
            } catch (javax.mail.MessagingException e) {
                if (e.getCause() instanceof NullPointerException) {
                    failed.getAndIncrement();
                }
            }

        }).start();

        new Thread(() -> {
            try {
                receiver.destroy();
            } catch (Exception ignore) {
                // ignore
            }
        }).start();
    }
    assertEquals(0, failed.get());
}

From source file:org.nuxeo.cm.event.MailInjectionListener.java

public void handleEvent(Event event) throws ClientException {
    MailService mailService = Framework.getService(MailService.class);
    MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE);

    Visitor visitor = new Visitor(pipe);
    Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

    Folder rootFolder = null;

    try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) {
        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();
        initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session);
        initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY,
                Framework.getService(MimetypeRegistry.class));
        initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY,
                Framework.getService(CaseDistributionService.class));

        // open store
        Store store = mailService.getConnectedStore(IMPORT_MAILBOX);
        rootFolder = store.getFolder(INBOX);
        rootFolder.open(Folder.READ_WRITE);
        Flags flags = new Flags();
        flags.add(Flag.SEEN);/*from www  .  j  a va  2  s.c  o  m*/
        SearchTerm term = new FlagTerm(flags, false);
        Message[] unreadMessages = rootFolder.search(term);

        // perform import
        visitor.visit(unreadMessages, initialExecutionContext);

        // save session
        session.save();

        if (rootFolder.isOpen()) {
            try {
                rootFolder.close(true);
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
            }
        }
    } catch (MessagingException e) {
        log.error(e, e);
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *//* w  w w . j  a va 2  s. com*/
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}