Example usage for javax.mail Store toString

List of usage examples for javax.mail Store toString

Introduction

In this page you can find the example usage for javax.mail Store toString.

Prototype

@Override
public String toString() 

Source Link

Document

Return getURLName.toString() if this service has a URLName, otherwise it will return the default toString.

Usage

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 av  a 2s  . com*/

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

/**
   Disconnect from all Mailhosts//from w  ww . j  a  v a2  s  .c  o m
*/
public void disconnectAll() {
    Enumeration<String> e = user.mailHosts();
    while (e.hasMoreElements()) {
        String name = e.nextElement();
        disconnect(name);
    }
    Set<String> zapKeys = new HashSet<String>();
    for (Map.Entry<String, Store> storeEntry : stores.entrySet()) {
        Store st = storeEntry.getValue();
        try {
            st.close();
            log.info("Mail: Connection to " + st.toString() + " closed.");
        } catch (Exception ex) {
            log.warn("Mail: Failed to close connection to " + st.toString() + ". Reason: " + ex.getMessage());
        }
        zapKeys.add(storeEntry.getKey());
    }
    for (String key : zapKeys)
        stores.remove(key);
    folders = null;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
   Disconnect from mailhost "name"/*from  w w  w . j  av  a 2  s .co  m*/
*/
public void disconnect(String name) {
    try {
        Folder f = connections.get(name);
        if (f != null && f.isOpen()) {
            f.close(true);
            Store st = connections.get(name).getStore();
            //st.close();
            log.info("Mail: Disconnected from folder " + f.toString() + " at store " + st.toString() + ".");
        } else {
            log.warn("Mail: Folder " + name + " was null???.");
        }
    } catch (MessagingException ex) {
        // Should not happen
        log.fatal("Unexpected failure to disconnect", ex);
    } catch (NullPointerException ex) {
        // This happens when deleting a folder with an error
        log.fatal("Failed to disconnect after deleting folder?  " + ex);
        // Log exception too if the comment above is wrong
    } finally {
        connections.remove(name);
    }
}

From source file:net.wastl.webmail.server.WebMailSession.java

protected Store connectStore(String host, String protocol, String login, String password)
        throws MessagingException {
    /* Check whether the domain of this user allows to connect to the host */
    WebMailVirtualDomain vdom = parent.getStorage().getVirtualDomain(user.getDomain());
    if (!vdom.isAllowedHost(host)) {
        throw new MessagingException("You are not allowed to connect to this host");
    }/*from   www .  ja v a 2  s .c o  m*/
    imapBasedir = vdom.getImapBasedir();

    /* Check if this host is already connected. Use connection if true, create a new one if false. */
    Store st = stores.get(host + "-" + protocol);
    if (st == null) {
        st = mailsession.getStore(protocol);
        stores.put(host + "-" + protocol, st);
    }

    /* Maybe this is a new store or this store has been disconnected. Reconnect if this is the case. */
    if (!st.isConnected()) {
        try {
            st.connect(host, login, password);
            log.info("Mail: Connection to " + st.toString() + ".");
        } catch (AuthenticationFailedException ex) {
            /* If login fails, try the login_password */
            if (!login_password.equals(password)
                    && parent.getStorage().getConfig("FOLDER TRY LOGIN PASSWORD").toUpperCase().equals("YES")) {
                st.connect(host, login, login_password);
                log.info("Mail: Connection to " + st.toString()
                        + ", second attempt with login password succeeded.");
            } else {
                throw ex;
            }
        }
    }
    return st;
}