com.neusoft.mid.clwapi.service.msg.MsgServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.neusoft.mid.clwapi.service.msg.MsgServiceImpl.java

Source

/**
 * @(#)MsgServiceImpl.java 2013-3-25
 *
 * Copyright 2013 Neusoft Group Ltd. All rights reserved.
 * Neusoft PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.neusoft.mid.clwapi.service.msg;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.ext.MessageContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.neusoft.mid.clwapi.common.ErrorConstant;
import com.neusoft.mid.clwapi.common.HttpConstant;
import com.neusoft.mid.clwapi.common.ModCommonConstant;
import com.neusoft.mid.clwapi.common.UserInfoKey;
import com.neusoft.mid.clwapi.entity.msg.CoreMsgInfo;
import com.neusoft.mid.clwapi.entity.msg.DiaoduInfo;
import com.neusoft.mid.clwapi.entity.msg.FindMsgMoldResp;
import com.neusoft.mid.clwapi.entity.msg.MsgMoldInfo;
import com.neusoft.mid.clwapi.entity.msg.MsgMoldReq;
import com.neusoft.mid.clwapi.entity.msg.MsgMoldResp;
import com.neusoft.mid.clwapi.entity.msg.PicCommandInfo;
import com.neusoft.mid.clwapi.entity.msg.PushMsgReceivedInfo;
import com.neusoft.mid.clwapi.entity.oauth.MobileUsrAllInfo;
import com.neusoft.mid.clwapi.exception.common.ApplicationException;
import com.neusoft.mid.clwapi.mapper.MsgMapper;
import com.neusoft.mid.clwapi.mapper.OauthMapper;
import com.neusoft.mid.clwapi.process.delivermsg.SendDeliverMsgService;
import com.neusoft.mid.clwapi.threadpool.MsgSendThreadPool;
import com.neusoft.mid.clwapi.tools.BeanUtil;
import com.neusoft.mid.clwapi.tools.CheckRequestParam;
import com.neusoft.mid.clwapi.tools.JacksonUtils;

/**
 * @author <a href="mailto:majch@neusoft.com">majch </a>
 * @version $Revision 1.0 $ 2013-3-25 ?6:39:47
 */
public class MsgServiceImpl implements MsgService {

    /**
     * .
     */
    private static Logger logger = LoggerFactory.getLogger(ModCommonConstant.LOGGER_NAME);

    @Autowired
    private MsgMapper msgMapper;

    @Autowired
    private OauthMapper oauthMapper;

    @Context
    private MessageContext context;

    @Autowired
    private SendDeliverMsgService sendDeliverMsgService;

    @Resource
    private MsgSendThreadPool msgSendThreadPool;

