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:net.wastl.webmail.server.WebMailSession.java

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent./* w ww.j a  v  a2  s.  c o m*/
 *
 * N.b. this method does not necessarily create a new XML Folder Element.
 * If called with subscribed_only and the target Folder (and in some
 * cases its descendants) are not subscribed, no Element will be created
 * and 0 will be returned.
 * <P>
 * Pop servers don't support nesting at all, so you'll just get a single
 * level out of this method.
 * <P>
 * There is a critical subscribed_only difference in behavior between
 * Maildir and mbox type mail servers.
 * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and
 * these folders have a subscribed attribute which the user can set,
 * and which we honor.
 * mbox folders, on the other hand, have no subscribed attribute for
 * their !HOLDS_MESSAGE folders, so we must recurse to all of the
 * descendant HOLDS_MESSAGE folders to see if we should show.
 *
 * @param folder the folder where we begin
 * @param xml_parent XML Element where the gathered information will be
 *                   appended
 * @param subscribed_only Only add 'subscribed' folders
 * @param doCount Whether to generate message counts for Elements
 *                corresponding to HOLDS_MESSAGE folders.
 * @returns maximum depth of the folder tree (needed to calculate the
 *     necessary columns in a table).  Returns 0 if no XML elements added.
 */
protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) {
    int generatedDepth = 0;
    int folderType;
    Element xml_folder;

    try {
        folderType = folder.getType();
    } catch (MessagingException ex) {
        log.error("Can't get enough info from server to even make Gui node", ex);
        xml_parent.setAttribute("error", "For child '" + folder.getName() + ":  " + ex.getMessage());
        return 0;
    }
    boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0;
    boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0;
    // Sanity check:
    if ((!holds_folders) && !holds_messages) {
        log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName());
        throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName());
    }
    if (subscribed_only && holds_messages && !folder.isSubscribed())
        return generatedDepth; // Return right away and save a LOT OF WORK
    // N.b. we honor folder.isSubscribed() only for holds_message
    // folders.  That means all Maildir server folders, and all
    // mbox server folders except for mbox directories.  In this
    // last case, we must recurse to determine whether to show folder.
    String id = generateFolderHash(folder);
    xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages);
    // XMLUserModel.createFolder() declares no throws.  If any Exceptions
    // are expected from it, move the statement above into the try block.
    // The xml_folder Element here will be orphaned and GC'd if we don't
    // appendChild (in which case we return 0).

    if (doCount && holds_messages)
        try {
            // this folder will definitely be added!
            /* This folder can contain messages */
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");
            log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName());
            xml_folder.appendChild(messagelist);
        } catch (MessagingException ex) {
            log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex);
            xml_folder.setAttribute("error", ex.getMessage());
        }

    int descendantDepth = 0;
    if (holds_folders)
        try {
            Set<String> fullNameSet = new HashSet<String>();

            /* Recursively add subfolders to the XML model */
            // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE
            // folders, that skips non-Message Folders which may contain
            // subscribed descendants!
            for (Folder f : folder.list()) {
                if (!fullNameSet.add(f.getFullName())) {
                    log.warn("Skipping duplicate subfolder returned by mail" + " server:  " + f.getFullName());
                    continue;
                }
                if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed())
                    continue;
                /* If we recursed here, the getFolderTree() would
                 * just return 0 and no harm done.
                 * Just helping performance by preventing a recursion
                 * here.
                 * For comment on the logic here, see the same test
                 * towards the top of this method (before recursion).
                 */
                int depth = getFolderTree(f, xml_folder, subscribed_only, doCount);
                if (depth > descendantDepth)
                    descendantDepth = depth;
            }
            generatedDepth += descendantDepth;
        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }

    // We've already validated that if subscribed_only and holds_message
    //  then folder is subcribed.  Also verified either holds_m or holds_f.
    //  Only have to check the !holds_message case.
    if (subscribed_only && (!holds_messages) && descendantDepth < 1) {
        xml_folder = null;
        // Unnecessary, but may encourage GC
        return generatedDepth;
    }

    /* We ALWAYS return only subscribed folders except for these two
     * distinct cases: */
    xml_folder.setAttribute("subscribed",
            ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false"
                    : "true");
    // N.b. our Element's "subscribed" element does not correspond 1:1
    // to Folder.isSubscribed(), since non-message-holding Folders have
    // no "subscribed" attribute.
    folders.put(id, folder);

    xml_parent.appendChild(xml_folder);
    generatedDepth++; // Add the count for xml_folder
    return generatedDepth;
}

From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java

protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession)
        throws MessagingException {
    String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
    String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
    if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
        mailService = getMailService();/*from  w  w w.  j  av  a2 s.  c o m*/

        MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);

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

        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();

        initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());

        initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString());

        initialExecutionContext.put(CORE_SESSION_KEY, coreSession);

        initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol'
                                                                        // schema

        Folder rootFolder = null;
        Store store = null;
        try {
            String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
            initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType);
            // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY));

            String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
            String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
            Boolean socketFactoryFallback = (Boolean) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
            String socketFactoryPort = (String) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
            Boolean starttlsEnable = (Boolean) currentMailFolder
                    .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
            String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
            Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
            long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue();

            String imapDebug = Framework.getProperty(IMAP_DEBUG, "false");

            Properties properties = new Properties();
            properties.put("mail.store.protocol", protocolType);
            // properties.put("mail.host", host);
            // Is IMAP connection
            if (IMAP.equals(protocolType)) {
                properties.put("mail.imap.host", host);
                properties.put("mail.imap.port", port);
                properties.put("mail.imap.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imap.debug", imapDebug);
                properties.put("mail.imap.partialfetch", "false");
            } else if (IMAPS.equals(protocolType)) {
                properties.put("mail.imaps.host", host);
                properties.put("mail.imaps.port", port);
                properties.put("mail.imaps.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imaps.ssl.protocols", sslProtocols);
                properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.imaps.socketFactory.port", socketFactoryPort);
                properties.put("mail.imap.partialfetch", "false");
                properties.put("mail.imaps.partialfetch", "false");
            } else if (POP3S.equals(protocolType)) {
                properties.put("mail.pop3s.host", host);
                properties.put("mail.pop3s.port", port);
                properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.pop3s.socketFactory.port", socketFactoryPort);
                properties.put("mail.pop3s.ssl.protocols", sslProtocols);
            } else {
                // Is POP3 connection
                properties.put("mail.pop3.host", host);
                properties.put("mail.pop3.port", port);
            }

            properties.put("user", email);
            properties.put("password", password);

            Session session = Session.getInstance(properties);

            store = session.getStore();
            store.connect(email, password);

            String folderName = INBOX; // TODO should be an attribute in 'protocol' schema
            rootFolder = store.getFolder(folderName);

            // need RW access to update message flags
            rootFolder.open(Folder.READ_WRITE);

            Message[] allMessages = rootFolder.getMessages();
            // VDU
            log.debug("nbr of messages in folder:" + allMessages.length);

            FetchProfile fetchProfile = new FetchProfile();
            fetchProfile.add(FetchProfile.Item.FLAGS);
            fetchProfile.add(FetchProfile.Item.ENVELOPE);
            fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
            fetchProfile.add("Message-ID");
            fetchProfile.add("Content-Transfer-Encoding");

            rootFolder.fetch(allMessages, fetchProfile);

            if (rootFolder instanceof IMAPFolder) {
                // ((IMAPFolder)rootFolder).doCommand(FetchProfile)
            }

            List<Message> unreadMessagesList = new ArrayList<Message>();
            for (Message message : allMessages) {
                Flags flags = message.getFlags();
                int unreadMessagesListSize = unreadMessagesList.size();
                if (flags != null && !flags.contains(Flag.SEEN)
                        && unreadMessagesListSize < emailsLimitLongValue) {
                    unreadMessagesList.add(message);
                    if (unreadMessagesListSize == emailsLimitLongValue - 1) {
                        break;
                    }
                }
            }

            Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]);

            // perform email import
            visitor.visit(unreadMessagesArray, initialExecutionContext);

            // perform flag update globally
            Flags flags = new Flags();
            flags.add(Flag.SEEN);

            boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY);
            if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) {
                flags.add(Flag.SEEN);
            } else {
                flags.add(Flag.DELETED);
            }
            rootFolder.setFlags(unreadMessagesArray, flags, true);

        } finally {
            if (rootFolder != null && rootFolder.isOpen()) {
                rootFolder.close(true);
            }
            if (store != null) {
                store.close();
            }
        }
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 *
 * @param request/*from   www  .  ja v  a2 s  . c  om*/
 *        where request.action = [ "Send" , "Update" ,"Read" , "Save" ]
 * @return
 */
