信息任务

package com.********job;


import com.***********.biss.uls.Logger;


public abstract class Job extends Thread{
static final Logger logger = Logger.getLogger(Job.class);
private JobConfig config;

protected abstract void execute(JobConfig config) throws Throwable;

public void init(JobConfig config){
this.config = config;
}


public void run() {
try {
execute(config);
} catch (Throwable e) {
logger.error(e);
e.printStackTrace();
}
}

}



package com.********.boss.ejb.smssend;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import com.******biss.rds.dao.Dao;
import com.****.biss.uls.Logger;
import com.****boss.ejb.idm.dao.MessageDaoHelper;
import com.****.boss.inf.config.BossConstants;
import com.*****boss.inf.config.SmsConfigHelper;
import com.*****.boss.inf.ds.idm.beans.Message;
import com*****.boss.inf.enumdef.idm.SendStatus;
import com****.job.Job;
import com.g******t.job.JobConfig;



public class SendSms extends Job {


private static Logger logger = Logger.getLogger(SendSms.class);
private final static int poolsize = SmsConfigHelper.getInt(BossConstants.SMS_POOL_SIZE, 1);
private int num = 0;
private int size = 0;
@Override
protected void execute(JobConfig config) throws Throwable {
try {
ExecutorService service = Executors.newFixedThreadPool(poolsize);
while (true) {
List<Message> list = null;
if(num == size) {
list = queryListMessage();
size = list.size();
int len = list.size() / poolsize;
List<Message> list1 = null;
for (int i = 0; i < poolsize; i++) {
if (i == poolsize - 1) {
list1 = list.subList(i * len, list.size());
} else {
list1 = list.subList(i * len, (i + 1) * len);
}
service.submit(new OperationThread(list1, size));
}
}
String interval = config.getParameter("interval");
logger.info("Wait " + interval + " seconds ...");
Thread.sleep(1000 * Integer.parseInt(interval));
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
} catch (Throwable e1) {
logger.error(e1.getMessage(), e1);
}
}


private class OperationThread extends Thread {


private List<Message> list;
private int listSize;


public OperationThread(List<Message> list, int listSize) {
this.list = list;
this.listSize = listSize;
}
public void run() {
try {
sendMessage(list, listSize);
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
}


/**
* 发送短信
* @param list
* @throws Exception
*/
private void sendMessage(List<Message> list, int listSize) throws Exception {
Dao dao = null;
logger.info(new Date() + "-------" + Thread.currentThread().getName() + " 发送条数[" + list.size() + "]条");
Set<Message> set = new HashSet<Message>(list); //list去重处理
for(Message message : set) {
try {
dao = new Dao("default");
logger.info(new Date() + "-------" + Thread.currentThread().getName() + " 发送信息 手机号:" + message.getMobile() + " 短信内容:" + message.getContent() + " 国家码:" + message.getRegion());
//根据国家取对应的网关配置
String gateWayConfig = SmsConfigHelper.getCountryGateway(message.getRegion().toUpperCase());
String serviceUrl = SmsConfigHelper.getGatewayTemplate(gateWayConfig, BossConstants.SMS_GATEWAY_SERVICE);
String from = SmsConfigHelper.getGatewayTemplate(gateWayConfig, BossConstants.SMS_GATEWAY_FROM);
String userName = SmsConfigHelper.getGatewayTemplate(gateWayConfig, BossConstants.SMS_GATEWAY_USERNAME);
String password = SmsConfigHelper.getGatewayTemplate(gateWayConfig, BossConstants.SMS_GATEWAY_PASSWORD);
// 调用短信网关发送短信
// GateWay gateWay = GateWay.valueOf(message.getRegion().toUpperCase());
SMSGatewayAdapter adapter = GatewayFactory.getSMSGateway(GateWay.CN);
adapter.sendSms(message, serviceUrl, from, userName, password);
// 更新发送短信状态
message.setLastModifiedTime(new Date());
message.setSendTime(new Date());
message.setStatus(SendStatus.SENT);
MessageDaoHelper.edit(dao, null, message);
logger.info(new Date() + "-------" + Thread.currentThread().getName() + " 发送信息 手机号:" + message.getMobile() + " 成功");
} catch(Throwable e) {
logger.error("send error:", e);
updateSendFailed(dao, message.getSmsId());
} finally {
num++;
if(num == listSize) {
num = 0;
size = 0;
}
if (dao != null) {
dao.close();
}
}
}
}


/**
* 发送失败的短信,同步更新其发送状态
* @param id
*/
private void updateSendFailed(Dao dao, Long id) {
try {
Message message = MessageDaoHelper.findById(dao, null, id);
message.setStatus(SendStatus.FAILED);
message.setSendTime(new Date());
message.setLastModifiedTime(new Date());
MessageDaoHelper.edit(dao, null, message);
} catch (Throwable e) {
logger.error("更新短信发送状态失败:" + e.getMessage(), e);
}
}
/**
* 查询可发送的短信
* @return
*/
public List<Message> queryListMessage() {
List<Message> listMessage = null;
Dao dao = null;
try {
dao = new Dao("default");
List<Object> params = new ArrayList<Object>();
listMessage = MessageDaoHelper.query(dao, null, "getNeedSendMessage", 0, params);
} catch (Throwable e) {
logger.error(e.getMessage(), e);
} finally {
if (dao != null) {
dao.close();
}
}
return listMessage;
}
}



package com.*****.job;


import java.io.IOException;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


import com.*****.biss.GigasetUtil;
import com.*****.biss.uls.Logger;


public class JobService {
static final Logger logger = Logger.getLogger(JobService.class);

public static void main(String[] args) {
try{
JobService main = new JobService();
NodeList joblist = main.init();
for(int i=0; i<joblist.getLength(); i++){
Node job = joblist.item(i);
main.startJob(job);
}
}catch(Throwable e){
e.printStackTrace();
logger.error(e);
}
}


private NodeList init() throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(GigasetUtil.getConfigPath() + "job-config.xml");
return doc.getDocumentElement().getElementsByTagName("job");
}

private void startJob(Node job){
String jobname = null;
try{
NamedNodeMap jobatts = job.getAttributes();
Node job_name = jobatts.getNamedItem("name");
jobname = job_name.getNodeValue();
Node job_enabled = jobatts.getNamedItem("enabled");
if(job_enabled != null && job_enabled.getNodeValue().equalsIgnoreCase("false"))
return;
Node job_clazz = jobatts.getNamedItem("class");
Class<?> clazz = Class.forName(job_clazz.getNodeValue());
NodeList jobconfig = job.getChildNodes();
for(int i=0; i<jobconfig.getLength(); i++){
Node config = jobconfig.item(i);
if(config.getNodeName().equalsIgnoreCase("init-param")){
JobConfig jobcon = new JobConfig(config);
Job obj_job = (Job)clazz.newInstance();
obj_job.init(jobcon);
obj_job.start();
logger.info("Job [" + jobname + "] start success");
}
}
}catch(Throwable e){
logger.error("Start job [" + jobname + "] faild", e);
}
}
}


package com.*******.boss.ejb.smssend;


import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import com.******.biss.helper.SecurityHelper;
import com.*****.biss.uls.Logger;
import com.*****.boss.inf.ds.basic.PublicRegionHelper;
import com.*****.boss.inf.ds.basic.beans.PublicRegion;
import com.*****.boss.inf.ds.idm.beans.Message;


/**
 * 
 * @Package com.gigaset.boss.ejb.smssend
 * @Class CNSMSGatewayAdapterImpl.java
 * @Description(发送短信)
 * @Author *
 * @Date 2015年5月15日 上午11:30:53
 * @Revision v1.0
 */
public class CNSMSGatewayAdapterImpl implements SMSGatewayAdapter {


static final Logger logger = Logger.getLogger(CNSMSGatewayAdapterImpl.class);


@Override
public void sendSms(Message message, String serviceUrl, String from, String userName, String password) throws Exception {
PublicRegion publicRegion = PublicRegionHelper.localPublicRegionMap.getByName(message.getRegion().toUpperCase());
String to = publicRegion.getPhoneAreaCode() + message.getMobile();
String messagebody = message.getContent();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
TrustManager trustSelfSigned = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
TrustManager[] tms = new TrustManager[] { trustSelfSigned };
sslContext.init(null, tms, null);
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
URL myURL = new URL(serviceUrl);
HttpsURLConnection myURLConnection = (HttpsURLConnection) myURL.openConnection();
try {
myURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
myURLConnection.setHostnameVerifier(hostnameVerifier);
String userCredentials = userName + ":" + password;
String basicAuth = "Basic " + SecurityHelper.base64Encode(userCredentials.getBytes());
myURLConnection.setRequestProperty("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
String urlParameters = "msg=" + messagebody + "&from=" + from + "&to=" + to;
DataOutputStream wr = new DataOutputStream(myURLConnection.getOutputStream());
myURLConnection.getOutputStream().write(urlParameters.getBytes("UTF-8"));
wr.flush();
wr.close();
int respCode = myURLConnection.getResponseCode();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
InputStream in = null;
boolean ret = false;
if (respCode == 200) {
ret = true;
in = myURLConnection.getInputStream();
} else if (respCode >= 400) {
in = myURLConnection.getErrorStream();
} else {
throw new IOException("error response[" + respCode + "]");
}
int c = 0;
while ((c = in.read()) != -1) {
bout.write(c);
}
String respStr = new String(bout.toByteArray(), "UTF-8");
logger.info("respStr: " + respStr);
if (ret == false)
throw new IOException(respStr);
} finally {
myURLConnection.disconnect();
}
} catch (Throwable e) {
logger.error("Send message error: ", e);
throw e;
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值