www.pudn.com > Javamail.rar > ReceiveTask.java


package com.digipower.automail.mailsender; 
 
import javax.servlet.*; 
import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import com.digipower.automail.AutoMailConstants; 
import java.sql.*; 
import com.digipower.common.basic.*; 
import java.io.*; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFRow; 
import org.apache.poi.hssf.usermodel.HSSFCell; 
import org.apache.poi.hssf.usermodel.HSSFFont; 
import org.apache.poi.hssf.usermodel.*; 
import com.digipower.automail.AutoMailConstants; 
import com.digipower.automail.DBHandler; 
import org.apache.log4j.*; 
 
 
public class ReceiveTask extends TimerTask{ 
 
  private static final int  C_SCHEDULE_HOUR = AutoMailConstants.SCHEDULE_HOUR; 
  private static boolean isRunning = false; 
  private ServletContext context = null; 
 
  private Connection conn = null; 
  private ConnectionDB_Oracle db = null; 
  private Statement stmt = null; 
  private ResultSet rs = null; 
  private PreparedStatement pstmt = null; 
  private String strSql = null; 
  private String strCom = ""; 
  private String strCustomer = ""; 
  private Calendar cal = null; 
  // Create a New XL Document 
  private HSSFWorkbook wb = null; 
  private HSSFSheet newsheet = null; 
  private HSSFRow newrow = null; 
  private HSSFCell newcell = null; 
  // The Output file is where the xls will be created 
  private FileOutputStream fOut = null; 
  private File file = null; 
  private String strOutPutFile = null; 
 
  private String strTemp = null; 
  private int iRowNum = 0; 
  private static Logger		s_log = null; 
 
  public ReceiveTask(ServletContext context) { 
    try 
    { 
      this.context = context; 
      db = new ConnectionDB_Oracle(); 
 
      s_log = Logger.getLogger(ReceiveTask.class); 
      PropertyConfigurator.configure(context.getRealPath("/") + "\\WEB-INF\\log4j.inf"); 
    } 
    catch(Exception e) 
    { 
      System.out.println("dboracle:" + e); 
    } 
  } 
 
