com.ctrip.infosec.rule.resource.DataProxy.java Source code

Java tutorial

Introduction

Here is the source code for com.ctrip.infosec.rule.resource.DataProxy.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ctrip.infosec.rule.resource;

import static com.ctrip.infosec.common.SarsMonitorWrapper.afterInvoke;
import static com.ctrip.infosec.common.SarsMonitorWrapper.beforeInvoke;
import static com.ctrip.infosec.common.SarsMonitorWrapper.fault;
import com.ctrip.infosec.configs.rule.trace.logger.TraceLogger;
import static com.ctrip.infosec.configs.utils.Utils.JSON;
import com.ctrip.infosec.rule.Contexts;
import com.ctrip.infosec.rule.ThreadLocalCache;
import com.ctrip.infosec.rule.resource.hystrix.DataProxyQueryCommand;
import com.ctrip.infosec.sars.util.GlobalConfig;
import com.ctrip.sec.userprofile.vo.content.request.DataProxyRequest;
import com.google.common.collect.ImmutableMap;

import java.util.*;

import org.apache.commons.lang3.Validate;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zhengby
 */
public class DataProxy {

    private static final Logger logger = LoggerFactory.getLogger(DataProxy.class);
    /**
     * URL?, ?ContextPath, : http://10.2.10.75:8080/counterws
     */
    private static final String urlPrefix = GlobalConfig.getString("DataProxy.REST.URL.Prefix");

    private static void check() {
        Validate.notEmpty(urlPrefix,
                "GlobalConfig.properties\"DataProxy.REST.URL.Prefix\"?.");
        Validate.notEmpty(urlPrefix,
                "GlobalConfig.properties\"DataProxy.Venus.ipAddressList\"?.");
    }

    static String buildCacheKey(String serviceName, String operationName, Map<String, Object> params) {
        StringBuilder builder = new StringBuilder("DataProxy.queryForMap__");
        builder.append(serviceName).append("__").append(operationName).append("__")
                .append(JSON.toJSONString(params));
        return builder.toString();
    }

    /**
     * ??
     *
     * @param serviceName
     * @param operationName
     * @param params
     * @return
     */
    public static Map queryForMap(String serviceName, String operationName, Map<String, Object> params) {
        check();
        beforeInvoke("DataProxy.queryForMap");
        beforeInvoke("DataProxy." + serviceName + "." + operationName);
        try {
            String cacheKey = buildCacheKey(serviceName, operationName, params);
            Map newResult = (Map) ThreadLocalCache.get(cacheKey);
            if (newResult == null) {
                boolean _isAsync = Contexts.isAsync();
                DataProxyQueryCommand command = new DataProxyQueryCommand(serviceName, operationName, params,
                        _isAsync);
                newResult = command.execute();
                if (serviceName.equals("UserProfileService")) {
                    newResult = parseProfileResult(newResult);
                }
                if (newResult != null && !newResult.isEmpty()) {
                    ThreadLocalCache.set(cacheKey, newResult);
                }
            } else {
                logger.info("hit cache, key = " + cacheKey);
            }
            return newResult;
        } catch (Exception ex) {
            fault("DataProxy.queryForMap");
            fault("DataProxy." + serviceName + "." + operationName);
            logger.error(Contexts.getLogPrefix() + "DataProxy.", ex);
            TraceLogger.traceLog("DataProxy, EXCEPTION: "
                    + (ex.getCause() == null ? ex.toString() : ex.getCause().toString()));
        } finally {
            afterInvoke("DataProxy.queryForMap");
            afterInvoke("DataProxy." + serviceName + "." + operationName);
        }
        return Collections.EMPTY_MAP;
    }

    /**
     * userProfiles?
     */
    public static Map<String, Object> queryTags(String profile, String value, List<String> tagNames) {
        String serviceName = "UserProfileService";
        String operationName = "DataQuery";
        Map params = ImmutableMap.of(profile, value, "tagNames", tagNames);
        return queryForMap(serviceName, operationName, params);
    }

    /**
     *
     * @param key tag?
     * @param values tag??tag?map example:key:uid-123
     * values:RECENT_IP-112.23.32.36 RECENT_IPAREA-
     * -------------------------------------
     *
     * ? temp = new
     * HashMap();temp.put("RECENT_IP","112.23.32.36");temp.put("RECENT_IPAREA","");
     * addTagData("123",temp)
     * @return ?true?false
     */
    public static boolean addTagData(String key, Map<String, String> values) {
        boolean flag = false;
        check();
        beforeInvoke("DataProxy.addTagData");
        try {
            List<DataProxyRequest> requests = new ArrayList<>();
            DataProxyRequest request = new DataProxyRequest();
            request.setServiceName("CommonService");
            request.setOperationName("addData");

            Map params = new HashMap<String, String>();
            params.put("tableName", "UserProfileInfo");
            params.put("pkValue", key.trim());
            params.put("storageType", "1");
            params.put("values", values);
            request.setParams(params);
            requests.add(request);
            String requestText = JSON.toPrettyJSONString(requests);
            String responseText = Request.Post(urlPrefix + "/rest/dataproxy/dataprocess")
                    .bodyString(requestText, ContentType.APPLICATION_JSON).execute().returnContent().asString();
            Map result = JSON.parseObject(responseText, Map.class);
            if (result.get("rtnCode").equals("0")) {
                flag = true;
            } else {
                flag = false;
                logger.warn("?:" + JSON.toPrettyJSONString(values) + "\t" + "userProfile!");
            }
        } catch (Exception ex) {
            fault("DataProxy.addTagData");
            logger.error(Contexts.getLogPrefix() + "invoke DataProxy.addTagData fault.", ex);
        } finally {
            afterInvoke("DataProxy.addTagData");
        }
        return flag;
    }

    /**
     * ?DataProxyResponseresultMap
     */
    private static Map parseProfileResult(Map result) {
        if (result != null) {
            if (result.get("tagName") != null) {
                return parseResult(result);
            } else if (result.get("tagNames") != null) {
                Object tagValues = result.get("tagNames");
                List oldResults = JSON.parseObject(JSON.toJSONString(tagValues), List.class);
                Map newResults = new HashMap();
                Iterator iterator = oldResults.iterator();
                while (iterator.hasNext()) {
                    Map oneResult = (Map) iterator.next();
                    newResults.putAll(parseResult(oneResult));
                }
                return newResults;
            } else {
                return result;
            }
        }
        return Collections.EMPTY_MAP;
    }

    /**
     * ??? userProfile???Map?
     */
    private static Map parseResult(Map oldValue) {
        Map newResult = new HashMap();
        String tagDataType = oldValue.get("tagDataType") == null ? "" : oldValue.get("tagDataType").toString();
        if (tagDataType.toLowerCase().equals("int") || tagDataType.toLowerCase().equals("string")
                || tagDataType.toLowerCase().equals("datetime") || tagDataType.toLowerCase().equals("boolean")) {

            String tagName = oldValue.get("tagName") == null ? "" : oldValue.get("tagName").toString();
            String tagContent = oldValue.get("tagContent") == null ? "" : oldValue.get("tagContent").toString();
            newResult.put(tagName, tagContent);

        } else if (tagDataType.toLowerCase().equals("list")) {

            String tagName = oldValue.get("tagName") == null ? "" : oldValue.get("tagName").toString();
            List tagContent = oldValue.get("tagContent") == null ? new ArrayList()
                    : JSON.parseObject(JSON.toJSONString(oldValue.get("tagContent")), List.class);
            newResult.put(tagName, tagContent);
        }
        return newResult;
    }
}