ApiBaseAction.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package com.kmall.api.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
  4. import com.kmall.common.advice.CustomDateEditor;
  5. import com.kmall.common.advice.CustomSqlDateEditor;
  6. import com.kmall.common.advice.CustomTimestampEditor;
  7. import com.kmall.api.cache.UserTokenCache;
  8. import com.kmall.api.entity.TokenEntity;
  9. import com.kmall.api.interceptor.AuthorizationInterceptor;
  10. import com.kmall.common.constant.Dict;
  11. import com.kmall.common.utils.DateUtils;
  12. import com.kmall.common.utils.StringUtils;
  13. import org.apache.commons.logging.Log;
  14. import org.apache.commons.logging.LogFactory;
  15. import org.apache.log4j.Logger;
  16. import org.apache.shiro.authz.UnauthorizedException;
  17. import org.springframework.beans.TypeMismatchException;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.beans.propertyeditors.StringTrimmerEditor;
  20. import org.springframework.validation.BindException;
  21. import org.springframework.web.bind.MissingServletRequestParameterException;
  22. import org.springframework.web.bind.WebDataBinder;
  23. import org.springframework.web.bind.annotation.ExceptionHandler;
  24. import org.springframework.web.bind.annotation.InitBinder;
  25. import org.springframework.web.bind.annotation.ResponseBody;
  26. import org.springframework.web.context.request.WebRequest;
  27. import javax.servlet.http.HttpServletRequest;
  28. import javax.servlet.http.HttpServletResponse;
  29. import java.io.BufferedReader;
  30. import java.io.IOException;
  31. import java.sql.Timestamp;
  32. import java.util.Date;
  33. import java.util.HashMap;
  34. import java.util.Map;
  35. /**
  36. * @author Scott
  37. * @ClassName: ApiBaseAction
  38. * @Description: 基础控制类
  39. * @date 2016年9月2日
  40. */
  41. public class ApiBaseAction {
  42. protected Log logger = LogFactory.getLog(ApiBaseAction.class);
  43. /**
  44. * 得到request对象
  45. */
  46. @Autowired
  47. protected HttpServletRequest request;
  48. /**
  49. * 得到response对象
  50. */
  51. @Autowired
  52. protected HttpServletResponse response;
  53. /**
  54. * 参数绑定异常
  55. */
  56. @ExceptionHandler({BindException.class, MissingServletRequestParameterException.class, UnauthorizedException.class, TypeMismatchException.class})
  57. @ResponseBody
  58. public Map<String, Object> bindException(Exception e) {
  59. if (e instanceof BindException) {
  60. return toResponsObject(1, "参数绑定异常", e.getMessage());
  61. } else if (e instanceof UnauthorizedException) {
  62. return toResponsObject(1, "无访问权限", e.getMessage());
  63. }
  64. return toResponsObject(1, "处理异常", e.getMessage());
  65. }
  66. /**
  67. * @param requestCode
  68. * @param msg
  69. * @param data
  70. * @return Map<String,Object>
  71. * @throws
  72. * @Description:构建统一格式返回对象
  73. * @date 2016年9月2日
  74. * @author zhuliyun
  75. */
  76. public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
  77. Map<String, Object> obj = new HashMap<String, Object>();
  78. obj.put("errno", requestCode);
  79. obj.put("errmsg", msg);
  80. if (data != null)
  81. obj.put("data", data);
  82. return obj;
  83. }
  84. public Map<String, Object> toResponsSuccess(Object data) {
  85. Map<String, Object> rp = toResponsObject(0, "执行成功", data);
  86. logger.info("response:" + rp);
  87. return rp;
  88. }
  89. public Map<String, Object> toResponsMsgSuccess(String msg) {
  90. return toResponsObject(0, msg, "");
  91. }
  92. public Map<String, Object> toResponsSuccessForSelect(Object data) {
  93. Map<String, Object> result = new HashMap<>(2);
  94. result.put("list", data);
  95. return toResponsObject(0, "执行成功", result);
  96. }
  97. public Map<String, Object> toResponsFail(String msg) {
  98. return toResponsObject(1, msg, null);
  99. }
  100. /**
  101. * 微信授权登录异常
  102. * @param msg
  103. * @return
  104. */
  105. public Map<String, Object> toResponsWxLoginFail(String msg) {
  106. return toResponsObject(2, msg, null);
  107. }
  108. /**
  109. * initBinder 初始化绑定 <br>
  110. * 这里处理了3种类型<br>
  111. * 1、字符串自动 trim 去掉前后空格 <br>
  112. * 2、java.util.Date 转换为 "yyyy-MM-dd HH:mm:ss" 格式<br>
  113. * 3、java.sql.Date 转换为 "yyyy-MM-dd" 格式<br>
  114. * 4、java.util.Timestamps 时间转换
  115. *
  116. * @param binder WebDataBinder 要注册的binder
  117. * @param request 前端请求
  118. */
  119. @InitBinder
  120. public void initBinder(WebDataBinder binder, WebRequest request) {
  121. // 绑定java.util.Date 类型转换
  122. // SimpleDateFormat dateFormat = new
  123. // SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设定前后台的格式对应
  124. // dateFormat.setLenient(false);
  125. binder.registerCustomEditor(Date.class, new CustomDateEditor());
  126. // 绑定 java.sql.Date类型
  127. binder.registerCustomEditor(java.sql.Date.class, new CustomSqlDateEditor());
  128. // Timestamp 绑定
  129. binder.registerCustomEditor(Timestamp.class, new CustomTimestampEditor());
  130. // 字符串自动Trim
  131. binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
  132. }
  133. /**
  134. * 获取请求方IP
  135. *
  136. * @return 客户端Ip
  137. */
  138. public String getClientIp() {
  139. String xff = request.getHeader("x-forwarded-for");
  140. if (xff == null) {
  141. return request.getRemoteAddr();
  142. }
  143. return xff;
  144. }
  145. public JSONObject getJsonRequest() {
  146. JSONObject result = null;
  147. StringBuilder sb = new StringBuilder();
  148. try (BufferedReader reader = request.getReader();) {
  149. char[] buff = new char[1024];
  150. int len;
  151. while ((len = reader.read(buff)) != -1) {
  152. sb.append(buff, 0, len);
  153. }
  154. result = JSONObject.parseObject(sb.toString());
  155. } catch (IOException e) {
  156. e.printStackTrace();
  157. }
  158. return result;
  159. }
  160. /**
  161. * 获取请求的openId
  162. *
  163. * @return 客户端Ip
  164. */
  165. public String getOpenId() {
  166. String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
  167. logger.info("请求openId的token:"+token);
  168. //查询token信息
  169. TokenEntity tokenEntity = UserTokenCache.getUserInfoByToken(token);
  170. logger.info("根据token获取token对象信息:"+tokenEntity);
  171. if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
  172. return null;
  173. }
  174. return tokenEntity.getOpenId();
  175. }
  176. public Long getUserId() {
  177. String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
  178. //查询token信息
  179. TokenEntity tokenEntity = UserTokenCache.getUserInfoByToken(token);
  180. if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
  181. return null;
  182. }
  183. return tokenEntity.getUserId();
  184. }
  185. /**
  186. * 获取请求的门店Id
  187. *
  188. * @return 客户端Ip
  189. */
  190. public Long getStoreId() {
  191. String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
  192. String isRefusedLogin = request.getHeader(AuthorizationInterceptor.IS_REFUSED_LOGIN);
  193. TokenEntity tokenEntity = null;
  194. if(StringUtils.isNotEmpty(isRefusedLogin)) {
  195. if (isRefusedLogin.equalsIgnoreCase("true")) {//用户拒绝授权
  196. tokenEntity = UserTokenCache.getStoreByTokenByRefused(token);//当用户拒绝授权时,根据门店token获取保存的信息
  197. } else {
  198. tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
  199. }
  200. }else{
  201. tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
  202. }
  203. if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
  204. return null;
  205. }
  206. return tokenEntity.getStoreId();
  207. }
  208. /**
  209. * 获取请求的商户编号
  210. *
  211. * @return 客户端Ip
  212. */
  213. public String getMerchSn() {
  214. String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
  215. String isRefusedLogin = request.getHeader(AuthorizationInterceptor.IS_REFUSED_LOGIN);
  216. TokenEntity tokenEntity = null;
  217. if(StringUtils.isNotEmpty(isRefusedLogin)) {
  218. if (isRefusedLogin.equalsIgnoreCase("true")) {//用户拒绝授权
  219. tokenEntity = UserTokenCache.getStoreByTokenByRefused(token);//当用户拒绝授权时,根据门店token获取保存的信息
  220. } else {
  221. tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
  222. }
  223. }else{
  224. tokenEntity = UserTokenCache.getUserInfoByToken(token);//查询token信息
  225. }
  226. if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
  227. return null;
  228. }
  229. return tokenEntity.getMerchSn();
  230. }
  231. public String setInvalidTime(MkStoreTicketDiscountVo mkStoreTicketDiscount){
  232. String inValidDate = "";
  233. if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
  234. String startDate = DateUtils.format(mkStoreTicketDiscount.getFixBegTime(), DateUtils.DATE_PATTERN);
  235. String endDate = DateUtils.format(mkStoreTicketDiscount.getFixEndTime(), DateUtils.DATE_PATTERN);
  236. inValidDate = startDate + " - " + endDate;
  237. }
  238. if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
  239. String postponeNum = StringUtils.isNotEmpty(mkStoreTicketDiscount.getPostponeNum()) ? mkStoreTicketDiscount.getPostponeNum() : "0";
  240. String validDayNum = StringUtils.isNotEmpty(mkStoreTicketDiscount.getValidDayNum()) ? mkStoreTicketDiscount.getValidDayNum() : "0";
  241. inValidDate = "领取" + postponeNum + "天后 " + validDayNum + "天内有效";
  242. }
  243. return inValidDate;
  244. }
  245. }