apzl_leasing/src_tenwa/com/tenwa/message/QuartzJobMsg.java

294 lines
12 KiB
Java

package com.tenwa.message;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jbo.com.tenwa.lease.comm.LB_SMS_NOTICE_TASKS;
import jbo.sys.MSG_CONFIG;
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.ListenerManager;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;
import com.amarsoft.are.jbo.BizObject;
import com.amarsoft.are.jbo.BizObjectManager;
import com.amarsoft.are.jbo.JBOException;
import com.amarsoft.are.jbo.JBOFactory;
import com.amarsoft.are.jbo.JBOTransaction;
import com.amarsoft.awe.util.ASResultSet;
import com.amarsoft.awe.util.SqlObject;
import com.amarsoft.awe.util.Transaction;
import com.tenwa.quartz.DateUtil;
import com.tenwa.quartz.JobListenerImpl;
import com.tenwa.quartz.TriggerListenerImpl;
import com.tenwa.reckon.util.UUIDUtil;
public class QuartzJobMsg implements Job{
public static final String MSG_GROUP_NAME = "MSG_DEFAULT_GROUP";
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JBOTransaction tx = null;
try{
tx= JBOFactory.createJBOTransaction();
Transaction tran = Transaction.createTransaction(tx);
Scheduler sch = StdSchedulerFactory.getDefaultScheduler();
Trigger trigger = context.getTrigger();
JobDetail detail = sch.getJobDetail(trigger.getJobKey());
JobDataMap data = detail.getJobDataMap();
//获取主键
String id = data.getString("id");
//获取sql语句
String msgsql = data.getString("msgSql");
//获取关键字
String msgsqlparam = data.getString("msgsqlparam");
//获取短信内容
String msgcontent = data.getString("msgcontent");
//获取触发方式
String triggermode = data.getString("triggermode");
//获取短信发送时间类型、短信延迟发送天数、短信发送时间点
String msgsendtype = data.getString("msgsendtype");//短信发送类型
String msgsendtime = "";//短信发送时间点
Date timeSet = null;
boolean checkTime = false;
Date timeNow = new Date();
if(data.getString("msgsendtime") != null){
msgsendtime = data.getString("msgsendtime");
timeSet = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd").format(timeNow)+" "+msgsendtime);
}
String delayday = "";//延迟发送天数
if(data.getString("delayday") != null){
delayday = data.getString("delayday");
}
//获得过期是否执行
String isoverdateexecute = data.getString("isoverdateexecute");
//获取短信类型
String msgtype = data.getString("msgType");
//获取是否按日期去重
String isrepatebydate = data.getString("isrepeatbydate");
//获取短信替换参数
int oldlength = msgcontent.length();
int newlength = msgcontent.replace("}", "").length();
String[] params = new String[oldlength-newlength];
if(params.length>0){
int index = 0;
for(int i=0;i<params.length;i++){
int start = msgcontent.indexOf("{", index);
int end = msgcontent.indexOf("}", index);
params[i] = msgcontent.substring(start+1, end);
index = end+1;
}
}
JBOFactory.getBizObjectManager(MSG_CONFIG.CLASS_NAME,tx).createQuery("update O set previous_fire_time='"+DateUtil.getDateTime(trigger.getPreviousFireTime())+"',next_fire_time='"+DateUtil.getDateTime(trigger.getNextFireTime())+"' where id='"+id+"'");
ASResultSet result = tran.getASResultSet(new SqlObject(msgsql));
while(result.next()){
boolean flag = false;
for(int p=0;p<params.length;p++){
if(result.getString(params[p]) == null){
flag = true;
}
}
if(flag){
continue;
}
String resultMsgContent = msgcontent;
Object phonenumber = result.getString("phonenumber");
if(phonenumber == null || phonenumber.toString().length() != 11){
continue;
}
String sql = "select * from msg_send_relative where 1=1 ";
String[] sqlparams = msgsqlparam.split("&");
if(sqlparams.length>0){
for(int i=0;i<sqlparams.length;i++){
sql += "and "+sqlparams[i]+"='"+result.getString(sqlparams[i]).toString()+"' ";
}
}
if(isrepatebydate.equals("yes")){//根据日期去重
sql+= "and inputtime='"+result.getString("checkdate")+"'";
}
if(msgtype.startsWith("holiday") || msgtype.startsWith("birthday")){//如果是生日祝福和节假日祝福必须添加短信类型和日期条件筛选
sql += "and msg_type='"+msgtype+"' and inputtime='"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"'";
}else{
sql += "and msg_type='"+msgtype+"'";
}
sql = sql.replaceAll(":", "");
SqlObject so = new SqlObject(sql);
so.setRunSql(so.getRunSql().replaceAll("", ":"));
ASResultSet msgSend = tran.getASResultSet(so);
if(!msgSend.next()){
for(int i=0;i<params.length;i++){
resultMsgContent = resultMsgContent.replace(params[i], result.getString(params[i]));
}
resultMsgContent = resultMsgContent.replace("{", "");
resultMsgContent = resultMsgContent.replace("}", "");
//创建短信发送记录
BizObjectManager bomLSNT = JBOFactory.getBizObjectManager(LB_SMS_NOTICE_TASKS.CLASS_NAME,tx);
BizObject sn = bomLSNT.newObject();
sn.setAttributeValue("inputuserid", result.getString("proj_manage")!=null?result.getString("proj_manage"):data.getString("userID"));
sn.setAttributeValue("customer_id", result.getString("customer_id"));
sn.setAttributeValue("phone_number", phonenumber.toString());
//sn.setAttributeValue("phone_number", "13718374615");
sn.setAttributeValue("send_flag", 0);
sn.setAttributeValue("sms_content", resultMsgContent);
sn.setAttributeValue("sms_type", "DELAYED");
sn.setAttributeValue("inputtime", DateUtil.getDateTime(new Date()));
bomLSNT.saveObject(sn);
//关联表生成记录
String insertSql = "insert into msg_send_relative (id,sms_id,msg_type,column) values('"+UUIDUtil.getUUID()+"','"+sn.getAttribute("ID").getString()+"','"+msgtype+"',data)";
String column = "";
String value = "";
for(int m=0;m<sqlparams.length;m++){
column += ","+sqlparams[m];
value += ",'"+result.getString(sqlparams[m]).toString()+"'";
}
column = column.substring(1, column.length());
value = value.substring(1,value.length());
if(msgtype.startsWith("holiday") || msgtype.startsWith("birthday")){
column += ",inputtime";
value += ",'"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"'";
}
if(isrepatebydate.equals("yes")){//根据日期去重
column += ",inputtime";
value += ",'"+result.getString("checkdate")+"'";
}
if("trigger_mode02".equals(triggermode)){//手动触发,不需要定时代理
continue;
}
//拼接短信发送定时代理
String jobName = UUIDUtil.getUUID();
String triggerName = UUIDUtil.getUUID();
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("smsnoticeid", sn.getAttribute("ID").getString());
Class jobClass = Class.forName("com.tenwa.message.JobSendMessage");
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, MSG_GROUP_NAME)
.usingJobData(new JobDataMap(dataMap)).requestRecovery("1".equals(isoverdateexecute)?true:false).storeDurably(false).build();
Date startTime = DateUtil.getTimeByFormat(DateUtil.getDateTime(new Date()), "yyyy-MM-dd HH:mm:ss");
//动态创建时间表达式
String cron = "";
Calendar ca = Calendar.getInstance();
ca.setTime(new Date());
if(timeSet != null){
if(timeSet.compareTo(timeNow) <= 0){
checkTime = true;
}
cron += msgsendtime.split(":")[2]+" ";
cron += msgsendtime.split(":")[1]+" ";
cron += msgsendtime.split(":")[0]+" ";
if(checkTime){
cron = "";
String tNow = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date().getTime()+2000));
cron += tNow.split(":")[2]+" ";
cron += tNow.split(":")[1]+" ";
cron += tNow.split(":")[0]+" ";
}
}
CronExpression ce = null;
column += ",msg_send_jobname,msg_send_triggername";
value += ",'"+jobName+"','"+triggerName+"'";
insertSql = insertSql.replace("column", column);
insertSql = insertSql.replace("data", value);
insertSql = insertSql.replaceAll(":", "");
SqlObject soInsert = new SqlObject(insertSql);
soInsert.setRunSql(soInsert.getRunSql().replaceAll("", ":"));
tran.executeSQL(new SqlObject(insertSql));
switch(msgsendtype){
case "msg_time_type01"://当天立即
cron = "";
String tNow = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date().getTime()+2000));
cron += tNow.split(":")[2]+" ";
cron += tNow.split(":")[1]+" ";
cron += tNow.split(":")[0]+" ";
cron += ca.get(Calendar.DAY_OF_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
sn.setAttributeValue("sms_type", "IMMEDIATELY");
break;
case "msg_time_type02"://当天指定时间
cron += ca.get(Calendar.DAY_OF_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
case "msg_time_type03"://本周最后一天
cron += ca.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(8*24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
case "msg_time_type04"://本月最后一天
cron += ca.getActualMaximum(Calendar.DAY_OF_MONTH)+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(31*24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
case "msg_time_type05"://延迟天
cron += (ca.get(Calendar.DAY_OF_MONTH)+Integer.parseInt(delayday))+" ";
cron += (ca.get(Calendar.MONTH)+1)+" ? *";
ce = new CronExpression(cron);
trigger = TriggerBuilder.newTrigger().forJob(jobName, MSG_GROUP_NAME).withIdentity(triggerName, MSG_GROUP_NAME).startAt(startTime).endAt(new Date(new Date().getTime()+(Integer.parseInt(delayday)*24*60*60*1000)))
.withSchedule(CronScheduleBuilder.cronSchedule(ce).withMisfireHandlingInstructionDoNothing())
.build();
getScheduler().scheduleJob(jobDetail,trigger);
break;
}
sn.setAttributeValue("notice_time", DateUtil.getDateTime(ce.getNextValidTimeAfter(startTime)));
ListenerManager lm = sch.getListenerManager();
KeyMatcher<JobKey> keyMetcher = KeyMatcher.keyEquals(JobKey.jobKey(jobName, MSG_GROUP_NAME));
lm.addJobListener(new JobListenerImpl(), keyMetcher);
bomLSNT.saveObject(sn);
}
}
tx.commit();
} catch (Exception e) {
e.printStackTrace();
try {
tx.rollback();
} catch (JBOException e1) {
e1.printStackTrace();
}
}
}
public Scheduler getScheduler() throws Exception
{
return StdSchedulerFactory.getDefaultScheduler();
}
}