From 1acfb98498c6e745e0488fe42450233697d6c40e Mon Sep 17 00:00:00 2001 From: "chen.ma" Date: Sun, 16 Oct 2022 12:15:20 +0800 Subject: [PATCH] Http tool code and format optimization --- .../cn/hippo4j/common/api/JsonFacade.java | 3 +- ...erConsts.java => HttpHeaderConstants.java} | 15 +- .../common/constant/HttpMediaType.java | 4 +- .../common/constant/HttpResponseCode.java | 43 ++- .../toolkit/{IoUtils.java => IoUtil.java} | 6 +- .../common/toolkit/JacksonHandler.java | 4 +- .../cn/hippo4j/common/toolkit/MapUtil.java | 12 +- .../hippo4j/common/toolkit/http/Header.java | 17 +- .../toolkit/http/HttpClientResponse.java | 1 + .../http/{HttpUtils.java => HttpUtil.java} | 282 +++++++++++++----- .../toolkit/http/JdkHttpClientResponse.java | 12 +- .../common/toolkit/logtracing/LogMessage.java | 32 +- .../common/toolkit/http/HttpUtilsTest.java | 14 +- .../service/ThreadPoolAdapterService.java | 4 +- ...olConfigModificationVerifyServiceImpl.java | 4 +- ...olConfigModificationVerifyServiceImpl.java | 4 +- .../ThreadPoolAdapterController.java | 4 +- .../controller/ThreadPoolController.java | 12 +- .../platform/LarkSendMessageHandler.java | 5 +- .../platform/WeChatSendMessageHandler.java | 5 +- .../springboot/starter/core/ClientWorker.java | 2 +- .../starter/remote/ServerHttpAgent.java | 14 +- .../starter/security/SecurityProxy.java | 4 +- 23 files changed, 348 insertions(+), 155 deletions(-) rename hippo4j-common/src/main/java/cn/hippo4j/common/constant/{HttpHeaderConsts.java => HttpHeaderConstants.java} (94%) rename hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/{IoUtils.java => IoUtil.java} (98%) rename hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/{HttpUtils.java => HttpUtil.java} (52%) diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/api/JsonFacade.java b/hippo4j-common/src/main/java/cn/hippo4j/common/api/JsonFacade.java index 374d3f32..97e68659 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/api/JsonFacade.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/api/JsonFacade.java @@ -65,7 +65,8 @@ public interface JsonFacade { List parseArray(String text, Class clazz); /** - * validate Json. + * Validate json. + * * @param text * @return */ diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpHeaderConsts.java b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpHeaderConstants.java similarity index 94% rename from hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpHeaderConsts.java rename to hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpHeaderConstants.java index d75246f4..90ccfa52 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpHeaderConsts.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpHeaderConstants.java @@ -18,20 +18,29 @@ package cn.hippo4j.common.constant; /** - * header constants. + * Http header constants. */ -public interface HttpHeaderConsts { +public interface HttpHeaderConstants { String CLIENT_VERSION_HEADER = "Client-Version"; + String USER_AGENT_HEADER = "User-Agent"; + String REQUEST_SOURCE_HEADER = "Request-Source"; + String CONTENT_TYPE = "Content-Type"; + String CONTENT_LENGTH = "Content-Length"; + String ACCEPT_CHARSET = "Accept-Charset"; + String ACCEPT_ENCODING = "Accept-Encoding"; + String CONTENT_ENCODING = "Content-Encoding"; + String CONNECTION = "Requester"; + String REQUEST_ID = "RequestId"; - String REQUEST_MODULE = "Request-Module"; + String REQUEST_MODULE = "Request-Module"; } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpMediaType.java b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpMediaType.java index 0b0d9843..58caa1d8 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpMediaType.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpMediaType.java @@ -20,7 +20,7 @@ package cn.hippo4j.common.constant; import cn.hippo4j.common.toolkit.StringUtil; /** - * Http Media types. + * Http media type. * * @author Rongzhen Yan */ @@ -85,7 +85,7 @@ public final class HttpMediaType { * Use the given contentType and charset to assemble into a {@code MediaType} object. * * @param contentType contentType - * @param charset charset + * @param charset charset * @return MediaType */ public static HttpMediaType valueOf(String contentType, String charset) { diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpResponseCode.java b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpResponseCode.java index 28bc4d95..e063e6a8 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpResponseCode.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/HttpResponseCode.java @@ -18,50 +18,91 @@ package cn.hippo4j.common.constant; /** - * Http状态码常量 + * Http response code. + * * @author Rongzhen Yan */ public interface HttpResponseCode { int SC_CONTINUE = 100; + int SC_SWITCHING_PROTOCOLS = 101; + int SC_OK = 200; + int SC_CREATED = 201; + int SC_ACCEPTED = 202; + int SC_NON_AUTHORITATIVE_INFORMATION = 203; + int SC_NO_CONTENT = 204; + int SC_RESET_CONTENT = 205; + int SC_PARTIAL_CONTENT = 206; + int SC_MULTIPLE_CHOICES = 300; + int SC_MOVED_PERMANENTLY = 301; + int SC_MOVED_TEMPORARILY = 302; + int SC_FOUND = 302; + int SC_SEE_OTHER = 303; + int SC_NOT_MODIFIED = 304; + int SC_USE_PROXY = 305; + int SC_TEMPORARY_REDIRECT = 307; + int SC_BAD_REQUEST = 400; + int SC_UNAUTHORIZED = 401; + int SC_PAYMENT_REQUIRED = 402; + int SC_FORBIDDEN = 403; + int SC_NOT_FOUND = 404; + int SC_METHOD_NOT_ALLOWED = 405; + int SC_NOT_ACCEPTABLE = 406; + int SC_PROXY_AUTHENTICATION_REQUIRED = 407; + int SC_REQUEST_TIMEOUT = 408; + int SC_CONFLICT = 409; + int SC_GONE = 410; + int SC_LENGTH_REQUIRED = 411; + int SC_PRECONDITION_FAILED = 412; + int SC_REQUEST_ENTITY_TOO_LARGE = 413; + int SC_REQUEST_URI_TOO_LONG = 414; + int SC_UNSUPPORTED_MEDIA_TYPE = 415; + int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; + int SC_EXPECTATION_FAILED = 417; + int SC_INTERNAL_SERVER_ERROR = 500; + int SC_NOT_IMPLEMENTED = 501; + int SC_BAD_GATEWAY = 502; + int SC_SERVICE_UNAVAILABLE = 503; + int SC_GATEWAY_TIMEOUT = 504; + int SC_HTTP_VERSION_NOT_SUPPORTED = 505; } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtils.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java similarity index 98% rename from hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtils.java rename to hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java index c32125d6..f777b35b 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtils.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IoUtil.java @@ -34,7 +34,7 @@ import java.util.zip.GZIPOutputStream; * * @author nacos */ -public class IoUtils { +public class IoUtil { /** * Try decompress by GZIP from stream. @@ -173,7 +173,7 @@ public class IoUtils { public static long copy(Reader input, Writer output) throws IOException { char[] buffer = new char[1 << 12]; long count = 0; - for (int n = 0; (n = input.read(buffer)) >= 0;) { + for (int n = 0; (n = input.read(buffer)) >= 0; ) { output.write(buffer, 0, n); count += n; } @@ -336,6 +336,6 @@ public class IoUtils { } public static void closeQuietly(Closeable... closeable) { - Arrays.stream(closeable).forEach(IoUtils::closeQuietly); + Arrays.stream(closeable).forEach(IoUtil::closeQuietly); } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java index b5e34d32..f86f0df2 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/JacksonHandler.java @@ -78,8 +78,8 @@ public class JacksonHandler implements JsonFacade { try { MAPPER.readTree(text); return true; - } catch (JsonProcessingException jpe) { - return false; + } catch (JsonProcessingException ignored) { } + return false; } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java index 63108237..7436cfda 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MapUtil.java @@ -25,7 +25,7 @@ import java.util.function.BiFunction; import java.util.function.Predicate; /** - * Map utils. + * Map util. */ public class MapUtil { @@ -137,13 +137,11 @@ public class MapUtil { */ public static V computeIfAbsent(Map target, K key, BiFunction mappingFunction, C param1, T param2) { - Objects.requireNonNull(target, "target"); Objects.requireNonNull(key, "key"); Objects.requireNonNull(mappingFunction, "mappingFunction"); Objects.requireNonNull(param1, "param1"); Objects.requireNonNull(param2, "param2"); - V val = target.get(key); if (val == null) { V ret = mappingFunction.apply(param1, param2); @@ -156,11 +154,11 @@ public class MapUtil { /** * remove value, Thread safety depends on whether the Map is a thread-safe Map. * - * @param map map - * @param key key + * @param map map + * @param key key * @param removeJudge judge this key can be remove - * @param key type - * @param value type + * @param key type + * @param value type * @return value */ public static V removeKey(Map map, K key, Predicate removeJudge) { diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java index ad155a9f..14d85b6f 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/Header.java @@ -18,7 +18,7 @@ package cn.hippo4j.common.toolkit.http; import cn.hippo4j.common.constant.Constants; -import cn.hippo4j.common.constant.HttpHeaderConsts; +import cn.hippo4j.common.constant.HttpHeaderConstants; import cn.hippo4j.common.constant.HttpMediaType; import cn.hippo4j.common.toolkit.MapUtil; import cn.hippo4j.common.toolkit.StringUtil; @@ -45,9 +45,8 @@ public class Header { private Header() { header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - addParam(HttpHeaderConsts.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON); - addParam(HttpHeaderConsts.ACCEPT_CHARSET, DEFAULT_CHARSET); - // addParam(HttpHeaderConsts.ACCEPT_ENCODING, DEFAULT_ENCODING); + addParam(HttpHeaderConstants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON); + addParam(HttpHeaderConstants.ACCEPT_CHARSET, DEFAULT_CHARSET); } public static Header newInstance() { @@ -57,7 +56,7 @@ public class Header { /** * Add the key and value to the header. * - * @param key the key + * @param key the key * @param value the value * @return header */ @@ -72,7 +71,7 @@ public class Header { if (contentType == null) { contentType = HttpMediaType.APPLICATION_JSON; } - return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType); + return addParam(HttpHeaderConstants.CONTENT_TYPE, contentType); } public Header build() { @@ -144,7 +143,7 @@ public class Header { * *

Currently only corresponds to the response header of JDK. * - * @param key original response header key + * @param key original response header key * @param values original response header values */ public void addOriginalResponseHeader(String key, List values) { @@ -166,9 +165,9 @@ public class Header { } public String getCharset() { - String acceptCharset = getValue(HttpHeaderConsts.ACCEPT_CHARSET); + String acceptCharset = getValue(HttpHeaderConstants.ACCEPT_CHARSET); if (acceptCharset == null) { - String contentType = getValue(HttpHeaderConsts.CONTENT_TYPE); + String contentType = getValue(HttpHeaderConstants.CONTENT_TYPE); acceptCharset = StringUtil.isNotBlank(contentType) ? analysisCharset(contentType) : Constants.ENCODE; } return acceptCharset; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpClientResponse.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpClientResponse.java index 0afe2cd8..e3cc8ce4 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpClientResponse.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpClientResponse.java @@ -57,6 +57,7 @@ public interface HttpClientResponse extends Closeable { /** * Return the body As string. + * * @return */ String getBodyString(); diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpUtils.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpUtil.java similarity index 52% rename from hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpUtils.java rename to hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpUtil.java index ac063e1c..a992c521 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpUtils.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/HttpUtil.java @@ -21,106 +21,224 @@ import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.constant.HttpMediaType; import cn.hippo4j.common.constant.HttpMethod; import cn.hippo4j.common.constant.HttpResponseCode; -import cn.hippo4j.common.toolkit.IoUtils; +import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.IoUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.logtracing.LogMessage; import cn.hippo4j.common.web.exception.ServiceException; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; + import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; +import java.util.Optional; -import static cn.hippo4j.common.constant.HttpHeaderConsts.CONTENT_LENGTH; +import static cn.hippo4j.common.constant.HttpHeaderConstants.CONTENT_LENGTH; /** * Http request utilities. + * * @author Rongzhen Yan */ @Slf4j -public class HttpUtils { +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class HttpUtil { - private static final int CONNECT_TIMEOUT = 10000; + /** + * Default connect timeout + */ + private static final int DEFAULT_CONNECT_TIMEOUT = 10000; - private static final int READ_TIMEOUT = 300000; + /** + * Default read timeout + */ + private static final int DEFAULT_READ_TIMEOUT = 30000; - private HttpUtils() { + /** + * Send a get network request. + * + * @param url target url + * @param headers headers + * @param params form data + * @param timeout request timeout + * @param clazz return the target data type + * @param return the target data type + * @return + */ + public static T get(String url, Map headers, Map params, long timeout, Class clazz) { + return execute(buildUrl(url, params), HttpMethod.GET, null, headers, timeout, clazz); } + /** + * Send a get network request. + * + * @param url target url + * @param params form data + * @return + */ + public static String get(String url, Map params) { + return execute(buildUrl(url, params), HttpMethod.GET, null, null); + } + + /** + * Send a get network request. + * + * @param url target url + * @return + */ + public static String get(String url) { + return execute(url, HttpMethod.GET, null, null); + } + + /** + * Send a get network request. + * + * @param url target url + * @param clazz return the target data type + * @param return the target data type + * @return + */ + public static T get(String url, Class clazz) { + return JSONUtil.parseObject(get(url), clazz); + } + + /** + * Send a post network request. + * + * @param url target url + * @param body request body + * @param clazz return the target data type + * @param return the target data type + * @return + */ public static T post(String url, Object body, Class clazz) { String result = post(url, body); return JSONUtil.parseObject(result, clazz); } - public static T post(String url, Object body, long timeoutMillis, Class clazz) { - String result = post(url, body, timeoutMillis); + /** + * Send a post network request. + * + * @param url target url + * @param body request body + * @param timeout request timeout + * @param clazz return the target data type + * @param return the target data type + * @return + */ + public static T post(String url, Object body, long timeout, Class clazz) { + String result = post(url, body, timeout); return JSONUtil.parseObject(result, clazz); } - public static T post(String url, Map headers, Map params, long timeoutMillis, Class clazz) { - String result = execute(buildUrl(url, params), HttpMethod.POST, null, headers, timeoutMillis).getBodyString(); - return JSONUtil.parseObject(result, clazz); + /** + * Send a post network request. + * + * @param url target url + * @param headers headers + * @param params form data + * @param timeout request timeout + * @param clazz return the target data type + * @param return the target data type + * @return + */ + public static T post(String url, Map headers, Map params, long timeout, Class clazz) { + return execute(buildUrl(url, params), HttpMethod.POST, null, headers, timeout, clazz); } - public static T post(String url, Map headers, Object body, long timeoutMillis, Class clazz) { - String result = execute(url, HttpMethod.POST, body, headers, timeoutMillis).getBodyString(); - return JSONUtil.parseObject(result, clazz); + /** + * Send a post network request. + * + * @param url target url + * @param headers headers + * @param body request body + * @param timeout request timeout + * @param clazz return the target data type + * @param return the target data type + * @return + */ + public static T post(String url, Map headers, Object body, long timeout, Class clazz) { + return execute(url, HttpMethod.POST, body, headers, timeout, clazz); } + /** + * Send a post network request. + * + * @param url target url + * @param body request body + * @return + */ public static String post(String url, Object body) { - return execute(url, HttpMethod.POST, body, null).getBodyString(); + return execute(url, HttpMethod.POST, body, null); } - public static String post(String url, Object body, long timeoutMillis) { - return execute(url, HttpMethod.POST, body, null, timeoutMillis).getBodyString(); + /** + * Send a post network request. + * + * @param url target url + * @param body request body + * @param timeout request timeout + * @return + */ + public static String post(String url, Object body, long timeout) { + return execute(url, HttpMethod.POST, body, null, timeout, String.class); } + /** + * Send a post network request. + * + * @param url target url + * @param json json data + * @return + */ public static String postJson(String url, String json) { - return executeJson(url, HttpMethod.POST, json, null).getBodyString(); + return executeJson(url, HttpMethod.POST, json, null); } + /** + * Send a put network request. + * + * @param url target url + * @param body request body + * @return + */ public static String put(String url, Object body) { - return execute(url, HttpMethod.PUT, body, null).getBodyString(); + return execute(url, HttpMethod.PUT, body, null); } + /** + * Send a put network request. + * + * @param url target url + * @param body request body + * @param headers headers + * @return + */ public static String put(String url, Object body, Map headers) { - return execute(url, HttpMethod.PUT, body, headers).getBodyString(); - } - - public static T get(String url, Map headers, Map params, long readTimeoutMillis, Class clazz) { - String result = execute(buildUrl(url, params), HttpMethod.GET, null, headers, readTimeoutMillis).getBodyString(); - return JSONUtil.parseObject(result, clazz); - } - - public static String get(String url, Map params) { - return execute(buildUrl(url, params), HttpMethod.GET, null, null).getBodyString(); - } - - public static String get(String url) { - return execute(url, HttpMethod.GET, null, null).getBodyString(); - } - - public static T get(String url, Class clazz) { - return JSONUtil.parseObject(get(url), clazz); + return execute(url, HttpMethod.PUT, body, headers); } /** * Constructs a complete Url from the query string. - * @param url - * @param queryString + * + * @param url target url + * @param queryParams query params * @return */ @SneakyThrows - public static String buildUrl(String url, Map queryString) { - if (null == queryString) { + public static String buildUrl(String url, Map queryParams) { + if (CollectionUtil.isEmpty(queryParams)) { return url; } - StringBuilder builder = new StringBuilder(url); boolean isFirst = true; - for (Map.Entry entry : queryString.entrySet()) { + StringBuilder builder = new StringBuilder(url); + for (Map.Entry entry : queryParams.entrySet()) { String key = entry.getKey(); if (key != null && entry.getValue() != null) { if (isFirst) { @@ -129,7 +247,7 @@ public class HttpUtils { } else { builder.append("&"); } - String value = URLEncoder.encode(queryString.get(key), Constants.ENCODE) + String value = URLEncoder.encode(queryParams.get(key), Constants.ENCODE) .replaceAll("\\+", "%20"); builder.append(key) .append("=") @@ -139,17 +257,49 @@ public class HttpUtils { return builder.toString(); } - public static HttpClientResponse execute(String url, String method, Object param, Map headers) { + private static String executeJson(String url, String method, String json, Map headers) { + if (!JSONUtil.isJson(json)) { + log.error(LogMessage.getInstance().setMsg("Http Call error.") + .kv("url", url) + .kv("method", method) + .kv("json", json) + .kv2String("headers", JSONUtil.toJSONString(headers))); + throw new ServiceException("Invalid http json body, please check it again."); + } + return execute(url, method, json, headers); + } + + private static String execute(String url, String method, Object param, Map headers) { HttpURLConnection connection = createConnection(url, method); - return doExecute(connection, param, headers); + HttpClientResponse response = null; + try { + response = doExecute(connection, param, headers); + return response.getBodyString(); + } finally { + Optional.ofNullable(response).ifPresent(each -> each.close()); + } + } + + private static T execute(String url, String method, Object body, Map headers, long timeout, Class clazz) { + HttpURLConnection connection = createConnection(url, method, timeout); + HttpClientResponse response = null; + try { + response = doExecute(connection, body, headers); + if (clazz == String.class) { + return (T) response.getBodyString(); + } + return JSONUtil.parseObject(response.getBodyString(), clazz); + } finally { + Optional.ofNullable(response).ifPresent(each -> each.close()); + } } @SneakyThrows - public static HttpClientResponse doExecute(HttpURLConnection connection, Object body, Map headers) { + private static HttpClientResponse doExecute(HttpURLConnection connection, Object body, Map headers) { try { - if (headers != null) { - for (String key : headers.keySet()) { - connection.setRequestProperty(key, headers.get(key)); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + connection.setRequestProperty(entry.getKey(), entry.getValue()); } } String bodyString; @@ -165,7 +315,7 @@ public class HttpUtils { OutputStream outputStream = connection.getOutputStream(); outputStream.write(b, 0, b.length); outputStream.flush(); - IoUtils.closeQuietly(outputStream); + IoUtil.closeQuietly(outputStream); } connection.connect(); JdkHttpClientResponse response = new JdkHttpClientResponse(connection); @@ -174,31 +324,14 @@ public class HttpUtils { throw new ServiceException(msg); } return response; - } catch (Throwable e) { - log.error(LogMessage.getInstance().setMsg("Http Call error.") + } catch (Throwable ex) { + log.error(LogMessage.getInstance().setMsg("Http call error. ") .kv("url", connection.getURL()) .kv("method", connection.getRequestMethod()) .kv("body", JSONUtil.toJSONString(body)) - .kv2String("headers", JSONUtil.toJSONString(headers)), e); - throw e; - } - } - - public static HttpClientResponse execute(String url, String method, Object body, Map headers, long timeout) { - HttpURLConnection connection = createConnection(url, method, timeout); - return doExecute(connection, body, headers); - } - - public static HttpClientResponse executeJson(String url, String method, String json, Map headers) { - if (!JSONUtil.isJson(json)) { - log.error(LogMessage.getInstance().setMsg("Http Call error.") - .kv("url", url) - .kv("method", method) - .kv("json", json) - .kv2String("headers", JSONUtil.toJSONString(headers))); - throw new ServiceException("invalid http json body, please check it again."); + .kv2String("headers", JSONUtil.toJSONString(headers)), ex); + throw ex; } - return execute(url, method, json, headers); } @SneakyThrows @@ -206,8 +339,8 @@ public class HttpUtils { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); - connection.setConnectTimeout(CONNECT_TIMEOUT); - connection.setReadTimeout(READ_TIMEOUT); + connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); + connection.setReadTimeout(DEFAULT_READ_TIMEOUT); connection.setRequestMethod(method); connection.setRequestProperty(Constants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON); return connection; @@ -216,7 +349,6 @@ public class HttpUtils { @SneakyThrows private static HttpURLConnection createConnection(String url, String method, long timeout) { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setDoInput(true); connection.setDoOutput(true); connection.setConnectTimeout(Integer.parseInt(String.valueOf(timeout))); diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/JdkHttpClientResponse.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/JdkHttpClientResponse.java index 6a55b245..683b6191 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/JdkHttpClientResponse.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/http/JdkHttpClientResponse.java @@ -18,8 +18,8 @@ package cn.hippo4j.common.toolkit.http; import cn.hippo4j.common.constant.Constants; -import cn.hippo4j.common.constant.HttpHeaderConsts; -import cn.hippo4j.common.toolkit.IoUtils; +import cn.hippo4j.common.constant.HttpHeaderConstants; +import cn.hippo4j.common.toolkit.IoUtil; import lombok.SneakyThrows; import java.io.ByteArrayInputStream; @@ -64,10 +64,10 @@ public class JdkHttpClientResponse implements HttpClientResponse { Header headers = getHeaders(); InputStream errorStream = this.conn.getErrorStream(); this.responseStream = (errorStream != null ? errorStream : this.conn.getInputStream()); - String contentEncoding = headers.getValue(HttpHeaderConsts.CONTENT_ENCODING); + String contentEncoding = headers.getValue(HttpHeaderConstants.CONTENT_ENCODING); // Used to process http content_encoding, when content_encoding is GZIP, use GZIPInputStream if (CONTENT_ENCODING.equals(contentEncoding)) { - byte[] bytes = IoUtils.tryDecompress(this.responseStream); + byte[] bytes = IoUtil.tryDecompress(this.responseStream); return new ByteArrayInputStream(bytes); } return this.responseStream; @@ -87,11 +87,11 @@ public class JdkHttpClientResponse implements HttpClientResponse { @Override public String getBodyString() { - return IoUtils.toString(this.getBody(), Constants.ENCODE); + return IoUtil.toString(this.getBody(), Constants.ENCODE); } @Override public void close() { - IoUtils.closeQuietly(this.responseStream); + IoUtil.closeQuietly(this.responseStream); } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/logtracing/LogMessage.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/logtracing/LogMessage.java index bacbada2..47ef1090 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/logtracing/LogMessage.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/logtracing/LogMessage.java @@ -17,6 +17,9 @@ package cn.hippo4j.common.toolkit.logtracing; +import cn.hippo4j.common.toolkit.StringUtil; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; @@ -24,16 +27,16 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** - * 日志KV打印框架 + * Log message. + * * @author Rongzhen Yan */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class LogMessage { private Map kvs = new ConcurrentHashMap<>(); - private String msg = ""; - private LogMessage() { - } + private String msg = ""; public static LogMessage getInstance() { return new LogMessage(); @@ -75,16 +78,23 @@ public class LogMessage { @Override public String toString() { StringBuilder sb = new StringBuilder(); - - if (msg != null && !msg.isEmpty()) { - sb.append("||_msg=").append(msg); + if (StringUtil.isNotEmpty(msg)) { + sb.append(msg); } - + int tempCount = 0; for (Map.Entry kv : kvs.entrySet()) { - sb.append("||" + kv.getKey() + "=").append(kv.getValue()); + tempCount++; + Object value = kv.getValue(); + if (value != null) { + if (value instanceof String && StringUtil.isEmpty((String) value)) { + continue; + } + sb.append(kv.getKey() + "=").append(kv.getValue()); + if (tempCount != kvs.size()) { + sb.append("||"); + } + } } - return sb.toString(); } - } diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java index d181e362..105228d6 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java @@ -41,7 +41,7 @@ public class HttpUtilsTest { @Test public void get() { - String s = HttpUtils.get(getUrl); + String s = HttpUtil.get(getUrl); Assert.assertNotNull(s); } @@ -52,7 +52,7 @@ public class HttpUtilsTest { loginInfo.setPassword("hippo4j"); loginInfo.setUsername("hippo4j"); loginInfo.setRememberMe(1); - String s = HttpUtils.post(loginUrl, loginInfo); + String s = HttpUtil.post(loginUrl, loginInfo); Result result = JSONUtil.parseObject(s, Result.class); Assert.assertNotNull(result); String data = result.getData().getData(); @@ -66,7 +66,7 @@ public class HttpUtilsTest { loginInfo.setPassword("hippo4j"); loginInfo.setUsername("hippo4j"); loginInfo.setRememberMe(1); - Result result = HttpUtils.post(loginUrl, loginInfo, Result.class); + Result result = HttpUtil.post(loginUrl, loginInfo, Result.class); Assert.assertNotNull(result); String data = result.getData().getData(); Assert.assertNotNull(data); @@ -79,7 +79,7 @@ public class HttpUtilsTest { loginInfo.setPassword("hippo4j"); loginInfo.setUsername("hippo4j"); loginInfo.setRememberMe(1); - Assert.assertThrows(SocketTimeoutException.class, () -> HttpUtils.post(loginUrl, loginInfo, 1, Result.class)); + Assert.assertThrows(SocketTimeoutException.class, () -> HttpUtil.post(loginUrl, loginInfo, 1, Result.class)); } @Test @@ -87,7 +87,7 @@ public class HttpUtilsTest { Map map = new HashMap<>(); map.put("password", "hippo4j"); map.put("username", "hippo4j"); - String s = HttpUtils.buildUrl(getUrl, map); + String s = HttpUtil.buildUrl(getUrl, map); Assert.assertEquals(getUrl + "?password=hippo4j&username=hippo4j", s); } @@ -96,7 +96,9 @@ public class HttpUtilsTest { private static class LoginInfo { private String username; + private String password; + private Integer rememberMe; } @@ -105,6 +107,7 @@ public class HttpUtilsTest { private static class Result { private String code; + private ResultData data; } @@ -113,6 +116,7 @@ public class HttpUtilsTest { private static class ResultData { private String data; + private String[] roles; } } \ No newline at end of file diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java index 4a92876d..03b23bb5 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java @@ -25,7 +25,7 @@ import cn.hippo4j.common.design.observer.ObserverMessage; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO; @@ -101,7 +101,7 @@ public class ThreadPoolAdapterService { param.put("mark", requestParameter.getMark()); param.put("threadPoolKey", requestParameter.getThreadPoolKey()); try { - String resultStr = HttpUtils.get(url, param); + String resultStr = HttpUtil.get(url, param); if (StringUtil.isNotBlank(resultStr)) { Result restResult = JSONUtil.parseObject(resultStr, new TypeReference>() { }); diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/AdapterThreadPoolConfigModificationVerifyServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/AdapterThreadPoolConfigModificationVerifyServiceImpl.java index 3b0be334..fb6cf00f 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/AdapterThreadPoolConfigModificationVerifyServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/AdapterThreadPoolConfigModificationVerifyServiceImpl.java @@ -19,7 +19,7 @@ package cn.hippo4j.config.service.biz.impl; import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -40,7 +40,7 @@ public class AdapterThreadPoolConfigModificationVerifyServiceImpl extends Abstra protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) { for (String each : getClientAddress(reqDTO)) { String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update"); - HttpUtils.post(urlString, reqDTO); + HttpUtil.post(urlString, reqDTO); } } } diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/WebThreadPoolConfigModificationVerifyServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/WebThreadPoolConfigModificationVerifyServiceImpl.java index 9ede76a6..e4fb6b17 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/WebThreadPoolConfigModificationVerifyServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/WebThreadPoolConfigModificationVerifyServiceImpl.java @@ -19,7 +19,7 @@ package cn.hippo4j.config.service.biz.impl; import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -40,7 +40,7 @@ public class WebThreadPoolConfigModificationVerifyServiceImpl extends AbstractCo protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) { for (String each : getClientAddress(reqDTO)) { String urlString = StringUtil.newBuilder("http://", each, "/web/update/pool"); - HttpUtils.post(urlString, reqDTO); + HttpUtil.post(urlString, reqDTO); } } } diff --git a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java index c01e628e..ada43d70 100644 --- a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java +++ b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java @@ -19,7 +19,7 @@ package cn.hippo4j.console.controller; import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.toolkit.*; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO; @@ -66,7 +66,7 @@ public class ThreadPoolAdapterController { if (UserContext.getUserRole().equals("ROLE_ADMIN")) { for (String each : requestParameter.getClientAddressList()) { String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update"); - HttpUtils.post(urlString, requestParameter); + HttpUtil.post(urlString, requestParameter); } } else { ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParameter, ConfigModifySaveReqDTO.class); diff --git a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java index 305e6876..539d6813 100644 --- a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java +++ b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java @@ -21,7 +21,7 @@ import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.model.InstanceInfo; import cn.hippo4j.common.toolkit.*; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.common.web.exception.ErrorCodeEnum; @@ -109,14 +109,14 @@ public class ThreadPoolController { public Result runState(@PathVariable("tpId") String tpId, @RequestParam(value = "clientAddress") String clientAddress) { String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/state/", tpId); - return HttpUtils.get(urlString, Result.class); + return HttpUtil.get(urlString, Result.class); } @GetMapping("/run/thread/state/{tpId}") public Result runThreadState(@PathVariable("tpId") String tpId, @RequestParam(value = "clientAddress") String clientAddress) { String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/thread/state/", tpId); - return HttpUtils.get(urlString, Result.class); + return HttpUtil.get(urlString, Result.class); } @GetMapping("/list/client/instance/{itemId}") @@ -152,13 +152,13 @@ public class ThreadPoolController { @GetMapping("/web/base/info") public Result getPoolBaseState(@RequestParam(value = "clientAddress") String clientAddress) { String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/base/info"); - return HttpUtils.get(urlString, Result.class); + return HttpUtil.get(urlString, Result.class); } @GetMapping("/web/run/state") public Result getPoolRunState(@RequestParam(value = "clientAddress") String clientAddress) { String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/run/state"); - return HttpUtils.get(urlString, Result.class); + return HttpUtil.get(urlString, Result.class); } @PostMapping("/web/update/pool") @@ -166,7 +166,7 @@ public class ThreadPoolController { if (UserContext.getUserRole().equals("ROLE_ADMIN")) { for (String each : requestParam.getClientAddressList()) { String urlString = StringUtil.newBuilder(HTTP, each, "/web/update/pool"); - HttpUtils.post(urlString, requestParam); + HttpUtil.post(urlString, requestParam); } } else { ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParam, ConfigModifySaveReqDTO.class); diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java index 790af7d3..356ea850 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java @@ -18,7 +18,7 @@ package cn.hippo4j.message.platform; import cn.hippo4j.common.toolkit.Singleton; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.enums.NotifyPlatformEnum; import cn.hippo4j.message.enums.NotifyTypeEnum; @@ -75,7 +75,6 @@ public class LarkSendMessageHandler implements SendMessageHandler headers, Map paramValues, long readTimeoutMs) { isHealthStatus(); injectSecurityInfo(paramValues); - return HttpUtils.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class); + return HttpUtil.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class); } @Override public Result httpPostByConfig(String path, Map headers, Map paramValues, long readTimeoutMs) { isHealthStatus(); injectSecurityInfo(paramValues); - return HttpUtils.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class); + return HttpUtil.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class); } @Override @@ -138,7 +138,7 @@ public class ServerHttpAgent implements HttpAgent { @Deprecated private String injectSecurityInfoByPath(String path) { - String resultPath = HttpUtils.buildUrl(path, injectSecurityInfo(new HashMap<>())); + String resultPath = HttpUtil.buildUrl(path, injectSecurityInfo(new HashMap<>())); return resultPath; } } diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java index e2ad35c7..72c5bd07 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java @@ -21,7 +21,7 @@ import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.model.TokenInfo; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hippo4j.common.toolkit.http.HttpUtils; +import cn.hippo4j.common.toolkit.http.HttpUtil; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.springboot.starter.config.BootstrapProperties; import lombok.extern.slf4j.Slf4j; @@ -79,7 +79,7 @@ public class SecurityProxy { bodyMap.put("userName", username); bodyMap.put("password", password); try { - Result result = HttpUtils.post(url, bodyMap, Result.class); + Result result = HttpUtil.post(url, bodyMap, Result.class); if (!result.isSuccess()) { log.error("Error getting access token. message: {}", result.getMessage()); return false;