All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hina.sdk.user.UserHandler Maven / Gradle / Ivy

The newest version!
package com.hina.sdk.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hina.sdk.HinaSdk;
import com.hina.sdk.exception.HinaException;
import com.hina.sdk.exception.HinaExceptionEnum;
import com.hina.sdk.util.GzipUtil;
import com.hina.sdk.util.IdUtil;
import com.hina.sdk.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户处理
 */
@Slf4j
public class UserHandler {


    private static UserHandler userHandler;

    private UserHandler() {
    }


    public static synchronized UserHandler getInstance() {
        if (userHandler == null) {
            userHandler = new UserHandler();
        }
        return userHandler;
    }


    /**
     * 发送事件
     */
    public void send(UserReq req) throws HinaException {

        UserRecord userRecord = null;
        try {
            // 构建记录
            userRecord = buildUserRecord(req);
            // 获取body
            String requestBody = getRequestBody(userRecord);
            // 发送请求
            String url = HinaSdk.getUrl();
            post(url, requestBody);
        } catch (Exception e) {
            log.error("HINA_Java_SDK 用户属性设置失败,参数:{}}", userRecord);
            throw new HinaException(e);
        }
    }

    /**
     * 构建事件记录
     *
     * @return
     */
    private UserRecord buildUserRecord(UserReq req) {
        UserRecord UserRecord = new UserRecord();
        UserRecord.set_track_id(IdUtil.generateId());
        String account_id = req.getUserUid();
        UserRecord.setAccount_id(account_id);
        UserRecord.setType(req.getType());
        UserRecord.setTime(String.valueOf(req.getReqTime()));
        UserRecord.setSend_time(String.valueOf(System.currentTimeMillis()));
        Map map = new HashMap<>();
        map.putAll(req.getData());
        UserRecord.setProperties(map);
        return UserRecord;
    }


    /**
     * 获取请求body
     *
     * @param record
     * @return
     * @throws IOException
     */
    private String getRequestBody(UserRecord record) throws IOException {
        ArrayList records = new ArrayList<>();
        records.add(record);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(records);
        if ("dev".equals(HinaSdk.getMode())) log.info(json);
        String zipstr = GzipUtil.zip(json);
        StringBuilder body = new StringBuilder("gzip=1&data=");
        body.append(zipstr);
        String bodystr = body.toString();
        return bodystr;
    }




    /**
     * 发送请求
     */
    private void post(String url, String body) throws Exception {
        CloseableHttpResponse response = null;
        String responseBody = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if ("dev".equals(HinaSdk.getMode())) log.info(body);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(body));
            httpPost.setHeader("Content-Type", "text/plain");
            httpPost.setHeader("Accept", "application/json");
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (null != responseEntity) {
                int statusCode = response.getStatusLine().getStatusCode();
                responseBody = EntityUtils.toString(responseEntity);
                log.debug("HINA_Java_SDK 响应参数:{}",responseBody);
                boolean resultIsSuccess = resultIsSuccess(statusCode, responseBody);
                if (false == resultIsSuccess) {
                    throw new HinaException(HinaExceptionEnum.EVENT_FAIL);
                }
            }
        } catch (Exception e){
            log.error("HINA_Java_SDK 发送失败,请求参数:{},响应参数:{}", body, responseBody, e);
            throw e;
        }
        finally {
            if (null != response) {
                response.close();
            }
            httpClient.close();
        }
    }

    /**
     * 判断响应是否成功
     *
     * @return
     */
    private boolean resultIsSuccess(int statusCode, String responseBody) throws IOException {
        if (statusCode != 200) return false;
        ObjectMapper objectMapper = JsonUtil.getObjectMapper();
        UserRes userRes = objectMapper.readValue(responseBody, UserRes.class);
        if (null == userRes) return false;
        if (200 != userRes.getStatus() || true != userRes.getSuccess()) return false;
        return true;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy