UsersJob.java 6.55 KB
package com.cnlive.shenhe.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cnlive.shenhe.entity.ShyUsers;
import com.cnlive.shenhe.mapper.ShyUsersMapper;
import com.cnlive.shenhe.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther: 周伟鹏
 * @Date: 2018/11/30 11:31
 * @Description:
 */
@Component
public class UsersJob {
    private static Logger logger = LoggerFactory.getLogger(UsersJob.class);

    @Value("${sync_users_api}")
    private String syncUserApi;

    @Value("${sync_users_app_key}")
    private String app_key;

    @Autowired
    ShyUsersMapper shyUsersMapper;


    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void syncUsers() {
        try {
            String tm = "0";
            Example usersExample = new Example(ShyUsers.class);
            usersExample.setOrderByClause("tm desc");
            List<ShyUsers> usersList = shyUsersMapper.selectByExample(usersExample);
            if (!usersList.isEmpty()) {
                Long tmStr = usersList.get(0).getTm();
                if (CommonUtils.isNotNull(tmStr)) tm = tmStr + "";
            }
            HashMap<String, String> dataMap = new HashMap<>();
            dataMap.put("tm", tm);
            dataMap.put("timestamp", new Date().getTime() / 1000 + "");
            String httpUrl = OpenUtil.buildURL(syncUserApi, dataMap, app_key);
            logger.info("httpUrl===" + httpUrl);
            Map<String, String> resultMap = HttpUtil.init().post(httpUrl);
            JSONObject result = JSON.parseObject(resultMap.get("result"));
            String errorCode = result.getString("errorCode");
            if ("0".equals(errorCode)) {
                JSONArray data = result.getJSONArray("data");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject user = data.getJSONObject(i);
                    Integer id = user.getInteger("sid");
                    String email = user.getString("email");
                    Integer spid = user.getInteger("new_sp_id");
                    String userLogo = user.getString("userLogo");
                    boolean master = user.getBoolean("master");
                    Long utm = user.getLong("tm");
                    String username = user.getString("contacts");
                    boolean status = user.getIntValue("status") == CommonConst.USER_STATUS_USE;
                    if (CommonUtils.isEmpty(username)) {
                        username = Integer.toString(id);
                    }
                    String mobile = user.getString("mobile");
                    String company_brief = user.getString("sname");
                    String company = user.getString("company");
                    ShyUsers shyUsers = new ShyUsers();
                    shyUsers.setEmail(email);
                    shyUsers.setId(id);
                    shyUsers.setSp_id(spid);
                    shyUsers.setMaster(master);
                    shyUsers.setState(status);
                    shyUsers.setMobile(mobile);
                    shyUsers.setUsername(username);
                    shyUsers.setCompany_brief(company_brief);
                    shyUsers.setCompany_name(company);
                    shyUsers.setUser_logo(userLogo);
                    shyUsers.setTm(utm);
                    ShyUsers old_shyUsers = shyUsersMapper.selectByPrimaryKey(id);
                    if (CommonUtils.isNull(old_shyUsers)) {
                        shyUsersMapper.insertSelective(shyUsers);
                    } else {
                        shyUsersMapper.updateByPrimaryKeySelective(shyUsers);
                    }
                }
            } else {
                logger.error("请求用户云失败,errorCode:{},errorMessage{}", errorCode, result.getString("errorMessage"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 生成URL
     *
     * @param url
     * @param params
     * @param app_key
     * @return
     */
    public static String buildURL(String url, Map<String, String> params, String app_key) {
        Map<String, String> map = order(params);
        if (map.containsKey("sign")) {
            map.remove("sign");
        }
        String str = mapJoin(map, true, false);
        String sign = SHA1.SHA1Digest(str + "&key=" + app_key).toUpperCase();
        map.put("sign", sign);
        return url + "?" + mapJoin(map, false, true);
    }

    /**
     * Map key 排序
     *
     * @param map
     * @return
     */
    private static Map<String, String> order(Map<String, String> map) {
        HashMap<String, String> tempMap = new LinkedHashMap<String, String>();
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());

        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });

        for (int i = 0; i < infoIds.size(); i++) {
            Map.Entry<String, String> item = infoIds.get(i);
            tempMap.put(item.getKey(), item.getValue());
        }
        return tempMap;
    }

    /**
     * url 参数串连
     *
     * @param map
     * @param keyLower
     * @param valueUrlencode
     * @return
     */
    private static String mapJoin(Map<String, String> map, boolean keyLower, boolean valueUrlencode) {
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : map.keySet()) {
            if (map.get(key) != null && !"".equals(map.get(key))) {
                try {
                    stringBuilder.append(key)
                            .append("=")
                            .append(valueUrlencode ? URLEncoder.encode(map.get(key), "utf-8").replace("+", "%20") : map.get(key))
                            .append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        if (stringBuilder.length() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        return stringBuilder.toString();
    }
}