后台接口版本配置

比对版本号工具:

package com.dbn.common.util;

import com.dbn.common.checker.Checker;
import com.dbn.common.vo.BizVo;
import com.dbn.common.vo.ZntRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;

public class BizUtil
  implements ApplicationContextAware, InitializingBean
{
  private ApplicationContext appCtx;
  private Map<String, BizVo> serviceMethodMap = new HashMap();
  private static final String BIZ_BEAN_NAME_ATTR_KEY = "beanName";
  private static final String METHOD_NAME_ATTR_KEY = "methodName";
  private static final String CODE_ATTR_KEY = "code";
  private static final String VERSION_ATTR_KEY = "version";
  private static final String CHECKER_BEAN_NAME_ATTR_KEY = "beanName";
  private static final String CHECKERS_LABLE_NAME = "checkers";
  
  public void afterPropertiesSet()
    throws Exception
  {
    Resource serviceDefResource = this.appCtx.getResource("classpath:bizDefine.xml");
    SAXReader saxReader = new SAXReader();
    Document doc = saxReader.read(serviceDefResource.getFile());
    Element rootElm = doc.getRootElement();
    List bizElmList = rootElm.elements();
    for (int i = 0; i < bizElmList.size(); i++)
    {
      Element bizElm = (Element)bizElmList.get(i);
      Attribute beanNameAttr = bizElm.attribute("beanName");
      String beanName = beanNameAttr.getValue();
      Attribute methodNameAttr = bizElm.attribute("methodName");
      String methodName = methodNameAttr.getValue();
      
      Class bizClazz = this.appCtx.getType(beanName);
      Method method = bizClazz.getDeclaredMethod(methodName, new Class[] { ZntRequest.class });
      
      BizVo bizVo = new BizVo();
      bizVo.setBeanName(beanName);
      bizVo.setServiceMethod(method);
      
      Element checkersElm = bizElm.element("checkers");
      if (checkersElm != null)
      {
        List checkerElmList = checkersElm.elements();
        List<Checker> checkerList = new ArrayList();
        for (int j = 0; j < checkerElmList.size(); j++)
        {
          Element checkerElm = (Element)checkerElmList.get(j);
          Attribute checkerNameAttr = checkerElm.attribute("beanName");
          String checkerName = checkerNameAttr.getValue();
          Object checker = this.appCtx.getBean(checkerName);
          checkerList.add((Checker)checker);
        }
        bizVo.setCheckerList(checkerList);
      }
      Attribute codeAttr = bizElm.attribute("code");
      String code = codeAttr.getValue();
      Attribute versionAttr = bizElm.attribute("version");
      String version = versionAttr.getValue();
      
      String bizKey = code + "_" + version;
      this.serviceMethodMap.put(bizKey, bizVo);
    }
  }
  
  public void setApplicationContext(ApplicationContext ctx)
    throws BeansException
  {
    this.appCtx = ctx;
  }
  
  public BizVo getBiz(String serviceKey)
  {
    BizVo bizVo = (BizVo)this.serviceMethodMap.get(serviceKey);
    return bizVo;
  }
}


接口版本控制配置文件xml:

 

<?xml version="1.0" encoding="UTF-8"?>
<services>
    <service beanName="v1_zhiNongLoginBiz" methodName="tokenLogin" code="001001" version="1">
        <checkers>
            <checker beanName="phoneChecker" />
        </checkers>
    </service>
</services>

phoneChecker 检测是否登入:

package com.dbn.common.checker.impl;

import com.aweb.platform.util.StringUtils;
import com.dbn.common.checker.Checker;
import com.dbn.common.vo.CheckResult;
import com.dbn.common.vo.RequestData;
import com.dbn.common.vo.ZntRequest;
import com.dbn.oatong.sysmodule.utils.DeviceUtil;
import com.dbn.oatong.sysmodule.utils.MClient;
import com.dbn.oatong.sysmodule.utils.MD5;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

