com.pureinfo.srm.project.ProjectToFinishRemindJob.java Source code

Java tutorial

Introduction

Here is the source code for com.pureinfo.srm.project.ProjectToFinishRemindJob.java

Source

/**
 * PureInfo Command
 * @(#)ProjectAutoFinishJob.java   1.0 2007-1-12
 * 
 * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. 
 * All rights reserved, see the license file.
 * 
 * www.pureinfo.com.cn
 */

package com.pureinfo.srm.project;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.pureinfo.ark.content.ArkContentHelper;
import com.pureinfo.common.sender.SenderHelper;
import com.pureinfo.common.sender.model.ISender;
import com.pureinfo.dolphin.DolphinHelper;
import com.pureinfo.dolphin.model.IObjects;
import com.pureinfo.dolphin.persister.IStatement;
import com.pureinfo.force.PureSystem;
import com.pureinfo.force.exception.PureException;
import com.pureinfo.srm.auth.SRMUserConstants;
import com.pureinfo.srm.auth.domain.ISRMUserMgr;
import com.pureinfo.srm.auth.model.SRMUser;
import com.pureinfo.srm.org.model.Organization;
import com.pureinfo.srm.project.domain.IProjectMgr;
import com.pureinfo.srm.project.model.Project;

/**
 * <P>
 * Created on 2007-1-12 17:08:30 <BR>
 * Last modified on 2007-1-12
 * </P>
 * TODO describe ProjectAutoFinishJob here ...
 * 
 * @author elmar.chen
 * @version 1.0, 2007-1-12
 * @since Command 1.0
 */
public class ProjectToFinishRemindJob implements Job {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private static final int REMIND_STATUS_1MON = 1;

    private static final int REMIND_STATUS_3MON = 2;

    private static Logger logger = Logger.getLogger(ProjectAutoFinishJob.class);

    private static Map m_admins = new HashedMap();

    private static Map m_hRemindedPrjs = new HashedMap();

    private Date m_1MonthLater;

    private Date m_3MonthLater;
    private int i = 0;

    private IProjectMgr m_prjMgr;

    public static final String TODAY = DATE_FORMAT.format(new Date());;

