ext.usercenter.UCClient.java Source code

Java tutorial

Introduction

Here is the source code for ext.usercenter.UCClient.java

Source

/*
 * Copyright (c) 2013, Helome and/or its affiliates. All rights reserved.
 * Helome PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * Created on 2013-10-29
 */
package ext.usercenter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import models.User;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import play.Logger;
import play.Logger.ALogger;
import play.libs.F.Promise;
import play.libs.WS.Response;
import utils.WSUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.jackjson.JackJsonUtil;

import ext.config.ConfigFactory;
import ext.usercenter.vo.UCUserVO;

/**
 * 
 * 
 * @ClassName: UCClient
 * @Description: 
 * @date 2013-10-29 ?2:54:02
 * @author ShenTeng
 * 
 */
public class UCClient {

    private static final ALogger LOGGER = Logger.of(UCClient.class);

    /**
     * 10000ms
     */
    private static int REQUEST_TIMEOUT = ConfigFactory.getInt("userCenter.client.timeout");
    private static String product = ConfigFactory.getString("userCenter.client.product");

    /**
     * ?
     */
    private UCClient() {
    }

    /**
     * ??,??
     * 
     * @param token ??
     * @return UCResult.data?email?isable?phoneNumber?realname?uid?username
     */
    public static UCResult<UCUser> queryUserInfoByToken(String token) {
        long beginMillis = System.currentTimeMillis();

        String post = postNullIgnore("/remote/user/queryUserInfoByToken", "token", token);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "queryUserInfoByToken", "/remote/user/queryUserInfoByToken");