private SetMessageResponseType sendImapSSLMail(SetMessageRequestType request) {

    //System.out.println("===> sendImapSSLMail: Action= " + request.getAction());

    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;
    Folder folder = null; //the email server folder the msg is CURRENTLY in.

    String userType = "";
    String[] access = new String[2];

    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDTO foundContact = null;
    try {
        foundContact = findContactByUserId(userId);
    } catch (Exception e) {
        log.error("Contact record not found for userid: " + request.getUserId());
        response.setMessage("Contact record not found for userid: " + request.getUserId());
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(foundContact.getCommonName(), foundContact.getUid());

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    // Use the sslStore to send/change the message
    try {
        //action = Save
        if (request.getAction().equalsIgnoreCase("Save")) {
            response = saveDraft(request, access, sslStore,
                    this.mapKmrLocationToImapFolder("Drafts", this.host), session);
            response.setSuccessStatus(true);
            //return response;
        }
        //action = Send
        else if (request.getAction().equalsIgnoreCase("Send")) {
            // create and send msg to recipient(s).
            Message[] msgArr = createMessage(session, access[0], request);
            sendMessagesTOCCBCC(msgArr, request, session);

            // Store a copy to sender's Sent folder
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder("Sent", this.host));
            folder.appendMessages(msgArr);

            response.setSuccessStatus(true);
        }
        //action = ..any other..
        else {
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
            folder.open(Folder.READ_WRITE);

            //--------------------------------------------
            // Find the message by the given Message-ID
            //--------------------------------------------
            IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

            //--------------------------------------------
            // Process the message
            //--------------------------------------------
            if (imapMessage != null) {
                System.out.println("===> sendImapSSLMail:Updating:   action=" + request.getAction());
                System.out.println("===> sendImapSSLMail:Updating:   folder=" + folder.getName());
                System.out.println("===> sendImapSSLMail:Updating:ImapMsgID=" + imapMessage.getMessageID());

                updateImapSSLMail(request, folder, imapMessage);

                System.out.println("===> sendImapSSLMail: Done Setting " + request.getAction() + " for msgId="
                        + request.getMessageId());

                response.setSuccessStatus(true);

            } else {
                String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
                System.out.println("===> sendImapSSLMail: " + statMsg);

                response.setSuccessStatus(false);
                response.setMessage(statMsg);
            }

        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error sending mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        return response;
    } finally {
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException me) {
                log.error("Error closing folder");
            }
        }
        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (MessagingException me) {
                log.error("Error closing SSLStore");
            }
        }
    }

    return response;

}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType archiveMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();

    IMAPSSLStore sslStore = null;//from  w  w w  .  j a  v a  2  s.  co  m
    Folder folder = null;
    Folder destinationFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    // INPUT:  request.getUserId()
    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    //PROCESSING the action.
    // folder --> the current folder the msg being processed is in.
    // destinationFolder --> the destination folder where the msg will be moved.
    try {

        //----------------------------------
        // Determine/Set destination folder
        //----------------------------------
        if (request.getAction().equals("Archive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "Archives");
        } else if (request.getAction().equals("Unarchive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        destinationFolder.open(Folder.READ_WRITE);

        //----------------------------------
        // Set originating folder
        //----------------------------------
        folder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
        folder.open(Folder.READ_WRITE);

        System.out.println(
                "===> DMD.archiveMessage: " + request.getAction() + "-ing for msgId=" + request.getMessageId()
                        + "\n===> from " + folder.getName() + " to folder=" + destinationFolder.getName());

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

        //--------------------------------------------
        // Process the message
        //--------------------------------------------
        if (imapMessage != null) {
            Message[] messages = new Message[] { imapMessage };
            folder.copyMessages(messages, destinationFolder);
            imapMessage.setFlag(Flags.Flag.DELETED, true);
            folder.expunge();

            System.out.println("===> DMD.archiveMessage: Done " + request.getAction() + " for msgId="
                    + request.getMessageId());

            response.setSuccessStatus(true);

        } else {
            String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> " + statMsg);

            response.setSuccessStatus(false);
            response.setMessage(statMsg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage(
                "Error " + request.getAction() + " mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;

    } finally {
        try {
            if ((folder != null) && folder.isOpen())
                folder.close(false);
            if ((destinationFolder != null) && destinationFolder.isOpen())
                destinationFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **///from w  w  w  .  j  a  va2s.  c o  m

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

From source file:com.sonicle.webtop.mail.Service.java

public void processViewAttachment(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");
    String pcid = request.getParameter("cid");
    String purl = request.getParameter("url");
    String punknown = request.getParameter("unknown");

    try {/*www  .  j a  va  2s .co  m*/
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = null;
        if (pcid != null) {
            part = mailData.getCidPart(pcid);
        } else if (purl != null) {
            part = mailData.getUrlPart(purl);
        } else if (pidattach != null) {
            part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
        } else if (punknown != null) {
            part = mailData.getUnknownPart(Integer.parseInt(punknown));
        }

        if (part != null) {
            String name = part.getFileName();
            if (name == null)
                name = "";
            try {
                name = MailUtils.decodeQString(name);
            } catch (Exception exc) {
            }
            name = name.trim();
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen())
                    folder.open(Folder.READ_ONLY);
            }

            String fileHash = AlgoUtils.md5Hex(new CompositeId(pfoldername, puidmessage, pidattach).toString());
            long lastModified = m.getReceivedDate().getTime();
            AttachmentViewerDocumentHandler docHandler = new AttachmentViewerDocumentHandler(false,
                    getEnv().getProfileId(), fileHash, part, lastModified);
            DocEditorManager.DocumentConfig config = getWts().prepareDocumentEditing(docHandler, name,
                    lastModified);

            new JsonResult(config).printTo(out);

        }
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetAttachment(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");
    String pcid = request.getParameter("cid");
    String purl = request.getParameter("url");
    String punknown = request.getParameter("unknown");
    String psaveas = request.getParameter("saveas");

    try {//from  ww w. j  av  a 2s.  c  o  m
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        IMAPMessage im = (IMAPMessage) m;
        im.setPeek(us.isManualSeen());
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = null;
        if (pcid != null) {
            part = mailData.getCidPart(pcid);
        } else if (purl != null) {
            part = mailData.getUrlPart(purl);
        } else if (pidattach != null) {
            part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
        } else if (punknown != null) {
            part = mailData.getUnknownPart(Integer.parseInt(punknown));
        }

        //boolean wasseen = m.isSet(Flags.Flag.SEEN);
        if (part != null) {
            String ctype = "binary/octet-stream";
            if (psaveas == null) {
                ctype = part.getContentType();
                int ix = ctype.indexOf(";");
                if (ix > 0)
                    ctype = ctype.substring(0, ix);
            }
            String name = part.getFileName();
            if (name == null)
                name = "";
            try {
                name = MailUtils.decodeQString(name);
            } catch (Exception exc) {
            }
            name = name.trim();
            if (psaveas == null) {
                int ix = name.lastIndexOf(".");
                if (ix > 0) {
                    //String ext=name.substring(ix+1);
                    String xctype = ServletHelper.guessMediaType(name);
                    if (xctype != null)
                        ctype = xctype;
                }
            }
            ServletUtils.setFileStreamHeaders(response, ctype, DispositionType.INLINE, name);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen())
                    folder.open(Folder.READ_ONLY);
            }
            InputStream is = part.getInputStream();
            OutputStream out = response.getOutputStream();
            fastStreamCopy(is, out);
            is.close();
            out.close();
            //if(!wasseen){
            //   if (us.isManualSeen()) {
            //   m.setFlag(Flags.Flag.SEEN, false);
            //   }
            //}
        }
        im.setPeek(false);

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetAttachments(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pids[] = request.getParameterValues("ids");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");

    try {//from   ww  w  . ja  v  a2s .  co m
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        String name = m.getSubject();
        if (name == null) {
            name = "attachments";
        }
        try {
            name = MailUtils.decodeQString(name);
        } catch (Exception exc) {
        }
        name += ".zip";
        //prepare hashmap to hold already used pnames
        HashMap<String, String> pnames = new HashMap<String, String>();
        ServletUtils.setFileStreamHeaders(response, "application/x-zip-compressed", DispositionType.INLINE,
                name);
        JarOutputStream jos = new java.util.jar.JarOutputStream(response.getOutputStream());
        byte[] b = new byte[64 * 1024];
        for (String pid : pids) {
            Part part = mailData.getAttachmentPart(Integer.parseInt(pid));
            String pname = part.getFileName();
            if (pname == null) {
                pname = "unknown";
            }
            /*
            try {
               pname = MailUtils.decodeQString(pname, "iso-8859-1");
            } catch (Exception exc) {
            }
            */
            //keep name and extension
            String bpname = pname;
            String extpname = null;
            int ix = pname.lastIndexOf(".");
            if (ix > 0) {
                bpname = pname.substring(0, ix);
                extpname = pname.substring(ix + 1);
            }
            //check for existing pname and find an unused name
            int xid = 0;
            String rpname = pname;
            while (pnames.containsKey(rpname)) {
                rpname = bpname + " (" + (++xid) + ")";
                if (extpname != null)
                    rpname += "." + extpname;
            }

            JarEntry je = new JarEntry(rpname);
            jos.putNextEntry(je);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen()) {
                    folder.open(Folder.READ_ONLY);
                }
            }
            InputStream is = part.getInputStream();
            int len = 0;
            while ((len = is.read(b)) != -1) {
                jos.write(b, 0, len);
            }
            is.close();

            //remember used pname
            pnames.put(rpname, rpname);
        }
        jos.closeEntry();
        jos.flush();
        jos.close();

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}