123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- package com.kmall.api.util;
- import com.alibaba.fastjson.JSONObject;
- import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
- import com.kmall.common.advice.CustomDateEditor;
- import com.kmall.common.advice.CustomSqlDateEditor;
- import com.kmall.common.advice.CustomTimestampEditor;
- import com.kmall.api.cache.UserTokenCache;
- import com.kmall.api.entity.TokenEntity;
- import com.kmall.api.interceptor.AuthorizationInterceptor;
- import com.kmall.common.constant.Dict;
- import com.kmall.common.utils.DateUtils;
- import com.kmall.common.utils.StringUtils;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.log4j.Logger;
- import org.apache.shiro.authz.UnauthorizedException;
- import org.springframework.beans.TypeMismatchException;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.propertyeditors.StringTrimmerEditor;
- import org.springframework.validation.BindException;
- import org.springframework.web.bind.MissingServletRequestParameterException;
- import org.springframework.web.bind.WebDataBinder;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.InitBinder;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.context.request.WebRequest;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.sql.Timestamp;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * @author Scott
- * @ClassName: ApiBaseAction
- * @Description: 基础控制类
- * @date 2016年9月2日
- */
- public class ApiBaseAction {
- protected Log logger = LogFactory.getLog(ApiBaseAction.class);
- /**
- * 得到request对象
- */
- @Autowired
- protected HttpServletRequest request;
- /**
- * 得到response对象
- */
- @Autowired
- protected HttpServletResponse response;
- /**
- * 参数绑定异常
- */
- @ExceptionHandler({BindException.class, MissingServletRequestParameterException.class, UnauthorizedException.class, TypeMismatchException.class})
- @ResponseBody
- public Map<String, Object> bindException(Exception e) {
- if (e instanceof BindException) {
- return toResponsObject(1, "参数绑定异常", e.getMessage());
- } else if (e instanceof UnauthorizedException) {
- return toResponsObject(1, "无访问权限", e.getMessage());
- }
- return toResponsObject(1, "处理异常", e.getMessage());
- }
- /**
- * @param requestCode
- * @param msg
- * @param data
- * @return Map<String,Object>
- * @throws
- * @Description:构建统一格式返回对象
- * @date 2016年9月2日
- * @author zhuliyun
- */
- public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
- Map<String, Object> obj = new HashMap<String, Object>();
- obj.put("errno", requestCode);
- obj.put("errmsg", msg);
- if (data != null)
- obj.put("data", data);
- return obj;
- }
- public Map<String, Object> toResponsSuccess(Object data) {
- Map<String, Object> rp = toResponsObject(0, "执行成功", data);
- logger.info("response:" + rp);
- return rp;
- }
- public Map<String, Object> toResponsMsgSuccess(String msg) {
- return toResponsObject(0, msg, "");
- }
- public Map<String, Object> toResponsSuccessForSelect(Object data) {
- Map<String, Object> result = new HashMap<>(2);
- result.put("list", data);
- return toResponsObject(0, "执行成功", result);
- }
- public Map<String, Object> toResponsFail(String msg) {
- return toResponsObject(1, msg, null);
- }
- /**
- * 微信授权登录异常
- * @param msg
- * @return
- */
- public Map<String, Object> toResponsWxLoginFail(String msg) {
- return toResponsObject(2, msg, null);
- }
- /**
- * initBinder 初始化绑定 <br>
- * 这里处理了3种类型<br>
- * 1、字符串自动 trim 去掉前后空格 <br>
- * 2、java.util.Date 转换为 "yyyy-MM-dd HH:mm:ss" 格式<br>
- * 3、java.sql.Date 转换为 "yyyy-MM-dd" 格式<br>
- * 4、java.util.Timestamps 时间转换
- *
- * @param binder WebDataBinder 要注册的binder
- * @param request 前端请求
- */
- @InitBinder
- public void initBinder(WebDataBinder binder, WebRequest request) {
- // 绑定java.util.Date 类型转换
- // SimpleDateFormat dateFormat = new
- // SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设定前后台的格式对应
- // dateFormat.setLenient(false);
- binder.registerCustomEditor(Date.class, new CustomDateEditor());
- // 绑定 java.sql.Date类型
- binder.registerCustomEditor(java.sql.Date.class, new CustomSqlDateEditor());
- // Timestamp 绑定
- binder.registerCustomEditor(Timestamp.class, new CustomTimestampEditor());
- // 字符串自动Trim
- binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
- }
- /**
- * 获取请求方IP
- *
- * @return 客户端Ip
- */
- public String getClientIp() {
- String xff = request.getHeader("x-forwarded-for");
- if (xff == null) {
- return request.getRemoteAddr();
- }
- return xff;
- }
- public JSONObject getJsonRequest() {
- JSONObject result = null;
- StringBuilder sb = new StringBuilder();
- try (BufferedReader reader = request.getReader();) {
- char[] buff = new char[1024];
- int len;
- while ((len = reader.read(buff)) != -1) {
- sb.append(buff, 0, len);
- }
- result = JSONObject.parseObject(sb.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 获取请求的openId
- *
- * @return 客户端Ip
- */
- public String getOpenId() {
- String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
- logger.info("请求openId的token:"+token);
- //查询token信息
- TokenEntity tokenEntity = UserTokenCache.getUserInfoByToken(token);
- logger.info("根据token获取token对象信息:"+tokenEntity);
- if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
- return null;
- }
- return tokenEntity.getOpenId();
- }
- public Long getUserId() {
- String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
- //查询token信息
- TokenEntity tokenEntity = UserTokenCache.getUserInfoByToken(token);
- if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
- return null;
- }
- return tokenEntity.getUserId();
- }
- /**
- * 获取请求的门店Id
- *
- * @return 客户端Ip
- */
- public Long getStoreId() {
- String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
- String isRefusedLogin = request.getHeader(AuthorizationInterceptor.IS_REFUSED_LOGIN);
- TokenEntity tokenEntity = null;
- if(StringUtils.isNotEmpty(isRefusedLogin)) {
- if (isRefusedLogin.equalsIgnoreCase("true")) {//用户拒绝授权
- tokenEntity = UserTokenCache.getStoreByTokenByRefused(token);//当用户拒绝授权时,根据门店token获取保存的信息
- } else {
- tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
- }
- }else{
- tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
- }
- if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
- return null;
- }
- return tokenEntity.getStoreId();
- }
- /**
- * 获取请求的商户编号
- *
- * @return 客户端Ip
- */
- public String getMerchSn() {
- String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
- String isRefusedLogin = request.getHeader(AuthorizationInterceptor.IS_REFUSED_LOGIN);
- TokenEntity tokenEntity = null;
- if(StringUtils.isNotEmpty(isRefusedLogin)) {
- if (isRefusedLogin.equalsIgnoreCase("true")) {//用户拒绝授权
- tokenEntity = UserTokenCache.getStoreByTokenByRefused(token);//当用户拒绝授权时,根据门店token获取保存的信息
- } else {
- tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
- }
- }else{
- tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
- }
- if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
- return null;
- }
- return tokenEntity.getMerchSn();
- }
- public String setInvalidTime(MkStoreTicketDiscountVo mkStoreTicketDiscount){
- String inValidDate = "";
- if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
- String startDate = DateUtils.format(mkStoreTicketDiscount.getFixBegTime(), DateUtils.DATE_PATTERN);
- String endDate = DateUtils.format(mkStoreTicketDiscount.getFixEndTime(), DateUtils.DATE_PATTERN);
- inValidDate = startDate + " - " + endDate;
- }
- if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
- String postponeNum = StringUtils.isNotEmpty(mkStoreTicketDiscount.getPostponeNum()) ? mkStoreTicketDiscount.getPostponeNum() : "0";
- String validDayNum = StringUtils.isNotEmpty(mkStoreTicketDiscount.getValidDayNum()) ? mkStoreTicketDiscount.getValidDayNum() : "0";
- inValidDate = "领取" + postponeNum + "天后 " + validDayNum + "天内有效";
- }
- return inValidDate;
- }
- }
|