Sunday, November 18, 2012

POP3 email polling


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage.RecipientType;

import com.orga.application.vo.EmailVO;
import com.orga.utility.loggers.Logger;
import com.orga.utility.loggers.LoggerFactory;
import com.orga.utility.utils.CommonUtils;
import com.orga.utility.utils.DateUtils;
import com.sun.mail.pop3.POP3SSLStore;
/**
 * This Class represents the global
 * Email Interaction and pop 3 configuration
 * to read the emails..
 *
 * @version 0.1, 05 Sept 2012 - Base version
 *
 */
public class EmailIntegration {
    /**
     * The logger instance for this class.
     */
    private static final Logger LOGGER = LoggerFactory.
    getInstance().getLogger(EmailIntegration.class);
    /**
     * Represent the Mail session object.
     */
    private Session session = null;
    /**
     * Represent the store Object.
     */
    private Store store = null;
    /**
     * Represent the Folder object of mail.
     */
    private Folder folder;
    private String username, password;
   
   
    /**
     * Closing Folder method
     *
     * @throws Exception
     */
    public void closeFolder() throws Exception {
        folder.close(false);
    }
    /**
     * Method to get the Message Count.
     *
     * @return no of messages<tt>int</tt>.
     *
     * @throws Exception
     */
    public int getMessageCount() throws Exception {
        return folder.getMessageCount();
    }
    /**
     * Method to get the unread Message Count.
     *
     * @return no of messages<tt>int</tt>.
     *
     * @throws Exception
     */
    public int getUnreadMessageCount() throws Exception {
        return folder.getUnreadMessageCount();
    }
    /**
     * Method to get the new Message Count.
     *
     * @return no of messages<tt>int</tt>.
     *
     * @throws Exception
     */
    public int getNewMessageCount() throws Exception {
        return folder.getNewMessageCount();
    }

