com.gamewin.weixin.web.api.ApiListController.java Source code

Java tutorial

Introduction

Here is the source code for com.gamewin.weixin.web.api.ApiListController.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.gamewin.weixin.web.api;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.gamewin.weixin.entity.Game;
import com.gamewin.weixin.entity.GameCode;
import com.gamewin.weixin.entity.HistoryWeixin;
import com.gamewin.weixin.entity.ManageQRcode;
import com.gamewin.weixin.service.account.AccountService;
import com.gamewin.weixin.service.game.GameService;
import com.gamewin.weixin.service.task.ManageQRcodeService;
import com.gamewin.weixin.service.task.ManageTaskService;
import com.gamewin.weixin.util.InputMessage;
import com.gamewin.weixin.util.MobileContants;
import com.gamewin.weixin.util.OutputMessage;
import com.gamewin.weixin.util.SHA1;
import com.gamewin.weixin.util.SerializeXmlUtil;
import com.thoughtworks.xstream.XStream;

@Controller
@RequestMapping(value = "/api")
public class ApiListController {
    private String Token = "DU2qERxP";

    @Autowired
    private ManageQRcodeService manageQRcodeService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ManageTaskService manageTaskService;
    @Autowired
    private GameService gameService;

    @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
    public void list(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("chat");
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            System.out.println(signature);
            System.out.println(timestamp);
            System.out.println(nonce);
            System.out.println(echostr);
            if (!StringUtils.isEmpty(signature) && !StringUtils.isEmpty(timestamp) && !StringUtils.isEmpty(nonce)
                    && !StringUtils.isEmpty(echostr))
                access(request, response);
        } else {
            // POST??
            System.out.println("enter post");
            try {
                // ??
                acceptMessage(request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * ?URL
     * 
     * @author morning
     * @date 2015217 ?10:53:07
     * @param request
     * @param response
     * @return String
     */
    private String access(HttpServletRequest request, HttpServletResponse response) {
        // ?URL
        System.out.println("?access");
        String signature = request.getParameter("signature");// ??
        String timestamp = request.getParameter("timestamp");// 
        String nonce = request.getParameter("nonce");// ?
        String echostr = request.getParameter("echostr");// ?
        List<String> params = new ArrayList<String>();
        params.add(Token);
        params.add(timestamp);
        params.add(nonce);
        // 1. token?timestamp?nonce???
        Collections.sort(params, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        // 2. ??sha1
        String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
        if (temp.equals(signature)) {
            try {
                response.getWriter().write(echostr);
                System.out.println("? echostr" + echostr);
                return echostr;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(" ?");
        return null;
    }

    private void acceptMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // ??
        ServletInputStream in = request.getInputStream();
        // POST??XStream
        XStream xs = SerializeXmlUtil.createXstream();
        xs.processAnnotations(InputMessage.class);
        xs.processAnnotations(OutputMessage.class);
        // xml?
        xs.alias("xml", InputMessage.class);
        // ??
        StringBuilder xmlMsg = new StringBuilder();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            xmlMsg.append(new String(b, 0, n, "UTF-8"));
        }
        // xml?InputMessage
        InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());

        String servername = inputMsg.getToUserName();// ?
        String custermname = inputMsg.getFromUserName();// 
        long createTime = inputMsg.getCreateTime();// 
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;//
        // 

        // ??
        String msgType = inputMsg.getMsgType();

        // ?
        System.out.println("??" + inputMsg.getToUserName());
        System.out.println("????" + inputMsg.getFromUserName());
        System.out.println("?" + inputMsg.getCreateTime() + new Date(createTime * 1000l));
        System.out.println("?Event" + inputMsg.getEvent());
        System.out.println("?EventKey" + inputMsg.getEventKey());
        System.out.println("" + inputMsg.getContent());
        StringBuffer str = new StringBuffer();
        // ????
        if ("event".equals(msgType)) {

            if ("subscribe".equals(inputMsg.getEvent())) {

                if (!StringUtils.isEmpty(inputMsg.getEventKey())) {
                    Long qrCodeId = null;
                    try {
                        qrCodeId = Long
                                .parseLong(inputMsg.getEventKey().replaceAll("qrscene_", "").trim().toString());
                    } catch (Exception e) {
                        System.out.println("" + inputMsg.getEventKey() + "------?");
                        e.printStackTrace();
                    }

                    ManageQRcode manageQRcode = manageQRcodeService.getManageQRcode(qrCodeId);

                    Integer count = manageQRcodeService.selectHistoryWeixinBytaskId(manageQRcode.getTask().getId(),
                            inputMsg.getFromUserName());

                    HistoryWeixin wxUser = new HistoryWeixin();
                    wxUser.setCreateDate(new Date());
                    wxUser.setToUserName(inputMsg.getToUserName());
                    wxUser.setFromUserName(inputMsg.getFromUserName());
                    wxUser.setMsgType(msgType);
                    wxUser.setEvent(inputMsg.getEvent());
                    wxUser.setEventKey(inputMsg.getEventKey());
                    wxUser.setCreateTime(inputMsg.getCreateTime().toString());
                    wxUser.setQrcodeId(qrCodeId);
                    wxUser.setTaskId(manageQRcode.getTask().getId());

                    if (count == 0) {
                        if ("Y".equals(manageQRcode.getQrState())) {
                            manageQRcode.setQrSubscribeCount(manageQRcode.getQrSubscribeCount() + 1);
                            manageQRcode.setQrSubscribeAdminCount(manageQRcode.getQrSubscribeAdminCount() + 1);
                            manageQRcodeService.saveManageQRcode(manageQRcode);
                            wxUser.setStatus("Y");
                        } else {
                            manageQRcode.setQrSubscribeAdminCount(manageQRcode.getQrSubscribeAdminCount() + 1);
                            manageQRcodeService.saveManageQRcode(manageQRcode);
                            wxUser.setStatus("N");
                        }
                    }

                    manageQRcodeService.saveHistoryWeixin(wxUser);

                }
                String content = "HI???????????? \n ";

                List<Game> gameList = gameService.getEffectiveGamelist();
                if (gameList != null && gameList.size() > 0) {
                    for (int i = 0; i < gameList.size(); i++) {
                        Game game = gameList.get(i);
                        content += "[" + game.getXuhao() + "] " + game.getGameName() + "\n";
                    }
                } else {
                    content += "???";
                }

                str.append("<xml>                                              ");
                str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
                str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
                str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
                str.append("<MsgType><![CDATA[text]]></MsgType>                ");
                str.append("<Content><![CDATA[" + content + "]]></Content>                     ");
                str.append("</xml>                                             ");
                System.out.println(str.toString());
                response.getWriter().write(str.toString());
            }

        } else if ("text".equals(msgType)) {

            String redurl = URLEncoder.encode(MobileContants.YM + "/weixinUser/bindUserOpenId", "utf-8");
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + MobileContants.appID
                    + "&redirect_uri=" + redurl + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

            String xxxx = inputMsg.getContent().toString();
            String content = "";
            if (xxxx.indexOf("") != -1) {

                str.append("<xml>                                              ");
                str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
                str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
                str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
                str.append("<MsgType><![CDATA[news]]></MsgType>                ");
                str.append("<ArticleCount>1</ArticleCount>                     ");
                str.append("<Articles>                                         ");
                str.append("<item>                                             ");
                str.append("<Title><![CDATA[??]]></Title>                   ");
                str.append(
                        "<Description><![CDATA[??,,]]></Description> ");
                str.append("<PicUrl><![CDATA[]]></PicUrl>                ");
                str.append("<Url><![CDATA[" + url + "]]></Url>                         ");
                str.append("</item>                                            ");
                str.append("</Articles>                                        ");
                str.append("</xml>                                             ");

                System.out.println(str.toString());
                response.getWriter().write(str.toString());
            } else {
                if ("?".equals(xxxx) || "".equals(xxxx) || "".equals(xxxx) || "".equals(xxxx)) {
                    List<Game> gameList = gameService.getEffectiveGamelist();
                    if (gameList != null && gameList.size() > 0) {
                        for (int i = 0; i < gameList.size(); i++) {
                            Game game = gameList.get(i);
                            content += "[" + game.getXuhao() + "] " + game.getGameName() + "\n";
                        }
                        content += "??????";
                    } else {
                        content = "???";
                    }
                } else {
                    Game game = gameService.findGameByNameOrXuhao(xxxx);
                    if (game != null) {
                        Long count = gameService.getMyGameCodeCount(game.getId(), custermname);
                        System.out.println(count);
                        System.out.println(game.getMaximum());
                        if (count < game.getMaximum()) {
                            //?
                            GameCode code = gameService.getMyGameCode(game.getId());
                            gameService.updateMyGameCode(code.getId(), custermname);
                            content = "???" + code.getCode() + " \n  "
                                    + game.getGameMessage() + "";

                        } else {
                            content = "????????\n ?'?'?????????";
                        }

                    } else {
                        content = " ????\n ?'?'?????????";
                    }

                }
                str.append("<xml>                                              ");
                str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
                str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
                str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
                str.append("<MsgType><![CDATA[text]]></MsgType>                ");
                str.append("<Content><![CDATA[" + content + "]]></Content>                     ");
                str.append("</xml>                                             ");
                System.out.println(str.toString());
                response.getWriter().write(str.toString());
            }

        }

    }
}