    /**
     * ?.
     * 
     * @param token
     *            ?.
     * @param ttMsgInfo
     *            ?.
     * @return ?.
     */
    @Override
    public Response sendTtMsg(String token, String ttMsgInfo) {
        logger.info("???");

        DiaoduInfo ttMsg = JacksonUtils.fromJsonRuntimeException(ttMsgInfo, DiaoduInfo.class);
        if (null == ttMsg || StringUtils.isEmpty(StringUtils.strip(ttMsg.getVins()))
                || StringUtils.isEmpty(StringUtils.strip(ttMsg.getMsg()))
                || StringUtils.isEmpty(StringUtils.strip(ttMsg.getType()))) {
            logger.info("??");
            throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
        } else {
            CoreMsgInfo msgInfo = new CoreMsgInfo();
            msgInfo.setVin(ttMsg.getVins());
            msgInfo.setType(parseTtmsgType(ttMsg.getType()));
            msgInfo.setMsg(ttMsg.getMsg());
            msgInfo.setUserId(context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID));

            // ????.
            msgSendThreadPool.executeSendMtMsgThread(msgInfo, msgMapper, sendDeliverMsgService);

            // ????.
            return Response.ok().header(HttpHeaders.CACHE_CONTROL, "no-store").header("Pragma", "no-cache").build();
        }

    }

    /**
     * ???.
     * 
     * @param reqTypeCont
     * @return
     */
    private String parseTtmsgType(String reqTypeCont) {
        StringBuffer strBuff = new StringBuffer();
        String setinfo0 = "0";
        String setinfo1 = "0";
        String setinfo2 = "0";
        String setinfo3 = "0";
        String[] typeArray = StringUtils.split(StringUtils.strip(reqTypeCont), "|");
        for (String set : typeArray) {
            String type = StringUtils.strip(set);
            if ("00".equals(type)) {
                // 00
                setinfo3 = "1";
            } else if ("01".equals(type)) {
                // 00
                setinfo1 = "1";
            } else if ("02".equals(type)) {
                // 00?
                setinfo0 = "1";
            } else if ("03".equals(type)) {
                // 00
                setinfo2 = "1";
            } else {
                logger.info("??:" + type + "??");
                throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
            }
        }
        strBuff.append(setinfo0).append(setinfo1).append(setinfo2).append(setinfo3).append("0000");
        String msgType = strBuff.toString();
        logger.info("???:" + msgType);
        return msgType;
    }

    /**
     * ??.
     * 
     * @param token
     *            ?.
     * @param photoInfo
     *            ??.
     * @return ??.
     */
    @Override
    public Response sendPhotoMsg(String token, String photoInfo) {
        logger.info("???");

        PicCommandInfo picCommand = JacksonUtils.fromJsonRuntimeException(photoInfo, PicCommandInfo.class);
        if (null == picCommand || StringUtils.isEmpty(StringUtils.strip((picCommand.getVins())))
                || StringUtils.isEmpty(StringUtils.strip((picCommand.getType())))) {
            logger.info("??");
            throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
        } else {
            //????
            checkPicChannel(picCommand.getType());
            /*????,
            client_id?????*/
            MobileUsrAllInfo usrInfo = oauthMapper.getValidUsrBindInfo(token);
            if (null == usrInfo) {
                logger.info("token??");
                return Response.status(Response.Status.UNAUTHORIZED).entity(ErrorConstant.ERROR20001.toJson())
                        .header("Content-Type", "application/json;charset=UTF-8").build();
            } else {
                CoreMsgInfo msgInfo = new CoreMsgInfo();
                msgInfo.setVin(picCommand.getVins());
                msgInfo.setType(picCommand.getType());

                // ????.
                msgSendThreadPool.executeSendPhotoThread(msgInfo, usrInfo, msgMapper, sendDeliverMsgService);
                // ????.
                return Response.ok().header(HttpHeaders.CACHE_CONTROL, "no-store").header("Pragma", "no-cache")
                        .build();
            }
        }
    }

    /**
     * ????.
     * @param reqChannel
     */
    public void checkPicChannel(String reqChannel) {
        String[] channelArray = StringUtils.split(StringUtils.strip(reqChannel), "|");
        for (String channelTemp : channelArray) {
            if (!("1".equals(channelTemp) || "2".equals(channelTemp) || "3".equals(channelTemp)
                    || "4".equals(channelTemp))) {
                throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
            }
        }
    }

    /**
     * ???.
     * 
     * @param token
     *            ?.
     * @param remark
     *            ??.
     * @return ???.
     */
    @Override
    public String addMsgMold(String token, String remark) {
        MsgMoldReq req = JacksonUtils.fromJsonRuntimeException(remark, MsgMoldReq.class);
        try {
            BeanUtil.checkObjectLegal(req);
        } catch (Exception e) {
            logger.error("??-???" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
        }

        String userId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);
        if (CheckRequestParam.isEmpty(userId)) {
            logger.info("??-ID");
            throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
        }

        logger.info("??-?????");
        MsgMoldInfo obj = new MsgMoldInfo();
        obj.setUserId(userId);
        obj.setRemark(req.getTtmsg_remark());
        msgMapper.insertMsgMoldInfo(obj);

        logger.info("??-??");
        obj = msgMapper.getMsgMoldInfo(obj);
        if (CheckRequestParam.isEmpty(obj)) {
            logger.info("??-insert????");
            throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
        }

        logger.info("??-??ETag");
        upUserETag(token, userId, obj.getEditT());

        MsgMoldResp result = new MsgMoldResp();
        result.setId(obj.getId());
        result.setEditT(obj.getEditT());
        return JacksonUtils.toJsonRuntimeException(result);

    }

    /**
     * ???.
     * 
     * @param token
     *            ?.
     * @param tempId
     *            ??ID.
     * @param remark
     *            ???.
     * @return ETag.
     */
    @Override
    public String eidtMsgMold(String token, String tempId, String remark) {
        tempId = StringUtils.strip(tempId);

        MsgMoldReq req = JacksonUtils.fromJsonRuntimeException(remark, MsgMoldReq.class);
        try {
            BeanUtil.checkObjectLegal(req);
        } catch (Exception e) {
            logger.error("??-???" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
        }

        String userId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);
        if (CheckRequestParam.isEmpty(userId)) {
            logger.info("??-ID");
            throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
        }

        int num = msgMapper.getMsgMoldCount(tempId, userId);
        if (num == 0) {
            logger.info("??-?" + tempId + "?");
            throw new ApplicationException(ErrorConstant.ERROR10010, Response.Status.NOT_FOUND);
        }

        logger.info("??-??");
        MsgMoldInfo obj = new MsgMoldInfo();
        obj.setId(tempId);
        obj.setUserId(userId);
        obj.setRemark(req.getTtmsg_remark());
        msgMapper.updateUserMsgMold(obj);

        logger.info("??-??");
        obj = msgMapper.getMsgMoldInfo(obj);
        if (CheckRequestParam.isEmpty(obj) || CheckRequestParam.isEmpty(obj.getId())) {
            logger.info("??-?" + tempId + "?");
            throw new ApplicationException(ErrorConstant.ERROR10010, Response.Status.NOT_FOUND);
        }

        logger.info("??-??ETag");
        upUserETag(token, userId, obj.getEditT());

        MsgMoldResp result = new MsgMoldResp();
        result.setEditT(obj.getEditT());
        return JacksonUtils.toJsonRuntimeException(result);
    }

    /**
     * ???.
     * 
     * @param token
     *            ?.
     * @param tempId
     *            ??ID.
     * @return ETag.
     */
    @Override
    public String delMsgMold(String token, String tempId) {
        tempId = StringUtils.strip(tempId);
        String userId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);
        if (CheckRequestParam.isEmpty(userId)) {
            logger.info("??-ID");
            throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
        }

        int num = msgMapper.getMsgMoldCount(tempId, userId);
        if (num == 0) {
            logger.info("??-?" + tempId + "?");
            throw new ApplicationException(ErrorConstant.ERROR10010, Response.Status.NOT_FOUND);
        }

        logger.info("??-??");
        MsgMoldInfo obj = new MsgMoldInfo();
        obj.setId(tempId);
        obj.setUserId(userId);
        obj.setDelFlag("1");
        msgMapper.updateUserMsgMold(obj);

        logger.info("??-??");
        obj = msgMapper.getMsgMoldInfo(obj);
        if (CheckRequestParam.isEmpty(obj) || CheckRequestParam.isEmpty(obj.getId())) {
            logger.info("??-?" + tempId + "?");
            throw new ApplicationException(ErrorConstant.ERROR10010, Response.Status.NOT_FOUND);
        }

        logger.info("??-??ETag");
        upUserETag(token, userId, obj.getEditT());

        MsgMoldResp result = new MsgMoldResp();
        result.setEditT(obj.getEditT());
        return JacksonUtils.toJsonRuntimeException(result);
    }

    /**
     * ??ETag?.
     * 
     * @param usrID
     *            ID.
     * @param ETag
     *            .
     * @return
     */
    /**
     * ???. edit by majch,mybatis?.
     * 
     * @param token
     *            ??.
     * @param userID
     *            ID
     * @param ETag
     *            ???.
     */
    private void upUserETag(String token, String userID, String ETag) {
        oauthMapper.updateUserTemplateEtag(token, ETag, userID);
    }

    /**
     * ???
     * 
     * @param token
     *            ?.
     * @param eTag
     *            
     * @return ???.
     */
    @Override
    public Object getMsgMold(String token, String eTag) {
        // ??
        boolean checkEtag = true;
        // ?ID
        String usrId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);
        String plaETag = context.getHttpHeaders().getHeaderString(UserInfoKey.RULE_ETAG);
        logger.info("????");
        logger.info("?ETag:" + eTag);
        logger.info("??ETag:" + plaETag);
        // ?
        Date dateTer = null;
        // ??
        Date datePla = null;
        // ?
        if (eTag == null) {
            logger.error("If-None-Match");
            throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
        }

        if (!eTag.equals(HttpConstant.TIME_ZERO)) {
            try {
                dateTer = BeanUtil.checkTimeForm(eTag, HttpConstant.TIME_FORMAT);
            } catch (ParseException e) {
                logger.error("??" + e.getMessage());
                throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
            }
        } else {
            // ???
            checkEtag = false;
        }

        // ??
        List<MsgMoldInfo> list = msgMapper.getMsgMoldInfoWithUsr(usrId);

        // ???
        if (list == null || list.size() == 0) {
            logger.info("???");
            return Response.notModified().build();
        } else {
            // ??
            String e = list.get(0).getEditT();
            // ?
            if (!StringUtils.equals(e, plaETag)) {
                logger.info("?");
                // ??ETag
                upUserETag(token, usrId, e);
                plaETag = e;
            }
        }

        // ??
        try {
            datePla = BeanUtil.checkTimeForm(plaETag, HttpConstant.TIME_FORMAT);
        } catch (ParseException e) {
            logger.error("???" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
        }

        // ??NO_CONTENT
        if ((list == null || list.size() == 0) && !plaETag.equals(HttpConstant.ZERO)) {
            logger.info("??");
            return Response.noContent().build();
        } else if (checkEtag && dateTer.compareTo(datePla) == 0) {
            // ??
            logger.info("???");
            return Response.notModified().build();
        } else if (checkEtag && dateTer.compareTo(datePla) > 0) {
            logger.error("???");
            throw new ApplicationException(ErrorConstant.ERROR10103, Response.Status.BAD_REQUEST);
        }

        // ?
        List<MsgMoldInfo> temp = new ArrayList<MsgMoldInfo>();
        // ????
        Iterator<MsgMoldInfo> it = list.iterator();
        while (it.hasNext()) {
            MsgMoldInfo iMsgMoldInfo = it.next();
            // ??
            if (iMsgMoldInfo.getDel().equals(HttpConstant.MSGMOLD_DEL_FALSE)) {
                temp.add(iMsgMoldInfo);
            }
        }

        FindMsgMoldResp iFindMsgMoldResp = new FindMsgMoldResp();
        iFindMsgMoldResp.setEtag(plaETag);
        iFindMsgMoldResp.setList(temp);
        return JacksonUtils.toJsonRuntimeException(iFindMsgMoldResp);
    }

    /**
     * ????
     * @author majch. 
     * @param token
     *            ?.
     * @param msg
     *            ??.
     * @return ???.
     */
    @Override
    public Object pushMsgReceived(String token, String msg) {
        logger.info("[???]?");
        // ?ID?.
        String userId = context.getHttpHeaders().getHeaderString(UserInfoKey.USR_ID);

        PushMsgReceivedInfo msgInfo = JacksonUtils.fromJsonRuntimeException(msg, PushMsgReceivedInfo.class);
        if (StringUtils.isEmpty(msgInfo.getClientId()) || StringUtils.isEmpty(msgInfo.getMsgType())
                || StringUtils.isEmpty(msgInfo.getMsgId())) {
            logger.error("??");
            throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
        } else {
            if ("01".equals(msgInfo.getMsgType())) {
                logger.info("???:?");
                msgMapper.updateAlarmPushMsgReceived(msgInfo.getMsgId(), userId, msgInfo.getClientId());
            } else if ("02".equals(msgInfo.getMsgType())) {
                logger.info("???:?");
                msgMapper.updatePicPushMsgReceived(msgInfo.getMsgId(), userId, msgInfo.getClientId());
            } else if ("03".equals(msgInfo.getMsgType())) {
                logger.info("???:");
                msgMapper.updateNewPushMsgReceived(msgInfo.getMsgId(), userId, msgInfo.getClientId());
            } else {
                logger.error("?[msgType]?");
                throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
            }
        }
        return Response.ok().build();
    }

}