    public void disconnect() throws Exception {
        store.close();
    }
    public void setUserPass(String username, String password) {
        this.username = username;
        this.password = password;
    }
    /**
     * Method represent the mail Connection.
     *
     * @throws Exception throws exception in
     * case not able to connect.
     */
    public void connect() throws Exception {
        try {
            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties pop3Props = new Properties();
            pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
            pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
            pop3Props.setProperty("mail.pop3.port", "995");
            pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
            pop3Props.setProperty("javax.net.ssl.trustStorePassword", "chimera");
            pop3Props.setProperty("mail.pop3.ssl.enable", "true");
            URLName url = new URLName("pop3", "pop.gmail.com", 995, "", username,
                    password);
            session = Session.getInstance(pop3Props, null);
            store = new POP3SSLStore(session, url);
            store.connect();
        } catch (Exception exception) {
            LOGGER.error("Not able to Connect the mail server!!");
            exception.printStackTrace();
        }
    }
    /**
     * Method to Open the Mail Folder to read and Write.
     *
     * @param folderName name of the folder to open.
     *
     * @throws Exception throws exception in
     * case not able to connect.
     */
    public void openFolder(String folderName) throws Exception {
        /*
         *  Open the Folder
         */
        folder = store.getDefaultFolder();
        folder = folder.getFolder(folderName);
        if (folder == null) {
            throw new Exception("Invalid folder");
        }
        /*
         *  try to open read/write and if that fails try read-only
         */
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
    }
    /**
     * Method to filter to get the recent and todays mails.
     *
     * @return an instance of <tt>List<EmailVO></tt>.
     *
     * @throws MessagingException
     * @throws IOException
     * @throws ParseException
     */
    public List<EmailVO> todaysDateMail() throws MessagingException,
    IOException, ParseException {
        Date sendDate = null;
        Date todaysDate = null;
        List<EmailVO> emailList = null;
        EmailVO emailVO = null;
        int recentMessage = 0;

        try {
            LOGGER.info("Folder to Scan :" + folder.getName());
            LOGGER.info("No of Msg in folder :"
                    + folder.getMessageCount());
            Message msgs[] = folder.getMessages();
            recentMessage = msgs.length;
            LOGGER.info("No of Msg in folder :" + recentMessage);
            if (recentMessage > 0) {
                emailList = new ArrayList<EmailVO>();
                for (int i = 0; i < recentMessage; i++) {
                    Message message = msgs[i];
                    /*
                     * Getting the Send Date.
                     */
                    String sdate = DateUtils.convertDateTOString(
                            message.getSentDate(), "MM/dd/yyyy");
                    sendDate = DateUtils.convertStringToDate(sdate,
                            "MM/dd/yyyy");
                    LOGGER.info("Mail Send date :" + sendDate);
                    /*
                     * Getting the Todays Date.
                     */
                    String tdate = DateUtils.convertDateTOString(new Date(),
                            "MM/dd/yyyy");
                    todaysDate = DateUtils.convertStringToDate(tdate,
                            "MM/dd/yyyy");
                    LOGGER.info("Today date :" + todaysDate);

                    // date compare between todays Date & mail sent Date.
                    if (sendDate.compareTo(todaysDate) == 0) {
                        String bcc = "";
                        Address[] address;
                        /*if ((address = message.getRecipients(Message.RecipientType.BCC)) != null) {
                            for (int j = 0; j < address.length; j++) {
                                bcc = address[j].toString();
                                LOGGER.info("BCC: " + bcc);
                            }
                        }*/
                /*    if (message.getRecipients(RecipientType.BCC) != null
                            && bcc.contains("bloomberg.interaction@gmail.com")) {*/
                        emailVO = new EmailVO();
                        /*
                         * Setting the Bcc field.
                         */
                        //emailVO.setBcc(bcc);
                        /*
                         * Setting the send Date field.
                         */
                        if (sendDate != null) {
                            LOGGER.info("Sent Date:" + sendDate);
                            emailVO.setSendDate(sendDate);
                        }
                        /*
                         * Setting the to field.
                         */
                        String to = "";
                        if ((address = message
                                .getRecipients(Message.RecipientType.TO)) != null) {
                            for (int j = 0; j < address.length; j++) {
                                 to = address[j].toString();           
                                LOGGER.info("TO: " + to);
                                EmailVO emailVOMul = new EmailVO();
                                CommonUtils.copyBeanProperties(emailVO, emailVOMul);
                                 if (CommonUtils.isValidObject(emailVOMul)) {
                                        if (to.contains("<")) {
                                            emailVOMul.setTo(to.substring(
                                                    to.indexOf("<") + 1,
                                                    to.indexOf(">")));
                                        } else {
                                            emailVOMul.setTo(to);
                                    }
                                }
                                emailList.add(getEmaiVOObject(message, emailVOMul));
                            }
                        }
                    //}
                    }// end if date compare
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return emailList;
    }
    /**
     * Method to get the Email VO Objet.
     *
     * @param message Message class.
     *
     * @param  an instance of <tt>EmailVO</tt>.
     *
     */
    private EmailVO getEmaiVOObject(Message message, EmailVO emailVO) {
        try {
            Address[] address;
            if ((address = message.getFrom()) != null) {
                for (int j = 0; j < address.length; j++) {
                    String from = address[j].toString();
                    LOGGER.info("FROM: " + from);
                    if (CommonUtils.isValidObject(emailVO)) {
                        if (from.contains("<")) {
                            emailVO.setFrom(from.substring(
                                    from.indexOf("<") + 1,
                                    from.indexOf(">")));
                        } else {
                            emailVO.setFrom(from);
                        }
                    }
                }
            }

       
        if ((address = message
        .getRecipients(Message.RecipientType.CC)) != null) {
            for (int j = 0; j < address.length; j++) {
                String cc = address[j].toString();
                LOGGER.info("CC: " + cc);
                if (CommonUtils.isValidObject(emailVO))
                    emailVO.setCc(cc);
            }
        }

        if ((message.getSubject()) != null) {
            String subject = message.getSubject();
            LOGGER.info("Subject:" + subject);
            if (CommonUtils.isValidObject(emailVO))
                emailVO.setSubject(subject);
        }

        System.out
                .println("---------------------------------");

        // Reading mail body part

        String contentType = message.getContentType();
        String textMessage = "";
        System.out.println("Message Content type:" + contentType);
        if (message.isMimeType("multipart/related")) {
            System.out.println("multipart/related".toUpperCase());
               Multipart mp = (Multipart)message.getContent(); 
             int partsCount = mp.getCount();
             for (int k = 0; k < partsCount; k++) {
                 Part p = mp.getBodyPart(k);
                 parseMail(p, emailVO);
             }
       
        }
        if (message.isMimeType("multipart/alternative")) {
            System.out.println("multipart/alternative".toUpperCase());
               Multipart mp = (Multipart)message.getContent(); 
                int partsCount = mp.getCount(); 
                for (int k = 0; k < partsCount; k++) {
                     Part p = mp.getBodyPart(k);
                     parseMail(p, emailVO);
                 }
        }
        if (contentType.contains("text/plain")
                || contentType.contains("text/html")) {
            LOGGER.info("Mail Content type is text/html!");
            textMessage = message.getContent() != null ? message
                    .getContent().toString() : "";
        } else if (contentType.contains("multipart")) {
            LOGGER.info("Mail Content type is multipart!");
            // possibly contains attachments
            Multipart multiPart = (Multipart) message
                    .getContent();
            int partCount = multiPart.getCount();
            for (int j = 0; j < partCount; j++) {
                BodyPart part = multiPart.getBodyPart(j);
                if (Part.ATTACHMENT.equalsIgnoreCase(part
                        .getDisposition())) {
                    // absolutely an attachment
                    saveAttachmentToFile(part);
                }
            }
        }
        System.out.println("Final Email body :" + emailVO.getMailBody());
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return emailVO;
    }
    public void parseMail(Part message, EmailVO emailVO)  throws Exception 
    {           
        System.out.println("parse mail Type:"+ message.getContentType());
        if ((message.isMimeType("text/*")) &&  
        (message.getDisposition() != null && message.getDisposition().equals(Part.INLINE))) 
        { 
            System.out.println("Pares mail1:" + (String)message.getContent()); 
        } else if (message.isMimeType("multipart/alternative")) { 
            Multipart mp = (Multipart)message.getContent(); 
            int partsCount = mp.getCount(); 
            for (int k = 0; k < partsCount; k++) {
                Part p = mp.getBodyPart(k);
                parseMail(p, emailVO);
            }
        } else if (message.isMimeType("multipart/related")) { 
            Multipart mp = (Multipart)message.getContent(); 
            int partsCount = mp.getCount(); 
            for (int k = 0; k < partsCount; k++) {
                Part p = mp.getBodyPart(k);
                parseMail(p, emailVO);
            }
        } else if (message.isMimeType("text/plain")) {
            LOGGER.info("Mail Content type is text/*!");
            System.out.println("Pares mail2:" + (String)message.getContent());
            emailVO.setMailBody(message.getContent().toString().replaceAll("\\<.*?>", ""));
        }
    }  
    /*
     * method use to save the attachment in mail.
     */
    private void saveAttachmentToFile(BodyPart part) throws MessagingException,
            IOException {
        String destFilePath = "/home/sougatd/mailattachments/"
                + part.getFileName();
        FileOutputStream output = new FileOutputStream(destFilePath);
        InputStream input = part.getInputStream();
        byte[] buffer = new byte[input.available()];
        int byteRead;
        while ((byteRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, byteRead);
        }
        output.close();
    }
}



/* Calling the email integration*/
EmailIntegration emailIntegration = new EmailIntegration();
          emailIntegration.setUserPass("mail@gmail.com", "password");  
         emailIntegration.connect();
            emailIntegration.openFolder("inbox");
            int totalMessages = emailIntegration.getMessageCount();
            int unreadmessage = emailIntegration.getUnreadMessageCount();
            LOGGER.info("Total messages = " + totalMessages);
            LOGGER.info("unread messages = " + unreadmessage);
            LOGGER.info("-------------------------------");
            emailVOList = emailIntegration.todaysDateMail();
            emailIntegration.closeFolder();
            emailIntegration.disconnect();

Thursday, November 15, 2012

Alfresco Content search example

This method will allows to search the Alfresco document repository by content in the document.
returen the result  
/**
     * Alfresco Document search by Content.
     * @param alfrescoSearchVO
     */
    public List<String> searchByContent(AlfrescoSearchVO alfrescoSearchVO) {
        LOGGER.entering("searchByContent");
        List<String> documentList = null;
        try {
            initiate();
           
            RepositoryServiceSoapBindingStub repositoryService = alfrescoServices
            .getRepositoryService();
           
            Query query = new Query(Constants.QUERY_LANG_LUCENE,
                    DOCUMENT_SEARCH_PATH1
            +  " AND TEXT:(\""+ alfrescoSearchVO.getText() +"\")");
            QueryResult queryResult = repositoryService.query(STORE, query, false);
            ResultSet resultSet = queryResult.getResultSet();
            ResultSetRow[] rows = resultSet.getRows();
            if (rows == null) {
                System.out.println("No query results found.");
                if (alfrescoSearchVO.getText().trim().contains(" ")) {
                    String textArray[] = alfrescoSearchVO.getText().split(" ");
                    StringBuffer queryBuffer = new StringBuffer();
                    queryBuffer.append(" AND (");
                    for (int i=0; i<textArray.length; i++) {
                        if (i == 0) {
                            queryBuffer.append(
                            " TEXT:\""+ textArray[i].trim() +"\"");
                        } else {
                            queryBuffer.append(
                            " OR TEXT:\""+ textArray[i].trim() +"\"");
                        }
                    }
                    queryBuffer.append(" )");
                    if (queryBuffer.toString().length() > 0) {
                        System.out.println("Query :" + queryBuffer.toString());
                        query = new Query(Constants.QUERY_LANG_LUCENE,
                        DOCUMENT_SEARCH_PATH
                        +  queryBuffer.toString());
                        queryResult = repositoryService.query(STORE, query, false);
                        resultSet = queryResult.getResultSet();
                        rows = resultSet.getRows();
                        if (rows != null) {
                            documentList = iterateQueryResultSet(rows);
                        } else {
                            System.out.println("Final No query results found.");
                        }
                    }
                }
               
            } else {
                documentList = iterateQueryResultSet(rows);
            }
            alfrescoServices.endSession();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        LOGGER.exiting("searchByContent");
        return documentList;
    }
    /**
     * The result will be iterate to content the document information.
     * @param rows
     */
    public List<String> iterateQueryResultSet(ResultSetRow[] rows){
        LOGGER.entering("iterateQueryResultSet");
        List<String> documentList = new ArrayList<String>();
        try {
            for (ResultSetRow row : rows) {
                System.out.println("UID: " + row.getNode().getId());
                System.out.println("Type: " + row.getNode().getType());
               
                NamedValue[] values = row.getColumns();
                System.out.println("Properties: ");
                for (NamedValue col : values) {
                    /*if (col.getName().endsWith("title") || col.getName().endsWith("path")) {
                        System.out.println("\tName: " + col.getName());
                        System.out.println("\tValue: " + col.getValue());
                        System.out.println("------------------------");
                    }*/
                    if (col.getName().endsWith("path")) {
                        System.out.println("\tName: " + col.getName());
                        System.out.println("\tValue: " + col.getValue());
                        String path = col.getValue();
                        path = path.replace("/{http://www.alfresco.org/model/application/1.0}", "/app:");
                        path = path.replace("/{http://www.alfresco.org/model/site/1.0}", "/st:");
                        path = path.replace("/{http://www.alfresco.org/model/content/1.0}", "/cm:");
                        System.out.println("------------------------");
                        System.out.println("path:" + path);
                        documentList.add(path);
                    }
               
                    /*System.out.println("\tName: " + col.getName());
                    System.out.println("\tValue: " + col.getValue());*/
                   
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        LOGGER.exiting("iterateQueryResultSet");
        return documentList;
    }


/*Alfresco serach vo*/
public class AlfrescoSearchVO {
    private String name;
    private String title;
    private String text;
    private String author;
    private String modifier;
    private String creator;
    private String contentType;
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }
    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }
    /**
     * @return the text
     */
    public String getText() {
        return text;
    }
    /**
     * @param text the text to set
     */
    public void setText(String text) {
        this.text = text;
    }
    /**
     * @return the author
     */
    public String getAuthor() {
        return author;
    }
    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }
    /**
     * @return the modifier
     */
    public String getModifier() {
        return modifier;
    }
    /**
     * @param modifier the modifier to set
     */
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    /**
     * @return the creator
     */
    public String getCreator() {
        return creator;
    }
    /**
     * @param creator the creator to set
     */
    public void setCreator(String creator) {
        this.creator = creator;
    }
    /**
     * @return the contentType
     */
    public String getContentType() {
        return contentType;
    }
    /**
     * @param contentType the contentType to set
     */
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
   
}