<commit_before>package com.java110.api.listener;

import com.alibaba.fastjson.JSONObject;
import com.java110.common.constant.CommonConstant;
import com.java110.common.constant.ResponseConstant;
import com.java110.common.util.Assert;
import com.java110.common.util.StringUtil;
import com.java110.core.context.DataFlowContext;
import com.java110.entity.center.AppService;
import com.java110.event.service.api.ServiceDataFlowListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Created by wuxw on 2018/11/15.
 */
public abstract class AbstractServiceApiDataFlowListener implements ServiceDataFlowListener {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplate restTemplateNoLoadBalanced;

    /**
     * 请求落地方
     * @param dataFlowContext
     * @param service
     * @param httpEntity
     */
    protected void doRequest(DataFlowContext dataFlowContext, AppService service, HttpEntity<String> httpEntity) {

        ResponseEntity responseEntity= null;
        //配置c_service 时请注意 如果是以out 开头的调用外部的地址
        RestTemplate tmpRestTemplate = service.getServiceCode().startsWith("out.")?restTemplateNoLoadBalanced:restTemplate;

        try {
            if (CommonConstant.HTTP_METHOD_GET.equals(service.getMethod())) {
                String requestUrl = dataFlowContext.getRequestHeaders().get("REQUEST_URL");
                if (!StringUtil.isNullOrNone(requestUrl)) {
                    String param = requestUrl.contains("?") ? requestUrl.substring(requestUrl.indexOf("?")+1, requestUrl.length()) : "";
                    if (service.getUrl().contains("?")) {
                        requestUrl = service.getUrl() + "&" + param;
                    } else {
                        requestUrl = service.getUrl() + "?" + param;
                    }
                }
                responseEntity = tmpRestTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class);
            } else if (CommonConstant.HTTP_METHOD_PUT.equals(service.getMethod())) {
                responseEntity = tmpRestTemplate.exchange(service.getUrl(), HttpMethod.PUT, httpEntity, String.class);
            } else if (CommonConstant.HTTP_METHOD_DELETE.equals(service.getMethod())) {
                String requestUrl = dataFlowContext.getRequestHeaders().get("REQUEST_URL");
                if (!StringUtil.isNullOrNone(requestUrl)) {
                    String param = requestUrl.contains("?") ? requestUrl.substring(requestUrl.indexOf("?"), requestUrl.length()) : "";
                    if (service.getUrl().contains("?")) {
                        requestUrl = service.getUrl() + "&" + param;
                    } else {
                        requestUrl = service.getUrl() + "?" + param;
                    }
                }
                responseEntity = tmpRestTemplate.exchange(requestUrl, HttpMethod.DELETE, httpEntity, String.class);
            } else {
                responseEntity = tmpRestTemplate.exchange(service.getUrl(), HttpMethod.POST, httpEntity, String.class);
            }
        }catch (HttpStatusCodeException e){ //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常，需要重新封装一下
            responseEntity = new ResponseEntity<String>("请求下游系统异常，"+e.getResponseBodyAsString(),e.getStatusCode());
        }