  //Get the content of company and customer 
  void getComCustomer(String Folder, String Address){ 
    String strRead = ""; 
    String strContent = ""; 
    String strTemp = null; 
    try 
    { 
      strCom = ""; 
      strCustomer = ""; 
 
      String addrFile = AutoMailConstants.BOOTDIR 
          + Folder 
          + AutoMailConstants.MAIL_ADDRESS_FILE; 
 
      File file = new File(addrFile); 
 
      if (file.exists()) 
      { 
//        FileReader fr = new FileReader(addrFile); 
 
        FileInputStream fis = new FileInputStream(file); 
        InputStreamReader isr = new InputStreamReader(fis, "UTF8"); 
 
        BufferedReader br = new BufferedReader(isr); 
//        BufferedReader br = new BufferedReader(fr); 
 
        while ( (strRead = br.readLine()) != null) 
        { 
          strContent += strRead; 
        } 
 
        br.close(); 
        isr.close(); 
        fis.close(); 
//        fr.close(); 
 
        int iEnd = strContent.indexOf(Address); 
 
        s_log.error("System.getProperty:" + System.getProperty("file.encoding")); 
 
//        s_log.error("strContent:" + strContent); 
 
        if(iEnd > 0) 
        { 
          strContent = strContent.substring(0, iEnd - 2); 
 
          iEnd = strContent.lastIndexOf(AutoMailConstants.SEPARATOR); 
          strCom = strContent.substring(iEnd + 2, strContent.length()); 
          strContent = strContent.substring(0, iEnd); 
          iEnd = strContent.lastIndexOf(";"); 
          strCustomer = strContent.substring(iEnd + 1, strContent.length()); 
//System.out.println("strCustomer:" + strCustomer); 
//System.out.println("strCom:" + strCom); 
        } 
        s_log.error("Folder:" + Folder); 
        s_log.error("Address:" + Address); 
        s_log.error("strCom:" + strCom); 
        s_log.error("strCustomer:" + strCustomer); 
 
      } 
    } 
    catch(Exception e) 
    { 
      s_log.error("getComCustomer:" + e); 
      e.printStackTrace(); 
    } 
  } 
//the run method 
 public void run(){ 
   try 
   { 
     cal = Calendar.getInstance(); 
 
     s_log.warn("UserName:" + AutoMailConstants.USER_NAME); 
     s_log.warn("PWD:" + AutoMailConstants.PSW); 
 
//System.out.println("Timer:" + (cal.get(Calendar.HOUR_OF_DAY) - C_SCHEDULE_HOUR)); 
 
     if (!isRunning) 
     { 
       //if ((cal.get(Calendar.HOUR_OF_DAY) - C_SCHEDULE_HOUR) <= 3 && (cal.get(Calendar.HOUR_OF_DAY) - C_SCHEDULE_HOUR) >= 0 ) 
       //{ 
         isRunning = true; 
 
         conn = db.getConnection(); 
         conn.setAutoCommit(false); 
 
         MailAuthenticator authenticator = null; 
 
         Properties props = new Properties(); 
         props.put("mail.pop3.host", AutoMailConstants.HOST_NAME); 
         props.put("mail.pop3.auth", "true"); //设置pop3认证,很关键的一句 
 
         authenticator = new MailAuthenticator(AutoMailConstants.USER_NAME, AutoMailConstants.PSW); 
 
         //Session session = Session.getDefaultInstance(props, authenticator); 
         Session session = Session.getInstance(props, authenticator); 
 
         Store store = session.getStore("pop3"); 
         store.connect(HOST_NAME, USER_NAME, PSW); 
 
         Folder folder = store.getFolder("INBOX"); 
         folder.open(Folder.READ_WRITE); 
 
         Message message[] = folder.getMessages(); 
 
//System.out.println("Messages's length: " + message.length); 
         receiver pmm = null;     //the receiver action's class name 
         int iStart = 0; 
         int iAddrEnd = 0; 
         String str = null; 
         String strFolder = ""; 
         String strFailAddr = ""; 
         int iNum = 0; 
 
         for (int j = 0; j < message.length; j++) 
         { 
           pmm = new receiver((MimeMessage)message[j]); 
 
System.out.println(":" + pmm.getFrom()); 
//System.out.println("pmm.getMailAddress(\"TO\"):" + pmm.getMailAddress("TO")); 
           if (pmm.getFrom().endsWith("")) //将发送失败的地址存入数据库 
           { 
             try 
             { 
               pmm.setDateFormat("yyyy/MM/dd HH:mm:ss"); 
               pmm.getMailContent((Part) message[j]); 
 
               str = pmm.getBodyText(); 
               iStart = str.indexOf("Content-Description:"); //the start of content 
               iAddrEnd = str.indexOf(AutoMailConstants.POSTMASTER_SEPARATOR); //the end of content 
 
               if (iStart > 0 && iAddrEnd > 0) 
               { 
                 strFailAddr = str.substring(iStart + 35, iAddrEnd); 
                 strFolder = str.substring(iStart + 21, iStart + 35); 
  //System.out.println("strFailAddr:" + strFailAddr); 
  //System.out.println("strFolder:" + strFolder); 
 
                 getComCustomer(strFolder, strFailAddr); 
System.out.println("Search for the problem of Receiver."); 
                 strSql = 
                     "select count(*) as num from FailureAddressLog where FolderNameF = '" + 
                     strFolder + "' and company = '" + strCom + "' and customer = '" + strCustomer + "'"; 
 
                 stmt = conn.createStatement(); 
                 rs = stmt.executeQuery(strSql); 
 
                 if (rs.next()) 
                 { 
                   iNum = rs.getInt("num"); 
 
                   strSql = "insert into FailureAddressLog values(?, ?, ?, ?)"; 
                   pstmt = conn.prepareStatement(strSql); 
 
                   if (iNum <= 0) 
                   { 
 
                     if(strCom != null && strCom.length() > 0 
                        && strCustomer != null && strCustomer.length() > 0) 
                     { 
                       pstmt.setString(1, strFolder); 
                       pstmt.setString(2, new String(strCom.getBytes())); 
                       pstmt.setString(3, new String(strCustomer.getBytes())); 
                       pstmt.setString(4, strFailAddr); 
 
                       pstmt.executeUpdate(); 
                       conn.commit(); 
                     } 
                   } 
 
                 } 
               } 
 
               message[j].setFlag(Flags.Flag.DELETED, true); //将邮件标记为删除,防止下次重读 
             } 
             catch(Exception e) 
             { 
               s_log.error(":" + pmm.getFrom() + e); 
 
               System.out.println(e + "receive insert db"); 
             } 
 
 
           } 
           else if( pmm.getMailAddress("TO") != null 
                    &&  pmm.getMailAddress("TO").length() > 19 
                    &&  pmm.getMailAddress("TO").indexOf(AutoMailConstants.REPLY_SEPARATOR) > 0) 
           {//将回条信息存入Excel档 
             try 
             { 
 
System.out.println("Message " + j + "  to: " + pmm.getMailAddress("TO")); 
               strTemp = pmm.getMailAddress("TO"); 
               //if(strTemp != null && strTemp.length() > 19 && strTemp.indexOf("#$#$#$") > 0) 
               //{ 
                 int iTemp = strTemp.indexOf(AutoMailConstants.REPLY_SEPARATOR); 
 
                 if(iTemp > 0) 
                 { 
                   strOutPutFile = strTemp.substring(iTemp + 4, iTemp + 18); 
 
                    wb = new HSSFWorkbook(new FileInputStream(AutoMailConstants.BOOTDIR 
                                                + strOutPutFile + "\\" 
                                               + strOutPutFile + ".xls")); 
                    newsheet = wb.getSheetAt(0); 
                    iRowNum = newsheet.getPhysicalNumberOfRows(); 
//System.out.println("iRowNum:" + iRowNum); 
//System.out.println("Message " + j + "  from: " + pmm.getFrom()); 
 
                   newrow = newsheet.createRow(iRowNum); 
 
 
                   newcell = newrow.createCell((short)3); 
                   newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                   newcell.setEncoding((short)1); 
                   newcell.setCellValue(pmm.getSubject()); 
 
                   pmm.setDateFormat("yyyy/MM/dd HH:mm:ss"); 
                   newcell = newrow.createCell((short)4); 
                   newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                   newcell.setEncoding((short)1); 
                   newcell.setCellValue(pmm.getSentDate()); 
 
                   newcell = newrow.createCell((short)2); 
                   newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                   newcell.setEncoding((short)1); 
 
                   strTemp = pmm.getFrom(); 
 
                   if(strTemp.indexOf("<") > 0) 
                   { 
                     strTemp = strTemp.substring(strTemp.indexOf("<") + 1, strTemp.indexOf(">")); 
                   } 
 
                   newcell.setCellValue(strTemp); 
 
                   getComCustomer(strOutPutFile, strTemp); 
 
//System.out.println("strCom:" + strCom); 
//System.out.println("strCustomer:" + strCustomer); 
                   newcell = newrow.createCell((short)1); 
                   newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                   newcell.setEncoding((short)1); 
                   newcell.setCellValue(strCustomer); 
 
                   newcell = newrow.createCell((short)0); 
                   newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                   newcell.setEncoding((short)1); 
                   newcell.setCellValue(strCom); 
 
                   iTemp = 0; 
 
                   fOut = new FileOutputStream(AutoMailConstants.BOOTDIR 
                                               + strOutPutFile + "\\" 
                                               + strOutPutFile + ".xls"); 
 
                   wb.write(fOut); 
                   fOut.flush(); 
                   // Done Deal.. 
System.out.println("fOut.close"); 
                   fOut.close(); 
                 //} 
 
                 message[j].setFlag(Flags.Flag.DELETED, true); //将邮件标记为删除,防止下次重读 
               } 
             } 
             catch(Exception e) 
             { 
               s_log.error(pmm.getMailAddress("TO") + e); 
 
               System.out.println(e.toString() + " 2"); 
             } 
 
           } 
           else 
           { 
             String strFolderName = null; 
             try 
             { 
               String strTemp = pmm.getSubject().trim(); 
               String strSql = "select foldernamem from automail_master where subject =?"; 
//System.out.println("start0000"); 
               strTemp = strTemp.substring(strTemp.lastIndexOf(":")+1, strTemp.length()).trim(); 
System.out.println("strTempgetSubject:" + strTemp); 
               DBHandler handler = new DBHandler(); 
//System.out.println("start1111111111111"); 
               strFolderName = handler.Handler(conn, strSql, strTemp, 1, 1); 
//System.out.println("strFolderName:" + strFolderName); 
//System.out.println("start22222222222222"); 
             } 
             catch(Exception e) 
             { 
               System.out.println(e + " get subject from db error"); 
             } 
             if(strFolderName != null) 
             { 
//System.out.println("start777777777"); 
               try 
               { 
 
                 String strAddress = pmm.getFrom(); 
                 strAddress = strAddress.substring(strAddress.indexOf("<") + 1, strAddress.indexOf(">")); 
System.out.println("strAddress.substring:" + strAddress); 
                 getComCustomer(strFolderName, strAddress); 
 
                 wb = new HSSFWorkbook(new FileInputStream(AutoMailConstants.BOOTDIR 
                                             + strFolderName + "\\" +strFolderName + ".xls")); 
                 newsheet = wb.getSheetAt(0); 
                 iRowNum = newsheet.getPhysicalNumberOfRows(); 
 
                 newrow = newsheet.createRow(iRowNum); 
 
                 newcell = newrow.createCell((short)3); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
                 newcell.setCellValue(pmm.getSubject()); 
 
                 pmm.setDateFormat("yyyy/MM/dd HH:mm:ss"); 
                 newcell = newrow.createCell((short)4); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
                 newcell.setCellValue(pmm.getSentDate()); 
 
                 newcell = newrow.createCell((short)2); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
 
                 strTemp = pmm.getFrom(); 
 
                 if(strTemp.indexOf("<") > 0) 
                 { 
                   strTemp = strTemp.substring(strTemp.indexOf("<") + 1, strTemp.indexOf(">")); 
                 } 
                 newcell.setCellValue(strTemp); 
 
                 newcell = newrow.createCell((short)1); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
                 newcell.setCellValue(strCustomer); 
 
                 newcell = newrow.createCell((short)0); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
                 newcell.setCellValue(strCom); 
 
                 fOut = new FileOutputStream(AutoMailConstants.BOOTDIR 
                                             + strFolderName + "\\" +strFolderName + ".xls"); 
                 wb.write(fOut); 
                 fOut.flush(); 
                 // Done Deal.. 
                 fOut.close(); 
                 message[j].setFlag(Flags.Flag.DELETED, true); //将邮件标记为删除,防止下次重读 
               } 
               catch(Exception e) 
               { 
                 System.out.println(e + "unconfirm reply address"); 
               } 
             } 
             else 
             { 
               try 
               { 
                 wb = new HSSFWorkbook(new FileInputStream(AutoMailConstants.BOOTDIR 
                                             +  "Reply.xls")); 
                 newsheet = wb.getSheetAt(0); 
                 iRowNum = newsheet.getPhysicalNumberOfRows(); 
 
                 newrow = newsheet.createRow(iRowNum); 
                 newcell = newrow.createCell((short)0); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
 
                 strTemp = pmm.getFrom(); 
 
                 if(strTemp.indexOf("<") > 0) 
                 { 
                   strTemp = strTemp.substring(strTemp.indexOf("<") + 1, strTemp.indexOf(">")); 
                 } 
                 newcell.setCellValue(strTemp); 
 
                 pmm.setDateFormat("yyyy/MM/dd HH:mm:ss"); 
                 newcell = newrow.createCell((short)1); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
                 newcell.setCellValue(pmm.getSentDate()); 
                 newcell = newrow.createCell((short)2); 
                 newcell.setCellType(HSSFCell.CELL_TYPE_STRING); 
                 newcell.setEncoding((short)1); 
                 //pmm.getMailContent((Part) message[j]); 
                 newcell.setCellValue(pmm.getSubject()); 
 
                 fOut = new FileOutputStream(AutoMailConstants.BOOTDIR 
                                             + "Reply.xls"); 
                 wb.write(fOut); 
                 fOut.flush(); 
                 // Done Deal.. 
                 fOut.close(); 
                 message[j].setFlag(Flags.Flag.DELETED, true); //将邮件标记为删除,防止下次重读 
               } 
               catch(Exception e) 
               { 
                 s_log.error("Reply.xls reply address" + e); 
 
                 System.out.println(e + "Reply.xls reply address"); 
               } 
             } 
 
           } 
         } 
 
         folder.close(true);  //将邮件标记为删除,防止下次重读 
         store.close(); 
 
         isRunning = false; 
 
       //} 
     } 
   } 
   catch(Exception e) 
   { 
     try 
     { 
       if(conn != null) 
       { 
         conn.rollback(); 
       } 
     } 
     catch(Exception ee) 
     { 
       ee.printStackTrace(); 
     } 
     e.printStackTrace(); 
   } 
   finally 
   { 
     try 
     { 
       if(fOut != null) 
       { 
         fOut.close(); 
       } 
 
       if(rs != null) 
       { 
         rs.close(); 
       } 
       if(pstmt != null) 
       { 
         pstmt.close(); 
       } 
       if(conn != null) 
       { 
System.out.println("Receiver CONN close"); 
         conn.close(); 
       } 
System.out.println("Receiver finally"); 
     } 
     catch(Exception e) 
     { 
       e.printStackTrace(); 
     } 
   } 
 } 
}