    private static Date getNMonthLater(int _n) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getDefault());
        cal.roll(Calendar.MONTH, _n);
        return cal.getTime();
    }

    /**
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
    public void execute(JobExecutionContext _sContext) throws JobExecutionException {
        try {
            logger.debug("i now is: " + i++);
            init();
            remindTeachers();
            logger.debug("" + m_hRemindedPrjs.size());
            remindAdmins();
        } catch (PureException e) {
            e.printStackTrace();
            logger.error(e);
        }

    }

    private void remindAdmins() throws PureException {
        for (Iterator iter = m_hRemindedPrjs.entrySet().iterator(); iter.hasNext();) {
            Map.Entry en = (Map.Entry) iter.next();
            Integer iDept = (Integer) en.getKey();
            SRMUser admin = (SRMUser) m_admins.get(iDept);
            if (admin == null)
                continue;
            StringBuffer sbuff = new StringBuffer();

            List[] prjs = (List[]) en.getValue();
            if (prjs == null || prjs[0].size() + prjs[1].size() == 0) {
                continue;
            }
            sbuff.append(admin.getTrueName()).append(" \n\n");
            sbuff.append("");
            for (int ii = 0; ii < prjs.length; ii++) {
                if (prjs[ii].size() > 0) {
                    sbuff.append("").append(ii == 0 ? 1 : 3).append("\n");
                    sbuff.append("\t\t\t\t\n");
                    sbuff.append("===================================================================\n");
                    for (Iterator iterator = prjs[ii].iterator(); iterator.hasNext();) {
                        Object[] ele = (Object[]) iterator.next();
                        Project prj = (Project) ele[0];
                        SRMUser usr = (SRMUser) ele[1];
                        Organization oSection = prj.getAdminSectionObj();
                        String sSectionName = oSection == null ? "" : oSection.getName();
                        sbuff.append(DATE_FORMAT.format(prj.getFinishDate())).append('\t');
                        sbuff.append(usr == null ? "" : usr.getTrueName()).append('\t');
                        sbuff.append(prj.getProjectNumber()).append('\t');
                        sbuff.append(sSectionName).append('\t');
                        sbuff.append(prj.getProjectName()).append('\t');
                        sbuff.append('\n');
                    }
                    sbuff.append("\n\n");
                }
            }
            sbuff.append("\n");
            sbuff.append(TODAY);
            String sMsg = sbuff.toString();
            sendMail(admin, "", sMsg);
            sbuff.setLength(0);

        }
    }

    private void remindTeachers() throws PureException {
        String sSQl = getSQL();
        IObjects objs = null;
        IStatement stat = null;
        try {
            stat = m_prjMgr.createQuery(sSQl, 0);
            logger.debug(sSQl);
            stat.setDate(0, m_3MonthLater);
            stat.setDate(1, m_1MonthLater);
            objs = stat.executeQuery(false);
            Project prj = null;
            while ((prj = (Project) objs.next()) != null) {
                logger.debug(prj.getProjectName());
                sendMail(prj);
            }
        } finally {
            DolphinHelper.clear(objs, stat);
        }

    }

    private void init() throws PureException {
        m_admins = new HashedMap();
        m_prjMgr = (IProjectMgr) ArkContentHelper.getContentMgrOf(Project.class);
        m_hRemindedPrjs = new HashedMap();
        m_1MonthLater = getNMonthLater(1);
        m_3MonthLater = getNMonthLater(3);
        IObjects admins = null;
        IStatement stat = null;
        try {
            ISRMUserMgr mgr = (ISRMUserMgr) ArkContentHelper.getContentMgrOf(SRMUser.class);
            stat = mgr.createQuery("SELECT * from {this} WHERE {this.type}=?", 0);
            stat.setInt(0, SRMUserConstants.UserType.MASK_ADMIN2);
            admins = stat.executeQuery();
            SRMUser user = null;
            while ((user = (SRMUser) admins.next()) != null) {
                m_admins.put(new Integer(user.getCollegeId()), user);
            }
        } finally {
            DolphinHelper.clear(admins, stat);
        }

    }

    private void sendMail(Project _prj) throws PureException {
        int nMonth = getMonthAhead(_prj);
        SRMUser user = _prj.getAdministrator();
        if (user == null) {
            return;
        }
        boolean success = sendMail(_prj, user, nMonth);
        if (success)
            addToAdmin(_prj, user, nMonth);
        int nLog = _prj.getIntProperty("finishRemindLog", 0);
        nLog = nLog | (nMonth == 1 ? REMIND_STATUS_1MON : REMIND_STATUS_3MON);
        _prj.setProperty("finishRemindLog", nLog);
        m_prjMgr.save(_prj);

    }

    private void addToAdmin(Project _prj, SRMUser _user, int _nMonth) throws PureException {
        int nDept = _user.getCollegeId();
        Integer iDept = new Integer(nDept);
        SRMUser admin = (SRMUser) m_admins.get(iDept);

        if (admin == null)
            return;
        List[] list = (List[]) m_hRemindedPrjs.get(iDept);
        if (list == null) {
            m_hRemindedPrjs.put(iDept, list = new ArrayList[] { new ArrayList(), new ArrayList() });
        }
        list[_nMonth == 1 ? 0 : 1].add(new Object[] { _prj, _user });
    }

    private boolean sendMail(Project _sPrj, SRMUser _sUser, int _nMonth) throws PureException {
        Organization oSection = _sPrj.getAdminSectionObj();
        String sSectionName = oSection == null ? "" : oSection.getName();
        String sMessage = makeMsg(_sPrj, _sUser, _nMonth, sSectionName);
        String sFromPerson = sSectionName.equals("") ? " " : sSectionName;
        return sendMail(_sUser, sFromPerson, sMessage);
    }

    private boolean sendMail(SRMUser _sUser, String sFromPerson, String sMessage) throws PureException {
        if (_sUser.getEmail() == null || !_sUser.getEmail().matches("[^@]+@([^@\\.]+\\.)+[^\\.@]+")) {
            return false;
        }
        String sToAddress = _sUser.getEmail();
        String sPerson = _sUser.getTrueName();
        ISender sender = SenderHelper.getSender(SenderHelper.TYPE_MAIL);
        String sFromAddress = PureSystem.getRequiredProperty("mail.system.user");
        return sender.send(sFromAddress, sFromPerson, sToAddress, sPerson, "", sMessage);
    }

    private String makeMsg(Project _sPrj, SRMUser _sUser, int _nMonth, String sSectionName) {
        StringBuffer sbuff = new StringBuffer();
        sbuff.append(_sUser.getTrueName()).append(" \n\n");
        sbuff.append("\t ").append(_sPrj.getProjectName()).append(" ").append(_nMonth)
                .append("[").append(DATE_FORMAT.format(_sPrj.getFinishDate())).append("]")
                .append(_nMonth == 1 ? "" : "").append("\n\n");
        sbuff.append(" ").append(sSectionName).append("\n");
        sbuff.append(TODAY);
        String sResult_ = sbuff.toString();
        sbuff.setLength(0);
        return sResult_;
    }

    private int getMonthAhead(Project _sPrj) {
        Date dFin = _sPrj.getFinishDate();
        //        logger.debug(dFin);
        int nLog = _sPrj.getIntProperty("finishRemindLog", 0);
        boolean in1Month = dFin.before(m_1MonthLater);
        int nMonth = -1;
        if (in1Month && (nLog & REMIND_STATUS_1MON) == 0) {
            nMonth = 1;
        } else {
            boolean in3Month = dFin.before(m_3MonthLater);
            if (in3Month && (nLog & REMIND_STATUS_3MON) == 0) {
                nMonth = 3;
            }
        }
        return nMonth;
    }

    public static String getSQL() {
        StringBuffer sbuff = new StringBuffer();
        sbuff.append("SELECT * FROM {this} WHERE");
        sbuff.append(" {this.lStatus} not in(");
        sbuff.append("'").append(ProjectConstants.STATUS_FINISHED).append("',");
        sbuff.append("'").append(ProjectConstants.STATUS_CANCELED).append("',");
        sbuff.append("'").append(ProjectConstants.STATUS_STOPED).append("',");
        sbuff.append("'").append(ProjectConstants.STATUS_APPLY_FINISH_AUDIT).append("',");
        sbuff.append("'").append(ProjectConstants.STATUS_APPLY_FINISH_AUDIT).append("')");
        sbuff.append(" AND (");

        sbuff.append("({this.finishDate}<=? AND {this.finishRemindLog}=0)");//
        sbuff.append(" OR ");
        sbuff.append("({this.finishDate}<=? AND ({this.finishRemindLog}=0 OR {this.finishRemindLog}="
                + REMIND_STATUS_3MON + ") )");//1
        sbuff.append(") AND {this.finishDate}>=now()");//
        sbuff.append(" AND {this.lPrjType}='").append(ProjectConstants.PROJECT_TYPE_V).append("'");//
        sbuff.append(" ORDER BY {this.finishDate}");//
        String sResult_ = sbuff.toString();
        sbuff.setLength(0);
        return sResult_;

    }
}