极光推送

来源:互联网 发布:常见的网络诈骗有 编辑:程序博客网 时间:2024/05/18 15:22
package com.jsecode.esb.web.action;import java.util.ArrayList;import java.util.List;import com.jsecode.esb.model.mempo.PushMsg;import com.jsecode.esb.model.protocol.jpush.PushResponse;import cn.jiguang.common.ClientConfig;import cn.jiguang.common.resp.APIConnectionException;import cn.jiguang.common.resp.APIRequestException;import cn.jiguang.common.resp.ResponseWrapper;import cn.jpush.api.JPushClient;import cn.jpush.api.push.PushResult;import cn.jpush.api.push.model.Platform;import cn.jpush.api.push.model.PushPayload;import cn.jpush.api.push.model.audience.Audience;import cn.jpush.api.push.model.notification.Notification;public class JGPushMsg {private final static String APP_KEY;private final static String MASTER_SECRET;private static JPushClient jPushClient;static {APP_KEY = "d4d6faf05f6582f07bbc72ad";// jPushProp.get(APP_KEY);MASTER_SECRET = "08163a439cee5045c42bb797";// jPushProp.get(MASTER_SECRET);jPushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());}/* * public static void sentMessage(List<PushMsg> listMsg) { List<PushPayload> * listPushPayLoad = toPushPayload(listMsg); try { for(PushPayload * pushPayLoad : listPushPayLoad) { jPushClient.sendPush(pushPayLoad); } } * catch (APIConnectionException e) { e.printStackTrace(); } catch * (APIRequestException e) { e.printStackTrace(); } } */public static List<PushResponse<PushResult>> sentMessage(List<PushMsg> listMsg) {List<PushResponse<PushResult>> listJPushResp = new ArrayList<PushResponse<PushResult>>();for (PushMsg pushMsg : listMsg) {listJPushResp.add(doSend(pushMsg));// 设置一秒发送一个,因为频率太高,会发送失败waiting(1000);}return listJPushResp;}public static void waiting(long millis) {try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}private static PushResponse<PushResult> doSend(PushMsg pushMsg) {PushResult pushResult = null;try {pushResult = jPushClient.sendPush(buildPushObject_all_alias_alert(pushMsg));} catch (APIRequestException e) {e.printStackTrace();ResponseWrapper wrapper = new ResponseWrapper();wrapper.responseCode = e.getErrorCode();wrapper.responseContent = e.getErrorMessage();pushResult = new PushResult();pushResult.setResponseWrapper(wrapper);} catch (Exception e) {e.printStackTrace();ResponseWrapper wrapper = new ResponseWrapper();wrapper.responseCode = 500;wrapper.responseContent = e.getMessage();pushResult = new PushResult();pushResult.setResponseWrapper(wrapper);}return new PushResponse<PushResult>(pushResult, pushMsg);}private static PushPayload buildPushObject_all_alias_alert(PushMsg pushMsg) {return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(pushMsg.getAppusername())).setNotification(Notification.alert(pushMsg.getMsgContent())).build();}public static void main(String[] args) {/* * JGPushMsgConfig config = new JGPushMsgConfig(); * config.setAppKey("d4d6faf05f6582f07bbc72ad"); * config.setMasterSecret("08163a439cee5045c42bb797"); * config.setPlatform(Platform.all()); *  * JGPushMsg msg = config.createJSPushMsg(); *  * msg.setContent("内容"); msg.addReceivers(List); msg.addReceiver(xx) *  * msg.send(); *  * if (JGPushMsg.sendToAllAndroid(list,"公务车", "hello", * "this is a ios Devtest", "") == 1) { System.out.println("success"); } */List<PushMsg> pushMsg = new ArrayList<PushMsg>();PushMsg pm = new PushMsg();pm.setMsgQueueId((long) 123);// pm.setAppusername("kk");pm.setAppusername("superuser");pm.setMsgContent("XXX");pushMsg.add(pm);JGPushMsg.sentMessage(pushMsg);}}

package com.jsecode.esb.threadwork.thread;import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;import javax.annotation.Resource;import com.alibaba.fastjson.JSONObject;import com.jsecode.esb.model.mempo.PushMsg;import com.jsecode.esb.model.protocol.jpush.PushResponse;import com.jsecode.esb.service.IMessageService;import com.jsecode.esb.web.action.JGPushMsg;import com.jsecode.platform.timer.WorkThread;import com.jsecode.platform.util.FastJsonHelper;import com.jsecode.platform.util.Util;import cn.jpush.api.push.PushResult;public class JpushTableRefreshThread extends WorkThread {@Resource(name = "messageService")    private IMessageService messageService;public JpushTableRefreshThread(){        this(60);    }        public JpushTableRefreshThread(int threadSleepSecond){        super("消息数据刷新工作线程", threadSleepSecond);    }@Overrideprotected void working() throws Exception {// 获取所有未推送的消息        List<PushMsg> receivers = messageService.searchAllUnpushedMsgReceivers();        if(Util.isEmpty(receivers)) {            return;        }        Date date = new Date();        //List<MsgInfo> serviceMsgs = new ArrayList<MsgInfo>();        List<PushMsg> pushedReceivers = new ArrayList<PushMsg>();        int i = 0;        for(PushMsg msg : receivers){        // 单次最多推送50条            if(i == 50) {                break;            }        //设为已推送            msg.setProcessed((short) 1);            msg.setProcessedTime(date);            //MsgInfo serviceMsg = new MsgInfo();            String content;            try{                content = createContent(msg);                msg.setMsgContent(content);            }catch(Exception e){                continue;            }            //serviceMsg.setMSG_CONTENT(content);            //serviceMsgs.add(serviceMsg);            pushedReceivers.add(msg);            i++;        }                // 调用极光进行推送        /*JPushClient jPushClient = new JPushClient();        jPushClient.setAppKey("d4d6faf05f6582f07bbc72ad");        jPushClient.setMasterSecret("08163a439cee5045c42bb797");        jPushClient.setPlatform(Platform.all());*/                        //JGPushMsg.sentMessage(pushedReceivers);        List<PushResponse<PushResult>> listJPushResp = JGPushMsg.sentMessage(pushedReceivers);        // 推送成功后插入推送记录, 更新处理状态        messageService.processAfterPushMessageFor(listJPushResp);                }private String createContent(PushMsg msg) throws Exception{        //MsgContent contentObj = new MsgContent();//contentObj.setContent(content);        //return FastJsonHelper.toJSONString(contentObj);        String content = getContent(msg.getMsgContent());                return content;    }private String getContent(String content) throws IOException{        JSONObject json = FastJsonHelper.parseObject(content);        JSONObject aps = json.getJSONObject("aps");        return aps.getString("alert");    }    class MsgContent {        private String content;        private String sendTime;        private String type;        private String appcode;        private String version;        private String address;        private String pushtype;        private String msgflag;        private String subtitle;        private String suburl;        private String priority;        private String usertype;        private String users;        public String getContent(){            return content;        }        public void setContent(String content){            this.content = content;        }        public String getSendTime(){            return sendTime;        }        public void setSendTime(String sendTime){            this.sendTime = sendTime;        }        public String getType(){            return type;        }        public void setType(String type){            this.type = type;        }        public String getAppcode(){            return appcode;        }        public void setAppcode(String appcode){            this.appcode = appcode;        }        public String getVersion(){            return version;        }        public void setVersion(String version){            this.version = version;        }        public String getAddress(){            return address;        }        public void setAddress(String address){            this.address = address;        }        public String getPushtype(){            return pushtype;        }        public void setPushtype(String pushtype){            this.pushtype = pushtype;        }        public String getMsgflag(){            return msgflag;        }        public void setMsgflag(String msgflag){            this.msgflag = msgflag;        }        public String getSubtitle(){            return subtitle;        }        public void setSubtitle(String subtitle){            this.subtitle = subtitle;        }        public String getSuburl(){            return suburl;        }        public void setSuburl(String suburl){            this.suburl = suburl;        }        public String getPriority(){            return priority;        }        public void setPriority(String priority){            this.priority = priority;        }        public String getUsertype(){            return usertype;        }        public void setUsertype(String usertype){            this.usertype = usertype;        }        public String getUsers(){            return users;        }        public void setUsers(String users){            this.users = users;        }    }}void processAfterPushMessageFor(List<PushResponse<PushResult>> listResponse);public void processAfterPushMessageFor(List<PushResponse<PushResult>> listResponse) {                List<PushMsg> listPushMsg = new ArrayList<PushMsg>();        // 推送成功后插入推送记录        for(PushResponse<PushResult> response : listResponse){            listPushMsg.add(response.getMsg());                        PushMsg msg = response.getMsg();                        MsgPushRecord record = new MsgPushRecord();            if(Util.isNotEmpty(msg.getMsgQueueId())){                record.setMsgQueueId(msg.getMsgQueueId());            }            if(Util.isNotEmpty(msg.getSubject())){                record.setMsgSubject(msg.getSubject());            }            if(Util.isNotEmpty(msg.getMsgContent())){                record.setMsgContent(msg.getMsgContent());            }            if(Util.isNotEmpty(msg.getMsgType())){                record.setMsgType(msg.getMsgType());            }            if(Util.isNotEmpty(msg.getReceiverUserId())){                record.setMsgReceiver(msg.getReceiverUserId());            }            if(Util.isNotEmpty(msg.getMsgCreateUserId())){                record.setMsgCreateUserid(msg.getMsgCreateUserId());            }            if(Util.isNotEmpty(msg.getMsgCreateTime())){                record.setMsgCreateTime(msg.getMsgCreateTime());            }            record.setMsgHasFile((short) 0);            if(Util.isNotEmpty(msg.getProcessedTime())){                record.setPushTime(msg.getProcessedTime());            }            record.setReturnCode(response.getResult().getResponseCode());            record.setReturnMsg(response.getResult().getOriginalContent());            record.setRepeatPushTimes(1);                        msgPushRecordDAO.save(record);                        if(Util.isNotEmpty(record.getPushId())){                msg.setPushId(record.getPushId());            }                    }                // 推送成功后更新处理状态        msgPushQueueDetailDAO.updateMsgProcessed(listPushMsg);    }
public void updateMsgProcessed(List<PushMsg> receivers);

public void updateMsgProcessed(final List<PushMsg> receivers){    final String sql = "update msg_push_queue_detail set processed = ?, processed_time = ?, push_id = ? where detail_id = ?";        getHibernateTemplate().getSessionFactory().openSession().doWork(new Work(){        @Override        public void execute(Connection connection) throws SQLException{            PreparedStatement statement = connection.prepareStatement(sql);            for (PushMsg msg : receivers) {                statement.setInt(1, msg.getProcessed());                statement.setTimestamp(2, new Timestamp(msg.getProcessedTime().getTime()));                statement.setLong(3, msg.getPushId());                statement.setLong(4, msg.getDetailId());                statement.addBatch();            }            statement.executeBatch();        }    });}



原创粉丝点击