Commit e3dc5c9c228cd6281b34c1974b31f37e2ea012aa

Authored by 周伟鹏
1 parent 3172f463

添加获取用户信息定时任务

... ... @@ -90,6 +90,14 @@
90 90 <artifactId>slf4j-api</artifactId>
91 91 <version>1.7.25</version>
92 92 </dependency>
  93 + <dependency>
  94 + <groupId>org.apache.httpcomponents</groupId>
  95 + <artifactId>httpclient</artifactId>
  96 + </dependency>
  97 + <dependency>
  98 + <groupId>org.apache.httpcomponents</groupId>
  99 + <artifactId>httpmime</artifactId>
  100 + </dependency>
93 101 </dependencies>
94 102  
95 103 <build>
... ...
src/main/java/com/cnlive/shenhe/entity/ShySites.java
... ... @@ -27,7 +27,7 @@ public class ShySites {
27 27 private String appid;
28 28  
29 29 /**
30   - * 免审业务
  30 + * 免审业务,多种用,分割
31 31 */
32 32 private String write_business;
33 33  
... ... @@ -138,18 +138,18 @@ public class ShySites {
138 138 }
139 139  
140 140 /**
141   - * 获取免审业务
  141 + * 获取免审业务,多种用,分割
142 142 *
143   - * @return write_business - 免审业务
  143 + * @return write_business - 免审业务,多种用,分割
144 144 */
145 145 public String getWrite_business() {
146 146 return write_business;
147 147 }
148 148  
149 149 /**
150   - * 设置免审业务
  150 + * 设置免审业务,多种用,分割
151 151 *
152   - * @param write_business 免审业务
  152 + * @param write_business 免审业务,多种用,分割
153 153 */
154 154 public void setWrite_business(String write_business) {
155 155 this.write_business = write_business;
... ...
src/main/java/com/cnlive/shenhe/entity/ShyUsers.java
... ... @@ -14,18 +14,6 @@ public class ShyUsers {
14 14 private String username;
15 15  
16 16 /**
17   - * 大网用户id
18   - */
19   - private Integer sid;
20   -
21   - private String remember_token;
22   -
23   - /**
24   - * 联系人
25   - */
26   - private String contacts;
27   -
28   - /**
29 17 * 邮箱
30 18 */
31 19 private String email;
... ... @@ -67,7 +55,9 @@ public class ShyUsers {
67 55 /**
68 56 * 接口最后一次更新时间
69 57 */
70   - private String tm;
  58 + private Long tm;
  59 +
  60 + private String user_logo;
71 61  
72 62 /**
73 63 * @return id
... ... @@ -102,56 +92,6 @@ public class ShyUsers {
102 92 }
103 93  
104 94 /**
105   - * 获取大网用户id
106   - *
107   - * @return sid - 大网用户id
108   - */
109   - public Integer getSid() {
110   - return sid;
111   - }
112   -
113   - /**
114   - * 设置大网用户id
115   - *
116   - * @param sid 大网用户id
117   - */
118   - public void setSid(Integer sid) {
119   - this.sid = sid;
120   - }
121   -
122   - /**
123   - * @return remember_token
124   - */
125   - public String getRemember_token() {
126   - return remember_token;
127   - }
128   -
129   - /**
130   - * @param remember_token
131   - */
132   - public void setRemember_token(String remember_token) {
133   - this.remember_token = remember_token;
134   - }
135   -
136   - /**
137   - * 获取联系人
138   - *
139   - * @return contacts - 联系人
140   - */
141   - public String getContacts() {
142   - return contacts;
143   - }
144   -
145   - /**
146   - * 设置联系人
147   - *
148   - * @param contacts 联系人
149   - */
150   - public void setContacts(String contacts) {
151   - this.contacts = contacts;
152   - }
153   -
154   - /**
155 95 * 获取邮箱
156 96 *
157 97 * @return email - 邮箱
... ... @@ -310,7 +250,7 @@ public class ShyUsers {
310 250 *
311 251 * @return tm - 接口最后一次更新时间
312 252 */
313   - public String getTm() {
  253 + public Long getTm() {
314 254 return tm;
315 255 }
316 256  
... ... @@ -319,7 +259,21 @@ public class ShyUsers {
319 259 *
320 260 * @param tm 接口最后一次更新时间
321 261 */
322   - public void setTm(String tm) {
  262 + public void setTm(Long tm) {
323 263 this.tm = tm;
324 264 }
  265 +
  266 + /**
  267 + * @return user_logo
  268 + */
  269 + public String getUser_logo() {
  270 + return user_logo;
  271 + }
  272 +
  273 + /**
  274 + * @param user_logo
  275 + */
  276 + public void setUser_logo(String user_logo) {
  277 + this.user_logo = user_logo;
  278 + }
325 279 }
326 280 \ No newline at end of file
... ...
src/main/java/com/cnlive/shenhe/job/UsersJob.java
1 1 package com.cnlive.shenhe.job;
2 2  
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.JSONArray;
  5 +import com.alibaba.fastjson.JSONObject;
3 6 import com.cnlive.shenhe.entity.ShyUsers;
4 7 import com.cnlive.shenhe.mapper.ShyUsersMapper;
5   -import com.cnlive.shenhe.serviceImpl.UsersServiceImpl;
  8 +import com.cnlive.shenhe.utils.*;
6 9 import org.slf4j.Logger;
7 10 import org.slf4j.LoggerFactory;
8 11 import org.springframework.beans.factory.annotation.Autowired;
  12 +import org.springframework.beans.factory.annotation.Value;
  13 +import org.springframework.scheduling.annotation.Scheduled;
9 14 import org.springframework.stereotype.Component;
10 15 import tk.mybatis.mapper.entity.Example;
11 16  
12   -import java.util.List;
  17 +import java.io.UnsupportedEncodingException;
  18 +import java.net.URLEncoder;
  19 +import java.util.*;
13 20  
14 21 /**
15 22 * @Auther: 周伟鹏
... ... @@ -20,19 +27,150 @@ import java.util.List;
20 27 public class UsersJob {
21 28 private static Logger logger = LoggerFactory.getLogger(UsersJob.class);
22 29  
  30 + @Value("${sync_users_api}")
  31 + private String syncUserApi;
  32 +
  33 + @Value("${sync_users_app_key}")
  34 + private String app_key;
23 35  
24 36 @Autowired
25 37 ShyUsersMapper shyUsersMapper;
26 38  
27   - //@Scheduled(fixedRate = 30*60 * 1000)
  39 +
  40 + @Scheduled(fixedRate = 30 * 60 * 1000)
28 41 public void syncUsers() {
29   - long tm = 0L;
30   - Example usersExample = new Example(ShyUsers.class);
31   - usersExample.setOrderByClause("tm desc");
32   - List<ShyUsers> usersList = shyUsersMapper.selectByExample(usersExample);
33   - if(!usersList.isEmpty()){
34   - String tmStr = usersList.get(0).getTm();
  42 + try {
  43 + String tm = "0";
  44 + Example usersExample = new Example(ShyUsers.class);
  45 + usersExample.setOrderByClause("tm desc");
  46 + List<ShyUsers> usersList = shyUsersMapper.selectByExample(usersExample);
  47 + if (!usersList.isEmpty()) {
  48 + Long tmStr = usersList.get(0).getTm();
  49 + if (CommonUtils.isNotNull(tmStr)) tm = tmStr + "";
  50 + }
  51 + HashMap<String, String> dataMap = new HashMap<>();
  52 + dataMap.put("tm", tm);
  53 + dataMap.put("timestamp", new Date().getTime() / 1000 + "");
  54 + String httpUrl = OpenUtil.buildURL(syncUserApi, dataMap, app_key);
  55 + logger.info("httpUrl===" + httpUrl);
  56 + Map<String, String> resultMap = HttpUtil.init().post(httpUrl);
  57 + JSONObject result = JSON.parseObject(resultMap.get("result"));
  58 + String errorCode = result.getString("errorCode");
  59 + if ("0".equals(errorCode)) {
  60 + JSONArray data = result.getJSONArray("data");
  61 + for (int i = 0; i < data.size(); i++) {
  62 + JSONObject user = data.getJSONObject(i);
  63 + Integer id = user.getInteger("sid");
  64 + String email = user.getString("email");
  65 + Integer spid = user.getInteger("new_sp_id");
  66 + String userLogo = user.getString("userLogo");
  67 + boolean master = user.getBoolean("master");
  68 + Long utm = user.getLong("tm");
  69 + String username = user.getString("contacts");
  70 + boolean status = user.getIntValue("status") == CommonConst.USER_STATUS_USE;
  71 + if (CommonUtils.isEmpty(username)) {
  72 + username = Integer.toString(id);
  73 + }
  74 + String mobile = user.getString("mobile");
  75 + String company_brief = user.getString("sname");
  76 + String company = user.getString("company");
  77 + ShyUsers shyUsers = new ShyUsers();
  78 + shyUsers.setEmail(email);
  79 + shyUsers.setId(id);
  80 + shyUsers.setSp_id(spid);
  81 + shyUsers.setMaster(master);
  82 + shyUsers.setState(status);
  83 + shyUsers.setMobile(mobile);
  84 + shyUsers.setUsername(username);
  85 + shyUsers.setCompany_brief(company_brief);
  86 + shyUsers.setCompany_name(company);
  87 + shyUsers.setUser_logo(userLogo);
  88 + shyUsers.setTm(utm);
  89 + ShyUsers old_shyUsers = shyUsersMapper.selectByPrimaryKey(id);
  90 + if (CommonUtils.isNull(old_shyUsers)) {
  91 + shyUsersMapper.insertSelective(shyUsers);
  92 + } else {
  93 + shyUsersMapper.updateByPrimaryKeySelective(shyUsers);
  94 + }
  95 + }
  96 + } else {
  97 + logger.error("请求用户云失败,errorCode:{},errorMessage{}", errorCode, result.getString("errorMessage"));
  98 + }
  99 +
  100 + } catch (Exception e) {
  101 + e.printStackTrace();
  102 + }
  103 +
  104 + }
  105 +
  106 +
  107 + /**
  108 + * 生成URL
  109 + *
  110 + * @param url
  111 + * @param params
  112 + * @param app_key
  113 + * @return
  114 + */
  115 + public static String buildURL(String url, Map<String, String> params, String app_key) {
  116 + Map<String, String> map = order(params);
  117 + if (map.containsKey("sign")) {
  118 + map.remove("sign");
35 119 }
  120 + String str = mapJoin(map, true, false);
  121 + String sign = SHA1.SHA1Digest(str + "&key=" + app_key).toUpperCase();
  122 + map.put("sign", sign);
  123 + return url + "?" + mapJoin(map, false, true);
  124 + }
  125 +
  126 + /**
  127 + * Map key 排序
  128 + *
  129 + * @param map
  130 + * @return
  131 + */
  132 + private static Map<String, String> order(Map<String, String> map) {
  133 + HashMap<String, String> tempMap = new LinkedHashMap<String, String>();
  134 + List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
  135 +
  136 + Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
  137 + public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
  138 + return (o1.getKey()).toString().compareTo(o2.getKey());
  139 + }
  140 + });
  141 +
  142 + for (int i = 0; i < infoIds.size(); i++) {
  143 + Map.Entry<String, String> item = infoIds.get(i);
  144 + tempMap.put(item.getKey(), item.getValue());
  145 + }
  146 + return tempMap;
  147 + }
36 148  
  149 + /**
  150 + * url 参数串连
  151 + *
  152 + * @param map
  153 + * @param keyLower
  154 + * @param valueUrlencode
  155 + * @return
  156 + */
  157 + private static String mapJoin(Map<String, String> map, boolean keyLower, boolean valueUrlencode) {
  158 + StringBuilder stringBuilder = new StringBuilder();
  159 + for (String key : map.keySet()) {
  160 + if (map.get(key) != null && !"".equals(map.get(key))) {
  161 + try {
  162 + stringBuilder.append(key)
  163 + .append("=")
  164 + .append(valueUrlencode ? URLEncoder.encode(map.get(key), "utf-8").replace("+", "%20") : map.get(key))
  165 + .append("&");
  166 + } catch (UnsupportedEncodingException e) {
  167 + e.printStackTrace();
  168 + }
  169 + }
  170 + }
  171 + if (stringBuilder.length() > 0) {
  172 + stringBuilder.deleteCharAt(stringBuilder.length() - 1);
  173 + }
  174 + return stringBuilder.toString();
37 175 }
38 176 }
... ...
src/main/java/com/cnlive/shenhe/utils/CommonConst.java
... ... @@ -20,6 +20,13 @@ public class CommonConst {
20 20 public static Integer AUDIT_REFUSE = 2;
21 21  
22 22  
23   -
  23 + /**
  24 + * 用户状态:可用
  25 + */
  26 + public static Integer USER_STATUS_USE = 1;
  27 + /**
  28 + * 用户状态:禁用
  29 + */
  30 + public static Integer USER_STATUS_FORBID = 2;
24 31  
25 32 }
... ...
src/main/java/com/cnlive/shenhe/utils/HttpUtil.java 0 → 100644
  1 +package com.cnlive.shenhe.utils;
  2 +
  3 +import org.apache.http.Header;
  4 +import org.apache.http.HttpEntity;
  5 +import org.apache.http.HttpStatus;
  6 +import org.apache.http.NameValuePair;
  7 +import org.apache.http.auth.AuthScope;
  8 +import org.apache.http.auth.UsernamePasswordCredentials;
  9 +import org.apache.http.client.CredentialsProvider;
  10 +import org.apache.http.client.config.RequestConfig;
  11 +import org.apache.http.client.config.RequestConfig.Builder;
  12 +import org.apache.http.client.entity.UrlEncodedFormEntity;
  13 +import org.apache.http.client.methods.CloseableHttpResponse;
  14 +import org.apache.http.client.methods.HttpGet;
  15 +import org.apache.http.client.methods.HttpPost;
  16 +import org.apache.http.client.methods.HttpUriRequest;
  17 +import org.apache.http.client.utils.URIBuilder;
  18 +import org.apache.http.entity.ContentType;
  19 +import org.apache.http.entity.StringEntity;
  20 +import org.apache.http.entity.mime.MultipartEntityBuilder;
  21 +import org.apache.http.entity.mime.content.FileBody;
  22 +import org.apache.http.impl.client.BasicCredentialsProvider;
  23 +import org.apache.http.impl.client.CloseableHttpClient;
  24 +import org.apache.http.impl.client.HttpClients;
  25 +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  26 +import org.apache.http.message.BasicHeader;
  27 +import org.apache.http.message.BasicNameValuePair;
  28 +import org.apache.http.util.EntityUtils;
  29 +import org.slf4j.Logger;
  30 +import org.slf4j.LoggerFactory;
  31 +import org.springframework.util.CollectionUtils;
  32 +import org.springframework.util.StringUtils;
  33 +
  34 +import java.io.File;
  35 +import java.io.InputStream;
  36 +import java.io.UnsupportedEncodingException;
  37 +import java.net.URI;
  38 +import java.net.URISyntaxException;
  39 +import java.nio.charset.UnsupportedCharsetException;
  40 +import java.util.ArrayList;
  41 +import java.util.HashMap;
  42 +import java.util.List;
  43 +import java.util.Map;
  44 +import java.util.Map.Entry;
  45 +
  46 +/**
  47 + * http请求工具类
  48 + *
  49 + * @author liujiong
  50 + */
  51 +public class HttpUtil {
  52 +
  53 + private Logger logger = LoggerFactory.getLogger(HttpUtil.class);
  54 +
  55 + private static PoolingHttpClientConnectionManager pcm;//httpclient连接池
  56 + private CloseableHttpClient httpClient = null; //http连接
  57 + private int connectTimeout = 120000;//连接超时时间
  58 + private int connectionRequestTimeout = 10000;//从连接池获取连接超时时间
  59 + private int socketTimeout = 300000;//获取数据超时时间
  60 + private String charset = "utf-8";
  61 + private RequestConfig requestConfig = null;//请求配置
  62 + private Builder requestConfigBuilder = null;//build requestConfig
  63 +
  64 + private List<NameValuePair> nvps = new ArrayList<>();
  65 + private List<Header> headers = new ArrayList<>();
  66 + private String requestParam = "";
  67 +
  68 + static {
  69 + pcm = new PoolingHttpClientConnectionManager();
  70 + pcm.setMaxTotal(50);//整个连接池最大连接数
  71 + pcm.setDefaultMaxPerRoute(50);//每路由最大连接数,默认值是2
  72 + }
  73 +
  74 + /**
  75 + * 默认设置
  76 + *
  77 + * @author Liu Jiong
  78 + * @createDate 2016年10月30日
  79 + */
  80 + private static HttpUtil defaultInit() {
  81 + HttpUtil httpUtil = new HttpUtil();
  82 + if (httpUtil.requestConfig == null) {
  83 + httpUtil.requestConfigBuilder = RequestConfig.custom().setConnectTimeout(httpUtil.connectTimeout)
  84 + .setConnectionRequestTimeout(httpUtil.connectionRequestTimeout)
  85 + .setSocketTimeout(httpUtil.socketTimeout);
  86 + httpUtil.requestConfig = httpUtil.requestConfigBuilder.build();
  87 + }
  88 + return httpUtil;
  89 + }
  90 +
  91 + /**
  92 + * 初始化 httpUtil
  93 + */
  94 + public static HttpUtil init() {
  95 + HttpUtil httpUtil = defaultInit();
  96 + if (httpUtil.httpClient == null) {
  97 + httpUtil.httpClient = HttpClients.custom().setConnectionManager(pcm).build();
  98 + }
  99 + return httpUtil;
  100 + }
  101 +
  102 + /**
  103 + * 初始化 httpUtil
  104 + */
  105 + public static HttpUtil init(Map<String, String> paramMap) {
  106 + HttpUtil httpUtil = init();
  107 + httpUtil.setParamMap(paramMap);
  108 + return httpUtil;
  109 + }
  110 +
  111 + /**
  112 + * 验证初始化
  113 + */
  114 + public static HttpUtil initWithAuth(String ip, int port, String username, String password) {
  115 + HttpUtil httpUtil = defaultInit();
  116 + if (httpUtil.httpClient == null) {
  117 + CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  118 + credentialsProvider.setCredentials(new AuthScope(ip, port, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password));
  119 + httpUtil.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
  120 + .setConnectionManager(pcm).build();
  121 + }
  122 + return httpUtil;
  123 + }
  124 +
  125 + /**
  126 + * 设置请求头
  127 + */
  128 + public HttpUtil setHeader(String name, String value) {
  129 + Header header = new BasicHeader(name, value);
  130 + headers.add(header);
  131 + return this;
  132 + }
  133 +
  134 + /**
  135 + * 设置请求头
  136 + */
  137 + public HttpUtil setHeaderMap(Map<String, String> headerMap) {
  138 + for (Entry<String, String> param : headerMap.entrySet()) {
  139 + Header header = new BasicHeader(param.getKey(), param.getValue());
  140 + headers.add(header);
  141 + }
  142 + return this;
  143 + }
  144 +
  145 + /**
  146 + * 设置请求参数
  147 + */
  148 + public HttpUtil setParam(String name, String value) {
  149 + nvps.add(new BasicNameValuePair(name, value));
  150 + return this;
  151 + }
  152 +
  153 + /**
  154 + * 设置请求参数
  155 + */
  156 + public HttpUtil setParamMap(Map<String, String> paramMap) {
  157 + for (Entry<String, String> param : paramMap.entrySet()) {
  158 + nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
  159 + }
  160 + return this;
  161 + }
  162 +
  163 + /**
  164 + * 设置字符串参数
  165 + */
  166 + public HttpUtil setStringParam(String requestParam) {
  167 + this.requestParam = requestParam;
  168 + return this;
  169 + }
  170 +
  171 + /**
  172 + * 设置连接超时时间
  173 + */
  174 + public HttpUtil setConnectTimeout(int connectTimeout) {
  175 + this.connectTimeout = connectTimeout;
  176 + this.requestConfigBuilder = requestConfigBuilder.setConnectTimeout(connectTimeout);
  177 + requestConfig = requestConfigBuilder.build();
  178 + return this;
  179 + }
  180 +
  181 + /**
  182 + * http get 请求
  183 + */
  184 + public Map<String, String> get(String url) {
  185 + Map<String, String> resultMap = new HashMap<>();
  186 + //获取请求URI
  187 + URI uri = getUri(url);
  188 + if (uri != null) {
  189 + HttpGet httpGet = new HttpGet(uri);
  190 + httpGet.setConfig(requestConfig);
  191 + if (!CollectionUtils.isEmpty(headers)) {
  192 + Header[] header = new Header[headers.size()];
  193 + httpGet.setHeaders(headers.toArray(header));
  194 + }
  195 +
  196 + //执行get请求
  197 + try {
  198 + CloseableHttpResponse response = httpClient.execute(httpGet);
  199 + return getHttpResult(response, url, httpGet, resultMap);
  200 + } catch (Exception e) {
  201 + httpGet.abort();
  202 + resultMap.put("result", e.getMessage());
  203 + logger.error("获取http GET请求返回值失败 url======" + url, e);
  204 + }
  205 + }
  206 + return resultMap;
  207 + }
  208 +
  209 + /**
  210 + * http post 请求
  211 + */
  212 + public Map<String, String> post(String url) {
  213 + HttpPost httpPost = new HttpPost(url);
  214 + httpPost.setConfig(requestConfig);
  215 + if (!CollectionUtils.isEmpty(headers)) {
  216 + Header[] header = new Header[headers.size()];
  217 + httpPost.setHeaders(headers.toArray(header));
  218 + }
  219 + if (!CollectionUtils.isEmpty(nvps)) {
  220 + try {
  221 + httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
  222 + } catch (UnsupportedEncodingException e) {
  223 + logger.error("http post entity form error", e);
  224 + }
  225 + }
  226 + if (!StringUtils.isEmpty(requestParam)) {
  227 + try {
  228 + httpPost.setEntity(new StringEntity(requestParam, charset));
  229 + } catch (UnsupportedCharsetException e) {
  230 + logger.error("http post entity form error", e);
  231 + }
  232 + }
  233 + Map<String, String> resultMap = new HashMap<>();
  234 + //执行post请求
  235 + try {
  236 + CloseableHttpResponse response = httpClient.execute(httpPost);
  237 + return getHttpResult(response, url, httpPost, resultMap);
  238 + } catch (Exception e) {
  239 + httpPost.abort();
  240 + resultMap.put("result", e.getMessage());
  241 + logger.error("获取http POST请求返回值失败 url======" + url, e);
  242 + }
  243 + return resultMap;
  244 + }
  245 +
  246 + /**
  247 + * post 上传文件
  248 + */
  249 + public Map<String, String> postUploadFile(String url, Map<String, File> fileParam) {
  250 + HttpPost httpPost = new HttpPost(url);
  251 + httpPost.setConfig(requestConfig);
  252 + if (!CollectionUtils.isEmpty(headers)) {
  253 + Header[] header = new Header[headers.size()];
  254 + httpPost.setHeaders(headers.toArray(header));
  255 + }
  256 +
  257 + MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  258 + if (fileParam != null) {
  259 + for (Entry<String, File> entry : fileParam.entrySet()) {
  260 + //将要上传的文件转化为文件流
  261 + FileBody fileBody = new FileBody(entry.getValue());
  262 + //设置请求参数
  263 + builder.addPart(entry.getKey(), fileBody);
  264 + }
  265 + }
  266 +
  267 + if (!CollectionUtils.isEmpty(nvps)) {
  268 + for (NameValuePair nvp : nvps) {
  269 + String value = nvp.getValue();
  270 + if (!StringUtils.isEmpty(value)) {
  271 + builder.addTextBody(nvp.getName(), value, ContentType.create("text/plain", charset));
  272 + }
  273 + }
  274 + }
  275 + httpPost.setEntity(builder.build());
  276 + Map<String, String> resultMap = new HashMap<>();
  277 + //执行post请求
  278 + try {
  279 + CloseableHttpResponse response = httpClient.execute(httpPost);
  280 + return getHttpResult(response, url, httpPost, resultMap);
  281 + } catch (Exception e) {
  282 + httpPost.abort();
  283 + resultMap.put("result", e.getMessage());
  284 + logger.error("获取http postUploadFile 请求返回值失败 url======" + url, e);
  285 + }
  286 + return resultMap;
  287 + }
  288 +
  289 + /**
  290 + * 获取请求返回值
  291 + */
  292 + private Map<String, String> getHttpResult(CloseableHttpResponse response, String url, HttpUriRequest request, Map<String, String> resultMap) {
  293 + String result = "";
  294 + int statusCode = response.getStatusLine().getStatusCode();
  295 + resultMap.put("statusCode", statusCode + "");
  296 + HttpEntity entity = response.getEntity();
  297 + if (entity != null) {
  298 + try {
  299 + result = EntityUtils.toString(entity, charset);
  300 + EntityUtils.consume(entity);//释放连接
  301 + } catch (Exception e) {
  302 + logger.error("获取http请求返回值解析失败", e);
  303 + request.abort();
  304 + }
  305 + }
  306 + if (statusCode != 200) {
  307 + result = "HttpClient status code :" + statusCode + " request url===" + url;
  308 + logger.info("HttpClient status code :" + statusCode + " request url===" + url);
  309 + request.abort();
  310 + }
  311 + resultMap.put("result", result);
  312 + return resultMap;
  313 + }
  314 +
  315 + /**
  316 + * 获取重定向url返回的location
  317 + */
  318 + public String redirectLocation(String url) {
  319 + String location = "";
  320 + //获取请求URI
  321 + URI uri = getUri(url);
  322 + if (uri != null) {
  323 + HttpGet httpGet = new HttpGet(uri);
  324 + requestConfig = requestConfigBuilder.setRedirectsEnabled(false).build();//设置自动重定向false
  325 + httpGet.setConfig(requestConfig);
  326 + if (!CollectionUtils.isEmpty(headers)) {
  327 + Header[] header = new Header[headers.size()];
  328 + httpGet.setHeaders(headers.toArray(header));
  329 + }
  330 +
  331 + try {
  332 + //执行get请求
  333 + CloseableHttpResponse response = httpClient.execute(httpGet);
  334 + int statusCode = response.getStatusLine().getStatusCode();
  335 + if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {//301 302
  336 + Header header = response.getFirstHeader("Location");
  337 + if (header != null) {
  338 + location = header.getValue();
  339 + }
  340 + }
  341 + HttpEntity entity = response.getEntity();
  342 + if (entity != null) {
  343 + EntityUtils.consume(entity);
  344 + }
  345 + } catch (Exception e) {
  346 + logger.error("获取http GET请求获取 302 Location失败 url======" + url, e);
  347 + httpGet.abort();
  348 + }
  349 + }
  350 + return location;
  351 + }
  352 +
  353 + /**
  354 + * 获取输入流
  355 + */
  356 + public InputStream getInputStream(String url) {
  357 + //获取请求URI
  358 + URI uri = getUri(url);
  359 + if (uri != null) {
  360 + HttpGet httpGet = new HttpGet(uri);
  361 + httpGet.setConfig(requestConfig);
  362 + if (!CollectionUtils.isEmpty(headers)) {
  363 + Header[] header = new Header[headers.size()];
  364 + httpGet.setHeaders(headers.toArray(header));
  365 + }
  366 + //执行get请求
  367 + try {
  368 + CloseableHttpResponse response = httpClient.execute(httpGet);
  369 + int statusCode = response.getStatusLine().getStatusCode();
  370 + if (statusCode != 200) {
  371 + logger.info("HttpClient status code :" + statusCode + " request url===" + url);
  372 + httpGet.abort();
  373 + } else {
  374 + HttpEntity entity = response.getEntity();
  375 + if (entity != null) {
  376 + InputStream in = entity.getContent();
  377 + return in;
  378 + }
  379 + }
  380 + } catch (Exception e) {
  381 + logger.error("获取http GET inputStream请求失败 url======" + url, e);
  382 + httpGet.abort();
  383 + }
  384 + }
  385 + return null;
  386 + }
  387 +
  388 + private URI getUri(String url) {
  389 + URI uri = null;
  390 + try {
  391 + URIBuilder uriBuilder = new URIBuilder(url);
  392 + if (!CollectionUtils.isEmpty(nvps)) {
  393 + uriBuilder.setParameters(nvps);
  394 + }
  395 + uri = uriBuilder.build();
  396 + } catch (URISyntaxException e) {
  397 + logger.error("url 地址异常", e);
  398 + }
  399 + return uri;
  400 + }
  401 +}
... ...
src/main/java/com/cnlive/shenhe/utils/OpenUtil.java 0 → 100644
  1 +package com.cnlive.shenhe.utils;
  2 +
  3 +import javax.servlet.ServletRequest;
  4 +import java.io.UnsupportedEncodingException;
  5 +import java.net.URLDecoder;
  6 +import java.net.URLEncoder;
  7 +import java.util.*;
  8 +
  9 +public class OpenUtil {
  10 +
  11 +
  12 + /**
  13 + * 验证签名
  14 + * 用于服务端
  15 + */
  16 + public static boolean validateSign(ServletRequest request, String spKey) {
  17 + return validateSign(request, spKey, null);
  18 + }
  19 +
  20 + /**
  21 + * 验证签名
  22 + */
  23 + private static boolean validateSign(ServletRequest request, String spKey, String... ignore) {
  24 + Map<String, String> map = getRequestParam(request);
  25 + String sign = map.get("sign");
  26 + map.remove("sign");
  27 + if (ignore != null) {
  28 + for (String key : ignore) {
  29 + map.remove(key);
  30 + }
  31 + }
  32 + map = order(map);
  33 + String str = mapJoin(map, false);
  34 + String mySign = SHA1.SHA1Digest(str + "&key=" + spKey).toUpperCase();
  35 + return mySign.equals(sign);
  36 + }
  37 +
  38 + /**
  39 + * 生成get 请求 URL
  40 + */
  41 + public static String buildURL(String url, Map<String, String> params, String spKey) {
  42 + Map<String, String> map = order(params);
  43 + if (map.containsKey("sign")) {
  44 + map.remove("sign");
  45 + }
  46 + String str = mapJoin(map, false);
  47 +
  48 + String sign = SHA1.SHA1Digest(str + "&key=" + spKey).toUpperCase();
  49 + map.put("sign", sign);
  50 + return url + "?" + mapJoin(map, true);
  51 + }
  52 +
  53 + /**
  54 + * 生成签名 sign
  55 + */
  56 + public static String sign(Map<String, String> params, String spKey) {
  57 + Map<String, String> map = order(params);
  58 + if (map.containsKey("sign")) {
  59 + map.remove("sign");
  60 + }
  61 + String str = mapJoin(map, false);
  62 + return SHA1.SHA1Digest(str + "&key=" + spKey).toUpperCase();
  63 + }
  64 +
  65 + /**
  66 + * 获取请求参数
  67 + */
  68 + private static Map<String, String> getRequestParam(ServletRequest request) {
  69 + Map<String, String> map = new LinkedHashMap<>();
  70 + Map<String, String[]> map2 = request.getParameterMap();
  71 + for (String key : map2.keySet()) {
  72 + if (map2.get(key) == null || map2.get(key).length == 0) {
  73 + map.put(key, null);
  74 + } else {
  75 + try {
  76 + String value = URLDecoder.decode(map2.get(key)[0], "utf-8");
  77 + map.put(key, value);
  78 + } catch (UnsupportedEncodingException e) {
  79 + e.printStackTrace();
  80 + }
  81 + }
  82 + }
  83 + return map;
  84 + }
  85 +
  86 + /**
  87 + * 获取附加参数
  88 + */
  89 + public static Map<String, String> getAttachParam(ServletRequest servletRequest, boolean attachKey) {
  90 + Map<String, String[]> maps = servletRequest.getParameterMap();
  91 + Map<String, String> map = new LinkedHashMap<String, String>();
  92 + for (String key : maps.keySet()) {
  93 + String[] vk = key.split("\\.");
  94 + if (vk.length == 2 && vk[0].equals("attach")) {
  95 + map.put(attachKey ? key : vk[1], maps.get(key)[0]);
  96 + }
  97 + }
  98 + return map;
  99 + }
  100 +
  101 +
  102 + /**
  103 + * url 参数串连
  104 + */
  105 + private static String mapJoin(Map<String, String> map, boolean valueUrlencode) {
  106 + StringBuilder stringBuilder = new StringBuilder();
  107 + for (String key : map.keySet()) {
  108 + if (map.get(key) != null && !"".equals(map.get(key))) {
  109 + try {
  110 + stringBuilder.append(key)
  111 + .append("=")
  112 + .append(valueUrlencode ? URLEncoder.encode(map.get(key), "utf-8").replace("+", "%20") : map.get(key))
  113 + .append("&");
  114 + } catch (UnsupportedEncodingException e) {
  115 + e.printStackTrace();
  116 + }
  117 + }
  118 + }
  119 + if (stringBuilder.length() > 0) {
  120 + stringBuilder.deleteCharAt(stringBuilder.length() - 1);
  121 + }
  122 + return stringBuilder.toString();
  123 + }
  124 +
  125 +
  126 + /**
  127 + * Map key 排序
  128 + */
  129 + private static Map<String, String> order(Map<String, String> map) {
  130 + HashMap<String, String> tempMap = new LinkedHashMap<>();
  131 + List<Map.Entry<String, String>> infoIds = new ArrayList<>(map.entrySet());
  132 +
  133 + infoIds.sort(new Comparator<Map.Entry<String, String>>() {
  134 + @Override
  135 + public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
  136 + return (o1.getKey()).compareTo(o2.getKey());
  137 + }
  138 + });
  139 +
  140 + for (Map.Entry<String, String> item : infoIds) {
  141 + tempMap.put(item.getKey(), item.getValue());
  142 + }
  143 + return tempMap;
  144 + }
  145 +
  146 +}
... ...
src/main/java/com/cnlive/shenhe/utils/SHA1.java 0 → 100644
  1 +package com.cnlive.shenhe.utils;
  2 +
  3 +import java.io.UnsupportedEncodingException;
  4 +import java.math.BigInteger;
  5 +import java.security.MessageDigest;
  6 +import java.security.NoSuchAlgorithmException;
  7 +
  8 +public class SHA1 {
  9 +
  10 + private final int[] abcde = { 0x67452301, 0xefcdab89, 0x98badcfe,
  11 + 0x10325476, 0xc3d2e1f0 };
  12 +
  13 + // 摘要数据存储数组
  14 + private int[] digestInt = new int[5];
  15 +
  16 + // 计算过程中的临时数据存储数组
  17 + private int[] tmpData = new int[80];
  18 +
  19 + /**
  20 + * 计算sha-1摘要
  21 + *
  22 + * @param bytedata
  23 + * @return
  24 + */
  25 + private int process_input_bytes(byte[] bytedata) {
  26 + // 初试化常量
  27 + System.arraycopy(abcde, 0, digestInt, 0, abcde.length);
  28 + // 格式化输入字节数组,补10及长度数据
  29 + byte[] newbyte = byteArrayFormatData(bytedata);
  30 + // 获取数据摘要计算的数据单元个数
  31 + int MCount = newbyte.length / 64;
  32 + // 循环对每个数据单元进行摘要计算
  33 + for (int pos = 0; pos < MCount; pos++) {
  34 + // 将每个单元的数据转换成16个整型数据,并保存到tmpData的前16个数组元素中
  35 + for (int j = 0; j < 16; j++) {
  36 + tmpData[j] = byteArrayToInt(newbyte, (pos * 64) + (j * 4));
  37 + }
  38 + // 摘要计算函数
  39 + encrypt();
  40 + }
  41 + return 20;
  42 + }
  43 +
  44 + /**
  45 + * 格式化输入字节数组格式
  46 + *
  47 + * @param bytedata
  48 + * @return
  49 + */
  50 + private byte[] byteArrayFormatData(byte[] bytedata) {
  51 + // 补0数量
  52 + int zeros = 0;
  53 + // 补位后总位数
  54 + int size = 0;
  55 + // 原始数据长度
  56 + int n = bytedata.length;
  57 + // 模64后的剩余位数
  58 + int m = n % 64;
  59 + // 计算添加0的个数以及添加10后的总长度
  60 + if (m < 56) {
  61 + zeros = 55 - m;
  62 + size = n - m + 64;
  63 + } else if (m == 56) {
  64 + zeros = 63;
  65 + size = n + 8 + 64;
  66 + } else {
  67 + zeros = 63 - m + 56;
  68 + size = (n + 64) - m + 64;
  69 + }
  70 + // 补位后生成的新数组内容
  71 + byte[] newbyte = new byte[size];
  72 + // 复制数组的前面部分
  73 + System.arraycopy(bytedata, 0, newbyte, 0, n);
  74 + // 获得数组Append数据元素的位置
  75 + int l = n;
  76 + // 补1操作
  77 + newbyte[l++] = (byte) 0x80;
  78 + // 补0操作
  79 + for (int i = 0; i < zeros; i++) {
  80 + newbyte[l++] = (byte) 0x00;
  81 + }
  82 + // 计算数据长度,补数据长度位共8字节,长整型
  83 + long N = (long) n * 8;
  84 + byte h8 = (byte) (N & 0xFF);
  85 + byte h7 = (byte) ((N >> 8) & 0xFF);
  86 + byte h6 = (byte) ((N >> 16) & 0xFF);
  87 + byte h5 = (byte) ((N >> 24) & 0xFF);
  88 + byte h4 = (byte) ((N >> 32) & 0xFF);
  89 + byte h3 = (byte) ((N >> 40) & 0xFF);
  90 + byte h2 = (byte) ((N >> 48) & 0xFF);
  91 + byte h1 = (byte) (N >> 56);
  92 + newbyte[l++] = h1;
  93 + newbyte[l++] = h2;
  94 + newbyte[l++] = h3;
  95 + newbyte[l++] = h4;
  96 + newbyte[l++] = h5;
  97 + newbyte[l++] = h6;
  98 + newbyte[l++] = h7;
  99 + newbyte[l++] = h8;
  100 + return newbyte;
  101 + }
  102 +
  103 + private int f1(int x, int y, int z) {
  104 + return (x & y) | (~x & z);
  105 + }
  106 +
  107 + private int f2(int x, int y, int z) {
  108 + return x ^ y ^ z;
  109 + }
  110 +
  111 + private int f3(int x, int y, int z) {
  112 + return (x & y) | (x & z) | (y & z);
  113 + }
  114 +
  115 + private int f4(int x, int y) {
  116 + return (x << y) | x >>> (32 - y);
  117 + }
  118 +
  119 + /**
  120 + * 单元摘要计算函数
  121 + */
  122 + private void encrypt() {
  123 + for (int i = 16; i <= 79; i++) {
  124 + tmpData[i] = f4(tmpData[i - 3] ^ tmpData[i - 8] ^ tmpData[i - 14]
  125 + ^ tmpData[i - 16], 1);
  126 + }
  127 + int[] tmpabcde = new int[5];
  128 + for (int i1 = 0; i1 < tmpabcde.length; i1++) {
  129 + tmpabcde[i1] = digestInt[i1];
  130 + }
  131 + for (int j = 0; j <= 19; j++) {
  132 + int tmp = f4(tmpabcde[0], 5)
  133 + + f1(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4]
  134 + + tmpData[j] + 0x5a827999;
  135 + tmpabcde[4] = tmpabcde[3];
  136 + tmpabcde[3] = tmpabcde[2];
  137 + tmpabcde[2] = f4(tmpabcde[1], 30);
  138 + tmpabcde[1] = tmpabcde[0];
  139 + tmpabcde[0] = tmp;
  140 + }
  141 + for (int k = 20; k <= 39; k++) {
  142 + int tmp = f4(tmpabcde[0], 5)
  143 + + f2(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4]
  144 + + tmpData[k] + 0x6ed9eba1;
  145 + tmpabcde[4] = tmpabcde[3];
  146 + tmpabcde[3] = tmpabcde[2];
  147 + tmpabcde[2] = f4(tmpabcde[1], 30);
  148 + tmpabcde[1] = tmpabcde[0];
  149 + tmpabcde[0] = tmp;
  150 + }
  151 + for (int l = 40; l <= 59; l++) {
  152 + int tmp = f4(tmpabcde[0], 5)
  153 + + f3(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4]
  154 + + tmpData[l] + 0x8f1bbcdc;
  155 + tmpabcde[4] = tmpabcde[3];
  156 + tmpabcde[3] = tmpabcde[2];
  157 + tmpabcde[2] = f4(tmpabcde[1], 30);
  158 + tmpabcde[1] = tmpabcde[0];
  159 + tmpabcde[0] = tmp;
  160 + }
  161 + for (int m = 60; m <= 79; m++) {
  162 + int tmp = f4(tmpabcde[0], 5)
  163 + + f2(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4]
  164 + + tmpData[m] + 0xca62c1d6;
  165 + tmpabcde[4] = tmpabcde[3];
  166 + tmpabcde[3] = tmpabcde[2];
  167 + tmpabcde[2] = f4(tmpabcde[1], 30);
  168 + tmpabcde[1] = tmpabcde[0];
  169 + tmpabcde[0] = tmp;
  170 + }
  171 + for (int i2 = 0; i2 < tmpabcde.length; i2++) {
  172 + digestInt[i2] = digestInt[i2] + tmpabcde[i2];
  173 + }
  174 + for (int n = 0; n < tmpData.length; n++) {
  175 + tmpData[n] = 0;
  176 + }
  177 + }
  178 +
  179 + /**
  180 + * 4字节数组转换为整数
  181 + *
  182 + * @param bytedata
  183 + * @param i
  184 + * @return
  185 + */
  186 + private int byteArrayToInt(byte[] bytedata, int i) {
  187 + return ((bytedata[i] & 0xff) << 24) | ((bytedata[i + 1] & 0xff) << 16)
  188 + | ((bytedata[i + 2] & 0xff) << 8) | (bytedata[i + 3] & 0xff);
  189 + }
  190 +
  191 + //
  192 + /**
  193 + * 整数转换为4字节数组
  194 + *
  195 + * @param intValue
  196 + * @param byteData
  197 + * @param i
  198 + */
  199 + private void intToByteArray(int intValue, byte[] byteData, int i) {
  200 + byteData[i] = (byte) (intValue >>> 24);
  201 + byteData[i + 1] = (byte) (intValue >>> 16);
  202 + byteData[i + 2] = (byte) (intValue >>> 8);
  203 + byteData[i + 3] = (byte) intValue;
  204 + }
  205 +
  206 + /**
  207 + * 将字节转换为十六进制字符串
  208 + *
  209 + * @param ib
  210 + * @return
  211 + */
  212 + private static String byteToHexString(byte ib) {
  213 + char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
  214 + 'B', 'C', 'D', 'E', 'F' };
  215 + char[] ob = new char[2];
  216 + ob[0] = Digit[(ib >>> 4) & 0X0F];
  217 + ob[1] = Digit[ib & 0X0F];
  218 + String s = new String(ob);
  219 + return s;
  220 + }
  221 +
  222 + /**
  223 + * 将字节数组转换为十六进制字符串
  224 + *
  225 + * @param bytearray
  226 + * @return
  227 + */
  228 + private static String byteArrayToHexString(byte[] bytearray) {
  229 + String strDigest = "";
  230 + for (int i = 0; i < bytearray.length; i++) {
  231 + strDigest += byteToHexString(bytearray[i]);
  232 + }
  233 + return strDigest;
  234 + }
  235 +
  236 + /**
  237 + * 计算sha-1摘要,返回相应的字节数组
  238 + *
  239 + * @param byteData
  240 + * @return
  241 + */
  242 + public byte[] getDigestOfBytes(byte[] byteData) {
  243 + process_input_bytes(byteData);
  244 + byte[] digest = new byte[20];
  245 + for (int i = 0; i < digestInt.length; i++) {
  246 + intToByteArray(digestInt[i], digest, i * 4);
  247 + }
  248 + return digest;
  249 + }
  250 +
  251 + /**
  252 + * 计算sha-1摘要,返回相应的十六进制字符串
  253 + *
  254 + * @param byteData
  255 + * @return
  256 + */
  257 + public String getDigestOfString(byte[] byteData) {
  258 + return byteArrayToHexString(getDigestOfBytes(byteData));
  259 + }
  260 +
  261 + /**
  262 + * @param data
  263 + * @return
  264 + */
  265 + public String Digest(String data){
  266 + return this.getDigestOfString(data.getBytes());
  267 + }
  268 +
  269 + /**
  270 + * @param data
  271 + * @return
  272 + */
  273 + public String Digest(String data,String encode){
  274 + try {
  275 + return this.getDigestOfString(data.getBytes(encode));
  276 + } catch (UnsupportedEncodingException e) {
  277 + return this.Digest(data);
  278 + }
  279 + }
  280 +
  281 + /**
  282 + * @param text
  283 + * @return
  284 + */
  285 + public static String SHA1Digest(String text) {
  286 + String pwd = "";
  287 + try {
  288 + MessageDigest md = MessageDigest.getInstance("SHA1");
  289 + md.update(text.getBytes());
  290 + pwd = new BigInteger(1, md.digest()).toString(16);
  291 + } catch (NoSuchAlgorithmException e) {
  292 + e.printStackTrace();
  293 + }
  294 + return pwd;
  295 + }
  296 +
  297 +}
0 298 \ No newline at end of file
... ...
src/main/resources/application.properties
... ... @@ -9,4 +9,8 @@ spring.jpa.show-sql= true
9 9  
10 10  
11 11 mybatis.mapper-locations=classpath:mapping/*.xml
12   -mybatis.type-aliases-package=com.cnlive.shenhe.entity
13 12 \ No newline at end of file
  13 +mybatis.type-aliases-package=com.cnlive.shenhe.entity
  14 +
  15 +
  16 +sync_users_api=http://api.cnlive.com/open/api2/inner2/shenhe/getuser
  17 +sync_users_app_key=314a9dd4-a9b7-4c12-bbbe-1150a36491ae
14 18 \ No newline at end of file
... ...
src/main/resources/mapper/ShyUsersMapper.xml
... ... @@ -7,9 +7,6 @@
7 7 -->
8 8 <id column="id" jdbcType="INTEGER" property="id" />
9 9 <result column="username" jdbcType="VARCHAR" property="username" />
10   - <result column="sid" jdbcType="INTEGER" property="sid" />
11   - <result column="remember_token" jdbcType="VARCHAR" property="remember_token" />
12   - <result column="contacts" jdbcType="VARCHAR" property="contacts" />
13 10 <result column="email" jdbcType="VARCHAR" property="email" />
14 11 <result column="master" jdbcType="BIT" property="master" />
15 12 <result column="mobile" jdbcType="VARCHAR" property="mobile" />
... ... @@ -19,6 +16,7 @@
19 16 <result column="state" jdbcType="BIT" property="state" />
20 17 <result column="created_at" jdbcType="TIMESTAMP" property="created_at" />
21 18 <result column="updated_at" jdbcType="TIMESTAMP" property="updated_at" />
22   - <result column="tm" jdbcType="VARCHAR" property="tm" />
  19 + <result column="tm" jdbcType="BIGINT" property="tm" />
  20 + <result column="user_logo" jdbcType="VARCHAR" property="user_logo" />
23 21 </resultMap>
24 22 </mapper>
25 23 \ No newline at end of file
... ...