Java tutorial
/** * Copyright (c) 2014 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baidu.rigel.biplatform.ac.model.callback; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import com.baidu.rigel.biplatform.ac.util.AnswerCoreConstant; import com.baidu.rigel.biplatform.ac.util.HttpRequest; import com.google.common.collect.Lists; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; /** * * Description: * @author david.wang * */ public final class CallbackServiceInvoker { /** * LOG */ private static final Logger LOG = LoggerFactory.getLogger(CallbackServiceInvoker.class); /** * */ private CallbackServiceInvoker() { } /** * * @param url callbackurl * @param params callback? * @param type callback * @return CallbackResponse callback? */ public static CallbackResponse invokeCallback(String url, Map<String, String> params, CallbackType type) { return invokeCallback(url, params, type, 50000); } /** * * @param url callbackurl * @param params callback? * @param type callback * @param timeOutMillSecond * @return CallbackResponse callback? */ public static CallbackResponse invokeCallback(String url, Map<String, String> params, CallbackType type, long timeOutMillSecond) { long begin = System.currentTimeMillis(); if (timeOutMillSecond <= 0) { timeOutMillSecond = 1000; } params.put(HttpRequest.SOCKET_TIME_OUT, String.valueOf(timeOutMillSecond)); // TODO ?????? // if (url.contains("\\?")) { // String[] tmp = url.split("\\?"); // url = tmp[0]; // String[] paramsMap = tmp[1].split("&"); // for (String str : paramsMap) { // tmp = str.split("="); // if (params.containsKey(tmp[0])) { // continue; // } // params.put(tmp[0], tmp[1]); // } // } LOG.info("[INFO] --- --- begin invoke callback service ... ..."); LOG.info("[INFO] --- --- params : {}", params); LOG.info("[INFO] --- --- request url : {}", url); LOG.info("[INFO] --- --- timeout time : {} ms", timeOutMillSecond); LOG.info("[INFO] --- --- callback type : {}", type.name()); LOG.info("[INFO] --- --- end invoke callback service. result is : \r\n"); LOG.info("[INFO] -------------------------------------------------------------------------\r\n"); try { String responseStr = HttpRequest.sendPost1(url, params); CallbackResponse response = convertStrToResponse(responseStr, type); LOG.info("[INFO] --- --- resposne : {}", response); LOG.info("[INFO] -------------------------------------------------------------------------\r\n"); long end = System.currentTimeMillis() - begin; LOG.info("[INFO] --- --- invoke callback service cost : " + end + "ms," + " cost on data transfer : " + (end - response.getCost()) + "ms," + " callback execute cost : " + response.getCost() + "ms"); return response; } catch (Exception e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e); } } /** * callback?CallbackResponse404?cache?? * @param responseStr * @param type * @return CallbackResponse */ private static CallbackResponse convertStrToResponse(String responseStr, CallbackType type) { LOG.info("[INFO] --- --- message received from callback server is {}", responseStr); CallbackResponse rs = new CallbackResponse(); long begin = System.currentTimeMillis(); if (StringUtils.isEmpty(responseStr)) { throw new RuntimeException("???"); } JsonObject json = new JsonParser().parse(responseStr).getAsJsonObject(); int status = json.get("status").getAsInt(); String message = json.get("message") == null || json.get("message") == JsonNull.INSTANCE ? "unknown" : json.get("message").getAsString(); String provider = json.get("provider") == null || json.get("provider") == JsonNull.INSTANCE ? "unknown" : json.get("provider").getAsString(); String cost = json.get("cost") == null || json.get("cost") == JsonNull.INSTANCE ? "" : json.get("cost").getAsString(); String version = json.get("version") == null || json.get("version") == JsonNull.INSTANCE ? "unknown" : json.get("version").getAsString(); LOG.info("[INFO] ------------------------------callback response desc -----------------------------------"); LOG.info("[INFO] --- --- status : {}", status); LOG.info("[INFO] --- --- message : {}", message); LOG.info("[INFO] --- --- provider : {}", provider); LOG.info("[INFO] --- --- cost : {}", cost); LOG.info("[INFO] --- --- callback version : {}", version); LOG.info("[INFO] -----------------------------end print response desc -----------------------------------"); LOG.info("[INFO] --- --- package result to CallbackResponse cost {} ms", (System.currentTimeMillis() - begin)); rs.setCost(Integer.valueOf(StringUtils.isEmpty(cost) ? "0" : cost)); rs.setStatus(getStatus(status)); rs.setProvider(provider); rs.setVersion(version); rs.setMessage(getNlsMessage(status)); if (ResponseStatus.SUCCESS.getValue() == status) { rs.setData(getCallbackValue(json.get("data").toString(), type)); } return rs; } private static ResponseStatus getStatus(int status) { for (ResponseStatus tmp : ResponseStatus.values()) { if (tmp.getValue() == status) { return tmp; } } throw new UnsupportedOperationException("???"); } private static List<CallbackValue> getCallbackValue(String data, CallbackType type) { List<CallbackValue> rs = Lists.newArrayList(); if (StringUtils.isEmpty(data)) { return rs; } switch (type) { case DIM: return AnswerCoreConstant.GSON.fromJson(data, new TypeToken<List<CallbackDimTreeNode>>() { }.getType()); case MEASURE: return AnswerCoreConstant.GSON.fromJson(data, new TypeToken<List<CallbackMeasureVaue>>() { }.getType()); } throw new IllegalStateException("?"); } /** * ???? * @param status * @return String */ private static String getNlsMessage(int status) { ResponseStatus statusType = getStatus(status); // ? switch (statusType) { case SUCCESS: return "???"; case COOKIE_VALUE_IS_NULL: return "Cookie"; case INTERNAL_SERVER_ERROR: return "?"; case INVALID_PARAM_TYPE: return "?"; case INVALIDATE_PARAM_NUM: return "??"; case INVALIDATE_USER_ID: return "?"; case MIS_PARAM: return "?"; case NOT_CONTENT_COOKIE: return "??cookie?"; case NOT_PROVIDE_USER_ID: return "???"; case PARAM_NOT_ASSIGN_VALUE: return "?"; case UN_AUTH: return "?"; case UN_KNOW_SERVICE: return "?"; case UN_SUPPORTED_METHOD: return ""; case UNKNOW_PARAMS: return "?"; default: } return "??"; } }