public class PhoneCheckerImpl
  implements Checker
{
  Logger log = Logger.getLogger(PhoneCheckerImpl.class);
  
  public CheckResult check(ActionInvocation invocation, ZntRequest requestVo)
    throws Exception
  {
    ActionContext context = invocation.getInvocationContext();
    HttpServletRequest request = (HttpServletRequest)context.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
    String userAgent = request.getHeader("user-agent");
    String token = getCookie("ticketCookie", request);
    
    this.log.info("tokenCookie================" + token);
    this.log.info("userAgent==================" + userAgent);
    if (StringUtils.checkStr(userAgent))
    {
      if (!StringUtils.checkStr(token))
      {
        token = DeviceUtil.getTicketCookie(userAgent);
        this.log.info(userAgent + "userAgent=====取token:" + token);
        if (!StringUtils.checkStr(token))
        {
          this.log.error("requestVo.getR()==============================" + requestVo.getR() + ";requestVo.getV()===========================" + requestVo.getV());
          CheckResult chkResult = buildErrorMsg("无法获取用户信息,请退出,重新登录!", token, request.getRequestURI(), userAgent);
          return chkResult;
        }
      }
      String deviceId = DeviceUtil.getDeviceId(userAgent);
      this.log.info("deviceId===============" + deviceId);
      
      MClient mcClient = MClient.getInstance();
      
      String achiveId = null;
      try
      {
        achiveId = StringUtils.nvl(mcClient.get(token));
      }
      catch (Throwable e)
      {
        Thread.sleep(1000L);
        try
        {
          achiveId = StringUtils.nvl(mcClient.get(token));
        }
        catch (Throwable throwable)
        {
          this.log.error("获取mc信息失败!achiveId=" + achiveId + ";tokenCookieName=" + token);
        }
      }
      if (!StringUtils.isLong(achiveId))
      {
        this.log.error("achiveId is null or empty, token=" + token);
        CheckResult chkResult = buildErrorMsg("获取登录信息失败,请退出,重新登录!", token, request.getRequestURI(), userAgent);
        return chkResult;
      }
      String deviceIdFlag = "";
      try
      {
        deviceIdFlag = StringUtils.nvl(mcClient.get("tokenid_deviceId_" + token));
        this.log.info("deviceIdFlag===================" + deviceIdFlag);
      }
      catch (Throwable e)
      {
        Thread.sleep(1000L);
        try
        {
          deviceIdFlag = StringUtils.nvl(mcClient.get("tokenid_deviceId_" + token));
          this.log.info("deviceIdFlag2===================" + deviceIdFlag);
        }
        catch (Throwable throwable)
        {
          this.log.error("获取mc信息失败!userAgent=" + userAgent + ";tokenCookieName=" + token);
        }
      }
      if (!StringUtils.checkStr(deviceIdFlag))
      {
        this.log.error("deviceIdFlag is null or empty, token=" + token);
        CheckResult chkResult = buildErrorMsg("获取登录信息失败,请退出,重新登录!", token, request.getRequestURI(), userAgent);
        return chkResult;
      }
      if (!deviceId.equals(deviceIdFlag))
      {
        this.log.error("deviceIdFlag is not equals user deviceId,deviceId=" + deviceId + ";deviceIdFlag=" + deviceIdFlag);
        CheckResult chkResult = buildErrorMsg("获取登录信息失败,请退出,重新登录!", token, request.getRequestURI(), userAgent);
        return chkResult;
      }
      Map<String, Object> reqAttrs = null;
      if (requestVo.getD() != null) {
        reqAttrs = requestVo.getD().getAttrs();
      }
      String timestamp = null;
      String sign = null;
      if (reqAttrs != null)
      {
        timestamp = (String)requestVo.getD().getAttrs().get("timestamp");
        sign = (String)requestVo.getD().getAttrs().get("sign");
        this.log.info("sign=========================" + sign);
        this.log.info("timestamp====================" + timestamp);
      }
      if ((!StringUtils.checkStr(sign)) || (!StringUtils.checkStr(timestamp)))
      {
        CheckResult chkResult = buildErrorMsg("签名信息为空,请退出,重新登录!", token, request.getRequestURI(), userAgent);
        return chkResult;
      }
      String secretKey = deviceId.substring(deviceId.length() - 4) + "+-*/";
      String signFlag = MD5.encryption(token + secretKey + timestamp);
      if (!signFlag.toLowerCase().equals(sign.toLowerCase()))
      {
        this.log.error("signFlag=" + signFlag + "sign=" + sign + ";timestamp" + timestamp + "secretKey" + secretKey + "token" + token);
        CheckResult chkResult = buildErrorMsg("签名信息验证失败,请退出,重新登录!", token, request.getRequestURI(), userAgent);
        return chkResult;
      }
    }
    CheckResult chkResult = new CheckResult();
    chkResult.setResultCode("0");
    return chkResult;
  }
  
  private CheckResult buildErrorMsg(String msg, String token, String url, String userAgent)
  {
    StringBuilder logError = new StringBuilder();
    logError.append("tokenCookieName:").append(token).append(";请求地址:").append(url)
      .append(";错误信息:").append(msg).append(";userAgent:").append(userAgent);
    this.log.error(logError.toString());
    
    CheckResult chkResult = new CheckResult();
    chkResult.setResultCode("3");
    chkResult.setResultMsg(msg);
    return chkResult;
  }
  
  public String getCookie(String name, HttpServletRequest request)
  {
    try
    {
      Cookie[] cookies = request.getCookies();
      if (cookies != null)
      {
        for (Cookie cookie : cookies)
        {
          cookie.setPath("/");
          if (cookie.getName().equals(name)) {
            return cookie.getValue();
          }
        }
      }
      else
      {
        this.log.error("未获取到Cookie================");
        return "";
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return "";
  }
}


客户端请求接口对比版本号:

package com.dbn.common.web.unionservice;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dbn.common.checker.Checker;
import com.dbn.common.util.BizUtil;
import com.dbn.common.vo.BizVo;
import com.dbn.common.vo.CheckResult;
import com.dbn.common.vo.ResponseData;
import com.dbn.common.vo.ZntRequest;
import com.dbn.common.vo.ZntResponse;
import com.dbn.oatong.sysmodule.staticspringcontext.StaticSpringContextHelper;
import com.dbn.oatong.sysmodule.utils.DbnBase64;
import com.dbn.oatong.sysmodule.utils.LoggerFactory;
import com.dbn.oatong.sysmodule.web.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

public class UnionServiceAction
  extends BaseAction
{
  private static final long serialVersionUID = -1123817229255500522L;
  private static final Logger log = LoggerFactory.getLogger(UnionServiceAction.class);
  private ZntResponse zntResponse;
  private BizUtil bizUtil;
  private static SerializerFeature[] serialFeatures = { SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero };
  private static final String ZNT_SUCCESS_CODE = "0";
  
  public String execute()
    throws Exception
  {
    HttpServletRequest request = ServletActionContext.getRequest();
    

    int reqLength = request.getContentLength();
    




    BufferedReader reader = request.getReader();
    String requestBody = reader.readLine();
    String requestJson = DbnBase64.decode(requestBody, "");
    reader.close();
    
    ZntRequest zntRequest = null;
    try
    {
      zntRequest = (ZntRequest)JSONObject.parseObject(requestJson, ZntRequest.class);
    }
    catch (Exception e)
    {
      log.error("requestBody====" + requestBody + "<<<<");
      log.error("requestJson====" + requestJson);
      log.error("RequestBytes==========" + reqLength);
      
      e.printStackTrace();
      writeServiceErrJSON();
      return null;
    }
    String serviceCode = zntRequest.getR();
    String version = zntRequest.getV();
    
    String serviceKey = serviceCode + "_" + version;
    BizVo bizVo = this.bizUtil.getBiz(serviceKey);
    

    List<Checker> checkerList = bizVo.getCheckerList();
    if (checkerList != null) {
      for (Checker checker : checkerList)
      {
        ActionInvocation invocation = ServletActionContext.getContext().getActionInvocation();
        CheckResult checkResult = checker.check(invocation, zntRequest);
        if (!"0".equals(checkResult.getResultCode()))
        {
          this.zntResponse = new ZntResponse();
          ResponseData respBody = new ResponseData(new HashMap(), new HashMap());
          this.zntResponse.setD(respBody);
          this.zntResponse.setR(checkResult.getResultCode());
          this.zntResponse.setM(checkResult.getResultMsg());
          writeJSON(this.zntResponse);
          return null;
        }
      }
    }
    Object serviceBean = StaticSpringContextHelper.getBeanByName(bizVo.getBeanName());
    Method servicemethod = bizVo.getServiceMethod();
    try
    {
      this.zntResponse = ((ZntResponse)servicemethod.invoke(serviceBean, new Object[] { zntRequest }));
    }
    catch (Exception e)
    {
      log.error("业务异常=============" + e);
      log.error("RequestJson>>>>>>>>>>>>>>>>>>>" + requestJson);
      e.printStackTrace();
      
      writeServiceErrJSON();
      return null;
    }
    if (this.zntResponse == null)
    {
      log.error("zntResponse is null");
      log.error("RequestJson>>>>>>>>>>>>>>>>>>>" + requestJson);
      
      writeServiceErrJSON();
      return null;
    }
    if ((this.zntResponse.getR() == null) || ("".equals(this.zntResponse.getR())))
    {
      log.error("zntResponse_R===============" + this.zntResponse.getR());
      log.error("RequestJson>>>>>>>>>>>>>>>>>>>" + requestJson);
      
      writeServiceErrJSON();
      return null;
    }
    if (this.zntResponse.getD() == null)
    {
      log.error("zntResponse_D===============" + this.zntResponse.getD());
      log.error("RequestJson>>>>>>>>>>>>>>>>>>>" + requestJson);
      
      writeServiceErrJSON();
      return null;
    }
    if (this.zntResponse.getD().getAttrs() == null)
    {
      log.error("zntResponse_D_Attrs===============" + this.zntResponse.getD().getAttrs());
      log.error("RequestJson>>>>>>>>>>>>>>>>>>>" + requestJson);
      
      writeServiceErrJSON();
      return null;
    }
    if (this.zntResponse.getD().getDomains() == null)
    {
      log.error("zntResponse_D_Domains===============" + this.zntResponse.getD().getDomains());
      log.error("RequestJson>>>>>>>>>>>>>>>>>>>" + requestJson);
      
      writeServiceErrJSON();
      return null;
    }
    writeJSON(this.zntResponse);
    return null;
  }
  
  private void writeJSON(ZntResponse zntResponse)
    throws IOException
  {
    String responseJson = JSONObject.toJSONString(zntResponse, serialFeatures);
    String encodeRespStr = new String(DbnBase64.encode(responseJson, ""));
    
    HttpServletResponse response = ServletActionContext.getResponse();
    PrintWriter writer = response.getWriter();
    writer.write(encodeRespStr);
    writer.flush();
    writer.close();
  }
  
  private void writeServiceErrJSON()
    throws IOException
  {
    this.zntResponse = new ZntResponse();
    this.zntResponse.setR("1");
    this.zntResponse.setM("服务异常");
    writeJSON(this.zntResponse);
  }
  
  public ZntResponse getZntResponse()
  {
    return this.zntResponse;
  }
  
  public void setZntResponse(ZntResponse zntResponse)
  {
    this.zntResponse = zntResponse;
  }
  
  public BizUtil getBizUtil()
  {
    return this.bizUtil;
  }
  
  public void setBizUtil(BizUtil bizUtil)
  {
    this.bizUtil = bizUtil;
  }
}

 

posted @ 2015-12-15 17:53  _ylsn  阅读(368)  评论(0编辑  收藏  举报