        dataFlowContext.setResponseEntity(responseEntity);
    }


    /**
     * 处理返回报文信息
     * @param dataFlowContext
     */
    protected void doResponse(DataFlowContext dataFlowContext) {
        ResponseEntity<String> responseEntity = dataFlowContext.getResponseEntity();
        ResponseEntity<String> newResponseEntity = null;
        if(responseEntity == null ||
                responseEntity.getStatusCode() != HttpStatus.OK ||
                StringUtil.isNullOrNone(responseEntity.getBody()) ||
                !Assert.isJsonObject(responseEntity.getBody())){ //这里一般进不去
            return ;
        }
        JSONObject resJson = JSONObject.parseObject(responseEntity.getBody());

        if(!resJson.containsKey("orders")
                || !ResponseConstant.RESULT_CODE_SUCCESS.equals(resJson.getJSONObject("orders").getJSONObject("response").getString("code"))){
            return ;
        }

        if(resJson.containsKey("business") && resJson.getJSONArray("business").size() == 1){
            JSONObject busiJson = resJson.getJSONArray("business").getJSONObject(0);
            if(busiJson.containsKey("orderTypeCd")){
                busiJson.remove("orderTypeCd");
            }
            if(busiJson.containsKey("serviceCode")){
                busiJson.remove("serviceCode");
            }
            if(busiJson.containsKey("response")){
                busiJson.remove("response");
            }
            if(busiJson.containsKey("bId")){
                busiJson.remove("bId");
            }

            if(busiJson.containsKey("businessType")){
                busiJson.remove("businessType");
            }

            if(busiJson.containsKey("dataFlowId")){
                busiJson.remove("dataFlowId");
            }
            //这个一般是 center服务和下游系统之间交互的流水可以删掉，返回出去也没有啥意义
            if(busiJson.containsKey("transactionId")){
                busiJson.remove("transactionId");
            }
            //newResponseEntity = new ResponseEntity<String>(busiJson.toJSONString(),responseEntity.getHeaders(), HttpStatus.OK);
            newResponseEntity = new ResponseEntity<String>(busiJson.toJSONString(), HttpStatus.OK);

            dataFlowContext.setResponseEntity(newResponseEntity);
        }
    }


    /**
     * 将rest 协议转为 订单协议
     * @param business
     * @return
     */
    protected JSONObject restToCenterProtocol(JSONObject business, Map<String,String> headers){

        JSONObject centerProtocol = JSONObject.parseObject("{\"orders\":{},\"business\":[]}");
        freshOrderProtocol(centerProtocol.getJSONObject("orders"),headers);
        centerProtocol.getJSONArray("business").add(business);
        return centerProtocol;
    }

    /**<commit_msg>修复加入下游系统头信息时 调用很慢的问题<commit_after>package com.java110.api.listener;

import com.alibaba.fastjson.JSONObject;
import com.java110.common.constant.CommonConstant;
import com.java110.common.constant.ResponseConstant;
import com.java110.common.util.Assert;
import com.java110.common.util.StringUtil;
import com.java110.core.context.DataFlowContext;
import com.java110.entity.center.AppService;
import com.java110.event.service.api.ServiceDataFlowListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * Created by wuxw on 2018/11/15.
 */
public abstract class AbstractServiceApiDataFlowListener implements ServiceDataFlowListener {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplate restTemplateNoLoadBalanced;

    /**
     * 请求落地方
     * @param dataFlowContext
     * @param service
     * @param httpEntity
     */
    protected void doRequest(DataFlowContext dataFlowContext, AppService service, HttpEntity<String> httpEntity) {

        ResponseEntity responseEntity= null;
        //配置c_service 时请注意 如果是以out 开头的调用外部的地址
        RestTemplate tmpRestTemplate = service.getServiceCode().startsWith("out.")?restTemplateNoLoadBalanced:restTemplate;

        try {
            if (CommonConstant.HTTP_METHOD_GET.equals(service.getMethod())) {
                String requestUrl = dataFlowContext.getRequestHeaders().get("REQUEST_URL");
                if (!StringUtil.isNullOrNone(requestUrl)) {
                    String param = requestUrl.contains("?") ? requestUrl.substring(requestUrl.indexOf("?")+1, requestUrl.length()) : "";
                    if (service.getUrl().contains("?")) {
                        requestUrl = service.getUrl() + "&" + param;
                    } else {
                        requestUrl = service.getUrl() + "?" + param;
                    }
                }
                responseEntity = tmpRestTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class);
            } else if (CommonConstant.HTTP_METHOD_PUT.equals(service.getMethod())) {
                responseEntity = tmpRestTemplate.exchange(service.getUrl(), HttpMethod.PUT, httpEntity, String.class);
            } else if (CommonConstant.HTTP_METHOD_DELETE.equals(service.getMethod())) {
                String requestUrl = dataFlowContext.getRequestHeaders().get("REQUEST_URL");
                if (!StringUtil.isNullOrNone(requestUrl)) {
                    String param = requestUrl.contains("?") ? requestUrl.substring(requestUrl.indexOf("?"), requestUrl.length()) : "";
                    if (service.getUrl().contains("?")) {
                        requestUrl = service.getUrl() + "&" + param;
                    } else {
                        requestUrl = service.getUrl() + "?" + param;
                    }
                }
                responseEntity = tmpRestTemplate.exchange(requestUrl, HttpMethod.DELETE, httpEntity, String.class);
            } else {
                responseEntity = tmpRestTemplate.exchange(service.getUrl(), HttpMethod.POST, httpEntity, String.class);
            }
        }catch (HttpStatusCodeException e){ //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常，需要重新封装一下
            responseEntity = new ResponseEntity<String>("请求下游系统异常，"+e.getResponseBodyAsString(),e.getStatusCode());
        }