        return UCResult.fromJsonString(post, UCUser.class, true);
    }

    /**
     * ??????? ????<br>
     * UCResult.data?????
     * 
     * @param username ??? ????
     * @return UCResult.data?email?phoneNumber?username
     */
    public static UCResult<UCUser> queryUsernameExist(String username) {
        long beginMillis = System.currentTimeMillis();

        String post = getNullIgnore("/remote/user/queryUsernameExist", "username", username, "product", product);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "queryUsernameExist", "/remote/user/queryUsernameExist");
        return UCResult.fromJsonString(post, UCUser.class, true);
    }

    /**
     * ?helome??id?
     * @param userId id
     * @return
     */
    public static User queryUserById(Long userId) {
        long beginMillis = System.currentTimeMillis();

        String post = postNullIgnore("/remote/security/findUserInfoByPrivateId", "privateId", userId.toString(),
                "product", product);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "queryUserById", "/remote/security/findUserInfoByPrivateId");
        return parseJsonForQueryUserById(post);
    }

    /**
     * ?queryUserById?json
     * @param json
     * @return
     */
    public static User parseJsonForQueryUserById(String json) {
        ObjectMapper mapper = JackJsonUtil.getMapperInstance(false);
        User user = new User();
        if (StringUtils.isNotEmpty(json)) {
            JsonNode node = null;
            try {
                node = mapper.readTree(json);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JsonNode jsonNode = node.path("data");
            Long privateId = jsonNode.path("privateId").asLong();
            String email = jsonNode.path("email").asText();
            String realname = jsonNode.path("realname").asText();
            String phoneNumber = jsonNode.path("phoneNumber").asText();
            user.setId(privateId);
            user.setUserName(realname);
            user.setEmail(email);
            user.setPhoneNumber(phoneNumber);
        }
        return user;
    }

    /**
     * ?helome??id???
     * @param userIdList id?
     * @return
     */
    public static List<UCUserVO> queryUserListByIds(List<Long> userIdList) {
        long beginMillis = System.currentTimeMillis();

        String json = play.libs.Json.toJson(userIdList).toString();
        String post = postWithJson("/remote/security/findNamesByPrivateIds", json);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "queryUserListByIds", "/remote/security/findNamesByPrivateIds");
        return parseJsonForQueryUserListByIds(post);
    }

    /**
      * ?queryUserById?json
      * @param json
      * @return
      */
    public static List<UCUserVO> parseJsonForQueryUserListByIds(String json) {
        ObjectMapper mapper = JackJsonUtil.getMapperInstance(false);
        List<UCUserVO> ucUserVOList = new ArrayList<UCUserVO>();
        if (StringUtils.isNotEmpty(json)) {
            JsonNode node = null;
            try {
                node = mapper.readTree(json);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (node != null && node.path("responsecode").asText().equals("_200")) {
                JsonNode jsonNode = node.path("data");
                Iterator<Entry<String, JsonNode>> fieldIte = jsonNode.fields(); // 2053={"englishName":null,"realname":null}
                while (fieldIte.hasNext()) {
                    Entry<String, JsonNode> entry = fieldIte.next();
                    Long userId = new Long(entry.getKey());
                    JsonNode valueNode = entry.getValue();
                    String englishName = valueNode.path("englishName").asText();
                    String realname = valueNode.path("realname").asText();
                    UCUserVO vo = new UCUserVO(userId, englishName, realname);
                    ucUserVOList.add(vo);
                }
            }
        }
        return ucUserVOList;
    }

    /**
     * 
     * 
     * @param username ??11????
     * @param userpassword ??
     * @param device android/iphone/ipad/web
     * @param ip ???ip?
     * @return UCResult.data?UCUser<br>
     *         ??????
     */
    public static UCResult<UCUser> login(String username, String userpassword, String device, String ip) {
        long beginMillis = System.currentTimeMillis();

        String post = postNullIgnore("/remote/security/login", "username", username, "userpassword", userpassword,
                "product", product, "device", device, "ip", ip);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "login", "/remote/security/login");

        UCResult<UCUser> result = UCResult.fromJsonString(post, UCUser.class, true);
        if (result.isSuccess() && (result.data == null || StringUtils.isBlank(result.data.userpassword))) {
            LOGGER.error(
                    "response error : null param or response. path = /remote/security/login, response = " + post);
        }
        return result;
    }

    /**
     * ?
     * 
     * @param token ??????
     * @return UCResult.data???null
     */
    public static UCResult<Void> checkUserLoginStatus(String token) {
        long beginMillis = System.currentTimeMillis();

        String post = postNullIgnore("/remote/security/checkUserLoginStatus", "token", token);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "checkUserLoginStatus", "/remote/security/checkUserLoginStatus");
        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     * token?
     * 
     * @param token ??????
     * @return UCResult.data???null<br>
     *         ???
     */
    public static UCResult<Void> logout(String token) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/logout", "token", token);

        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "logout", "/remote/security/logout");

        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     *  ????<br>
     * ??????????
     * 
     * @param userpassword ?
     * @param username ?null????
     * @param realname ?null????
     * @param email ?null??
     * @param phoneNumber ?null?????
     * @param device android/iphone/ipad/web
     * @param ip ???ip?
     * @param privateId Id
     * @return UCResult.data?email?isable?phoneNumber?realname?token?uid?username?userpassword<br>
     *         ?????????
     */
    public static UCResult<UCUser> register(String userpassword, String username, String realname, String email,
            String phoneNumber, String device, String ip, Long privateId) {

        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/register", "userpassword", userpassword, "username",
                username, "realname", realname, "email", email, "phoneNumber", phoneNumber, "product", product,
                "device", device, "ip", ip, "privateId", privateId.toString());
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "register", "/remote/security/register");

        UCResult<UCUser> result = UCResult.fromJsonString(post, UCUser.class, true);
        if (result.data == null || StringUtils.isBlank(result.data.userpassword)) {
            LOGGER.error("response error : null param or response. path = /remote/security/register, response = "
                    + post);
        }
        return result;
    }

    /**
     * ??
     * 
     * @param username ??????????
     * @param newPassword ?
     * @return UCResult.data?userpassword
     */
    public static UCResult<UCUser> modifyPassword(String username, String newPassword) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/modifyPassword", "username", username, "newPassword",
                newPassword);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "modifyPassword", "/remote/security/modifyPassword");

        UCResult<UCUser> result = UCResult.fromJsonString(post, UCUser.class, true);
        if (result.data == null || StringUtils.isBlank(result.data.userpassword)) {
            LOGGER.error(
                    "response error : null param or response. path = /remote/security/modifyPassword, response = "
                            + post);
        }
        return result;
    }

    /**
     * ?????<br>
     * ??????????
     * 
     * @param token ????
     * @param password ?
     * @return UCResult.data???null<br>
     */
    public static UCResult<Void> checkPassword4ModifyUsername(String token, String password) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/checkPassword4ModifyUsername", "token", token, "password",
                password);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "checkPassword4ModifyUsername", "/remote/security/checkPassword4ModifyUsername");
        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     * ????
     * 
     * @param token ????
     * @param password ?
     * @return UCResult.data???null<br>
     */
    public static UCResult<Void> checkPassword4ModifyPassword(String token, String password) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/checkPassword4ModifyPassword", "token", token, "password",
                password);

        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "checkPassword4ModifyPassword", "/remote/security/checkPassword4ModifyPassword");
        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     * ??,?:,,<br>
     * <br>
     * strong--(???)<br>
     * medium--(?)<br>
     * weak--(??,??8)
     * 
     * @param token ????
     * @return UCResult.data Stringstrong -  medium -  weak - <br>
     */
    public static UCResult<String> passwordSecurityGrade(String token) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/passwordSecurityGrade", "token", token);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "passwordSecurityGrade", "/remote/security/passwordSecurityGrade");
        return UCResult.fromJsonString(post, String.class, true);
    }

    /**
     * ?email
     * 
     * @param token ????
     * @param email 
     * @return UCResult.data???null<br>
     *         ???
     */
    public static UCResult<Void> modifyEmail(String token, String email) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/modifyEmail", "token", token, "email", email);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "modifyEmail", "/remote/security/modifyEmail");
        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     * ()?
     * 
     * @param token ????
     * @param phoneNumber ?
     * @return UCResult.data???null<br>
     *         ???
     */
    public static UCResult<Void> bindingPhoneNumber(String token, String phoneNumber) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/bindingPhoneNumber", "token", token, "phoneNumber",
                phoneNumber);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "bindingPhoneNumber", "/remote/security/bindingPhoneNumber");
        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     * ?????
     * 
     * @param username ??11????
     * @param userpassword ??
     * @param device android/iphone/ipad/web
     * @param ip ???ip?
     * @return UCResult.data?UCUser<br>
     *         ??????
     */
    public static UCResult<UCUser> encryptLogin(String username, String userpassword, String device, String ip) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/encryptLogin", "username", username, "userpassword",
                userpassword, "product", product, "device", device, "ip", ip);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "encryptLogin", "/remote/security/encryptLogin");
        UCResult<UCUser> ucResult = UCResult.fromJsonString(post, UCUser.class, true);

        if (ucResult.isSuccess()) {
            UCResult<UCUser> oldUCResult = ucResult;
            ucResult = queryUserInfoByToken(ucResult.data.token);
            if (ucResult.isSuccess()) {
                ucResult.data.token = oldUCResult.data.token;
                ucResult.data.userpassword = userpassword;
            }
        }

        return ucResult;
    }

    public static UCResult<Void> modifyRealname(String token, String realname) {
        long beginMillis = System.currentTimeMillis();
        String post = postNullIgnore("/remote/security/modifyRealname", "token", token, "realname", realname);
        long endMillis = System.currentTimeMillis();
        long callTime = endMillis - beginMillis;
        callTimeLog(callTime, "modifyRealname", "/remote/security/modifyRealname");
        return UCResult.fromJsonString(post, Void.class, false);
    }

    /**
     * ?post?null?
     */
    private static String postNullIgnore(String relativeUrl, String... params) {
        if (null == relativeUrl || (params != null && params.length % 2 != 0)) {
            throw new IllegalArgumentException("illegal method input param. param: relativeUrl=" + relativeUrl
                    + ", params=" + Arrays.toString(params));
        }

        String[] paramArray = filterNullParams(params);
        String uri = ConfigFactory.getString("userCenter.client.serverUrl") + relativeUrl;

        Promise<Response> post = WSUtil.postFormURLEncoded(uri, paramArray);

        LOGGER.debug("usercenter request uri : " + uri + ", post : " + Arrays.toString(params));

        Response response;
        try {
            response = post.get(REQUEST_TIMEOUT);
        } catch (Exception e) {
            throw new UserCenterException("??.METHOD = post, URI = " + uri
                    + ", params = " + Arrays.toString(params), e);
        }

        String body = response.getBody();

        LOGGER.debug("usercenter request uri : " + uri + ", post response : " + body);

        return body;
    }

    /**
     * ?post?json
     */
    private static String postWithJson(String relativeUrl, String json) {
        if (StringUtils.isEmpty(json)) {
            throw new IllegalArgumentException("Parameters cannot be empty");
        }

        String uri = ConfigFactory.getString("userCenter.client.serverUrl") + relativeUrl;

        Promise<Response> post = WSUtil.postWithJson(uri, json);

        LOGGER.debug("usercenter request uri : " + uri + ", post : " + json);

        Response response;
        try {
            response = post.get(REQUEST_TIMEOUT);
        } catch (Exception e) {
            throw new UserCenterException(
                    "??.METHOD = post, URI = " + uri + ", params = " + json,
                    e);
        }

        String body = response.getBody();

        LOGGER.debug("usercenter request uri : " + uri + ", post response : " + body);

        return body;
    }

    private static String[] filterNullParams(String[] params) {
        if (ArrayUtils.isNotEmpty(params)) {
            List<String> paramList = new ArrayList<>();
            for (int i = 0; i < params.length; i += 2) {
                if (null == params[i + 1]) {
                    continue;
                }

                paramList.add(params[i]);
                paramList.add(params[i + 1]);
            }
            return paramList.toArray(new String[0]);
        }
        return null;
    }

    /**
     * ?get?null?
     */
    private static String getNullIgnore(String relativeUrl, String... params) {
        if (null == relativeUrl || (params != null && params.length % 2 != 0)) {
            throw new IllegalArgumentException("illegal method input param. param: relativeUrl=" + relativeUrl
                    + ", params=" + Arrays.toString(params));
        }

        String[] paramArray = filterNullParams(params);
        String uri = ConfigFactory.getString("userCenter.client.serverUrl") + relativeUrl;

        Promise<Response> get = WSUtil.get(uri, paramArray);

        LOGGER.debug("usercenter request uri : " + uri + ", get : " + Arrays.toString(params));

        Response response = null;
        try {
            response = get.get(REQUEST_TIMEOUT);
        } catch (Exception e) {
            throw new UserCenterException("??.METHOD = get, URI = " + uri
                    + ", params = " + Arrays.toString(params), e);
        }

        String body = response.getBody();

        LOGGER.debug("usercenter request uri : " + uri + ", get response : " + body);

        return body;

    }

    private static void callTimeLog(long callTime, String method, String url) {
        StringBuilder log = new StringBuilder();
        log.append("=").append(method);
        log.append(",URL=").append(url);
        log.append(",=").append(callTime).append("ms");
        LOGGER.info(log.toString());
    }

}