        dataFlowContext.setResponseEntity(responseEntity);
    }


    /**
     * 处理返回报文信息
     * @param dataFlowContext
     */
    protected void doResponse(DataFlowContext dataFlowContext) {
        ResponseEntity<String> responseEntity = dataFlowContext.getResponseEntity();
        ResponseEntity<String> newResponseEntity = null;
        if(responseEntity == null ||
                responseEntity.getStatusCode() != HttpStatus.OK ||
                StringUtil.isNullOrNone(responseEntity.getBody()) ||
                !Assert.isJsonObject(responseEntity.getBody())){ //这里一般进不去
            return ;
        }
        JSONObject resJson = JSONObject.parseObject(responseEntity.getBody());

        if(!resJson.containsKey("orders")
                || !ResponseConstant.RESULT_CODE_SUCCESS.equals(resJson.getJSONObject("orders").getJSONObject("response").getString("code"))){
            return ;
        }

        if(resJson.containsKey("business") && resJson.getJSONArray("business").size() == 1){
            JSONObject busiJson = resJson.getJSONArray("business").getJSONObject(0);
            if(busiJson.containsKey("orderTypeCd")){
                busiJson.remove("orderTypeCd");
            }
            if(busiJson.containsKey("serviceCode")){
                busiJson.remove("serviceCode");
            }
            if(busiJson.containsKey("response")){
                busiJson.remove("response");
            }
            if(busiJson.containsKey("bId")){
                busiJson.remove("bId");
            }

            if(busiJson.containsKey("businessType")){
                busiJson.remove("businessType");
            }

            if(busiJson.containsKey("dataFlowId")){
                busiJson.remove("dataFlowId");
            }
            //这个一般是 center服务和下游系统之间交互的流水可以删掉，返回出去也没有啥意义
            if(busiJson.containsKey("transactionId")){
                busiJson.remove("transactionId");
            }
            Map<String,String> headersMap = responseEntity.getHeaders().toSingleValueMap();
            if(headersMap.containsKey("Content-Disposition")) {
                headersMap.remove("Content-Disposition");
            }
            if(headersMap.containsKey("Content-Type")) {
                headersMap.remove("Content-Type");
            }
            if(headersMap.containsKey("Content-Length")) {
                headersMap.remove("Content-Length");
            }
            if(headersMap.containsKey("Accept-Charset")) {
                headersMap.remove("Accept-Charset");
            }
            if(headersMap.containsKey("X-Application-Context")) {
                headersMap.remove("X-Application-Context");
            }

            HttpHeaders header = new HttpHeaders();
            header.setAll(headersMap);
            newResponseEntity = new ResponseEntity<String>(busiJson.toJSONString(),header, HttpStatus.OK);
            //newResponseEntity = new ResponseEntity<String>(busiJson.toJSONString(), HttpStatus.OK);

            dataFlowContext.setResponseEntity(newResponseEntity);
        }
    }


    /**
     * 将rest 协议转为 订单协议
     * @param business
     * @return
     */
    protected JSONObject restToCenterProtocol(JSONObject business, Map<String,String> headers){

        JSONObject centerProtocol = JSONObject.parseObject("{\"orders\":{},\"business\":[]}");
        freshOrderProtocol(centerProtocol.getJSONObject("orders"),headers);
        centerProtocol.getJSONArray("business").add(business);
        return centerProtocol;
    }

    /**
{'fraction_non_alphanumeric': 0.11644746564208659, 'fraction_numerical': 0.005467710950199498, 'mean_word_length': 2.5844809322033897, 'pattern_counts': {'":': 4, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1119783', 'n_tokens_mistral': 3733, 'n_tokens_neox': 3650, 'n_words': 495}