From cb1419453f98f316c44f11965dd93805a1e243ef Mon Sep 17 00:00:00 2001 From: Shing Rui Date: Sat, 19 Oct 2024 09:49:44 +0800 Subject: [PATCH 1/3] Add JSONUtils and include all json convert methods. --- .../client/JsonRpcClientHandler.java | 4 +- .../JsonRpcClientInvocationHandler.java | 4 +- .../jsonrpc4j/client/JsonRpcHttpClient.java | 20 ++-- .../client/JsonRpcHttpClientHandler.java | 7 +- .../jsonrpc4j/client/JsonRpcTcpClient.java | 20 ++-- .../client/JsonRpcTcpClientHandler.java | 7 +- .../sunquakes/jsonrpc4j/discovery/Consul.java | 9 +- .../sunquakes/jsonrpc4j/discovery/Nacos.java | 4 +- .../sunquakes/jsonrpc4j/dto/RequestDto.java | 4 + .../jsonrpc4j/exception/JSONException.java | 7 ++ .../server/JsonRpcHttpServerHandler.java | 4 +- .../server/JsonRpcTcpServerHandler.java | 4 +- .../sunquakes/jsonrpc4j/utils/JSONUtils.java | 89 +++++++++++++++++ .../jsonrpc4j/utils/RequestUtils.java | 66 ++++++------- .../com/sunquakes/jsonrpc4j/JsonTest.java | 4 +- .../client/JsonRpcHttpsClientTest.java | 24 +++-- .../server/JsonRpcHttpServerTest.java | 38 ++++---- .../server/JsonRpcTcpServerTest.java | 27 +++--- .../jsonrpc4j/utils/JSONUtilsTest.java | 95 +++++++++++++++++++ 19 files changed, 313 insertions(+), 124 deletions(-) create mode 100644 src/main/java/com/sunquakes/jsonrpc4j/exception/JSONException.java create mode 100644 src/main/java/com/sunquakes/jsonrpc4j/utils/JSONUtils.java create mode 100644 src/test/java/com/sunquakes/jsonrpc4j/utils/JSONUtilsTest.java diff --git a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientHandler.java b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientHandler.java index c33f54e..5531c42 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientHandler.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientHandler.java @@ -1,9 +1,9 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSON; import com.sunquakes.jsonrpc4j.ErrorEnum; import com.sunquakes.jsonrpc4j.dto.ErrorDto; import com.sunquakes.jsonrpc4j.dto.ErrorResponseDto; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import com.sunquakes.jsonrpc4j.utils.RequestUtils; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; @@ -41,7 +41,7 @@ protected void handleInternalError(ChannelHandlerContext ctx) { ErrorResponseDto errorResponseDto = new ErrorResponseDto(null, RequestUtils.JSONRPC, new ErrorDto(ErrorEnum.INTERNAL_ERROR.getCode(), ErrorEnum.INTERNAL_ERROR.getText(), null)); Promise promise = promiseMap.get(channel); if (promise != null) { - promise.setSuccess(JSON.toJSONString(errorResponseDto)); + promise.setSuccess(JSONUtils.toString(errorResponseDto)); promiseMap.remove(channel); } } diff --git a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientInvocationHandler.java b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientInvocationHandler.java index 65574a5..c7fbc95 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientInvocationHandler.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcClientInvocationHandler.java @@ -1,6 +1,6 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSON; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.InvocationHandler; @@ -26,6 +26,6 @@ public JsonRpcClientInvocationHandler(JsonRpcClientInterface jsonRpcClient, Stri @Override public Object invoke(Object proxy, Method method, Object[] args) { String methodPath = String.format("/%s/%s", service, method.getName()); - return JSON.to(method.getReturnType(), jsonRpcClient.handle(methodPath, args)); + return JSONUtils.toJavaObject(method.getReturnType(), jsonRpcClient.handle(methodPath, args)); } } diff --git a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClient.java b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClient.java index 1ba4cd1..916a41c 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClient.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClient.java @@ -1,14 +1,14 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSON; -import com.alibaba.fastjson2.JSONObject; import com.sunquakes.jsonrpc4j.ErrorEnum; import com.sunquakes.jsonrpc4j.JsonRpcProtocol; import com.sunquakes.jsonrpc4j.config.Config; import com.sunquakes.jsonrpc4j.dto.ErrorDto; +import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.dto.ResponseDto; import com.sunquakes.jsonrpc4j.exception.JsonRpcClientException; import com.sunquakes.jsonrpc4j.exception.JsonRpcException; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import com.sunquakes.jsonrpc4j.utils.RequestUtils; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; @@ -64,19 +64,15 @@ public void initLoadBalancer() { @Override public Object handle(String method, Object[] args) throws JsonRpcException { - JSONObject request = new JSONObject(); - request.put("id", RequestUtils.getId()); - request.put("jsonrpc", RequestUtils.JSONRPC); - request.put("method", method); - request.put("params", args); + RequestDto requestDto = new RequestDto(RequestUtils.getId(), RequestUtils.JSONRPC, method, args); ResponseDto responseDto; String body; FixedChannelPool pool = loadBalancer.getPool(); try { Channel channel = pool.acquire().get(); - body = jsonRpcHttpClientHandler.send(request, channel); + body = jsonRpcHttpClientHandler.send(requestDto, channel); pool.release(channel); - responseDto = JSONObject.parseObject(body, ResponseDto.class); + responseDto = JSONUtils.parseJavaObject(body, ResponseDto.class); } catch (InterruptedException e) { loadBalancer.removePool(pool); Thread.currentThread().interrupt(); @@ -85,9 +81,9 @@ public Object handle(String method, Object[] args) throws JsonRpcException { throw new JsonRpcClientException(e.getMessage()); } if (responseDto.getResult() == null) { - JSONObject bodyJSON = JSON.parseObject(body); - if (bodyJSON.containsKey("error")) { - ErrorDto errorDto = JSONObject.parseObject(bodyJSON.getString("error"), ErrorDto.class); + Object error = JSONUtils.get(JSONUtils.parseJSONObject(body), "error"); + if (error != null) { + ErrorDto errorDto = JSONUtils.parseJavaObject(JSONUtils.toString(error), ErrorDto.class); throw ErrorEnum.getException(errorDto.getCode(), errorDto.getMessage()); } } diff --git a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClientHandler.java b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClientHandler.java index 55fad26..bc1e0d9 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClientHandler.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpClientHandler.java @@ -1,6 +1,7 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSONObject; +import com.sunquakes.jsonrpc4j.dto.RequestDto; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import com.sunquakes.jsonrpc4j.utils.RequestUtils; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @@ -25,11 +26,11 @@ public class JsonRpcHttpClientHandler extends JsonRpcClientHandler { @Synchronized - public synchronized String send(JSONObject data, Channel channel) throws InterruptedException, ExecutionException { + public synchronized String send(RequestDto data, Channel channel) throws InterruptedException, ExecutionException { Promise promise = new DefaultPromise<>(channel.eventLoop()); promiseMap.put(channel, promise); - String message = data.toJSONString(); + String message = JSONUtils.toString(data); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, ""); request.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8"); ByteBuf buffer = request.content().clear(); diff --git a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClient.java b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClient.java index eca3978..ba02d73 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClient.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClient.java @@ -1,13 +1,13 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSON; -import com.alibaba.fastjson2.JSONObject; import com.sunquakes.jsonrpc4j.ErrorEnum; import com.sunquakes.jsonrpc4j.config.Config; import com.sunquakes.jsonrpc4j.dto.ErrorDto; +import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.dto.ResponseDto; import com.sunquakes.jsonrpc4j.exception.JsonRpcClientException; import com.sunquakes.jsonrpc4j.exception.JsonRpcException; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import com.sunquakes.jsonrpc4j.utils.RequestUtils; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; @@ -71,19 +71,15 @@ protected void initChannel(SocketChannel ch) throws Exception { @Override public Object handle(String method, Object[] args) throws JsonRpcException { - JSONObject request = new JSONObject(); - request.put("id", RequestUtils.getId()); - request.put("jsonrpc", RequestUtils.JSONRPC); - request.put("method", method); - request.put("params", args); + RequestDto requestDto = new RequestDto(RequestUtils.getId(), RequestUtils.JSONRPC, method, args); ResponseDto responseDto; String body; FixedChannelPool pool = loadBalancer.getPool(); try { Channel channel = pool.acquire().get(); - body = jsonRpcTcpClientHandler.send(request, channel); + body = jsonRpcTcpClientHandler.send(requestDto, channel); pool.release(channel); - responseDto = JSONObject.parseObject(body, ResponseDto.class); + responseDto = JSONUtils.toJavaObject(ResponseDto.class, body); } catch (InterruptedException e) { loadBalancer.removePool(pool); Thread.currentThread().interrupt(); @@ -92,9 +88,9 @@ public Object handle(String method, Object[] args) throws JsonRpcException { throw new JsonRpcClientException(e.getMessage()); } if (responseDto.getResult() == null) { - JSONObject bodyJSON = JSON.parseObject(body); - if (bodyJSON.containsKey("error")) { - ErrorDto errorDto = JSONObject.parseObject(bodyJSON.getString("error"), ErrorDto.class); + Object error = JSONUtils.get(JSONUtils.parseJSONObject(body), "error"); + if (error != null) { + ErrorDto errorDto = JSONUtils.parseJavaObject(JSONUtils.toString(error), ErrorDto.class); throw ErrorEnum.getException(errorDto.getCode(), errorDto.getMessage()); } } diff --git a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClientHandler.java b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClientHandler.java index 5e125c2..899ee25 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClientHandler.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/JsonRpcTcpClientHandler.java @@ -1,7 +1,8 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSONObject; +import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.utils.ByteArrayUtils; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; @@ -34,8 +35,8 @@ public JsonRpcTcpClientHandler(TcpClientOption tcpClientOption) { } @Synchronized - public synchronized String send(JSONObject request, Channel channel) throws InterruptedException, ExecutionException { - String message = request.toJSONString() + tcpClientOption.getPackageEof(); + public synchronized String send(RequestDto request, Channel channel) throws InterruptedException, ExecutionException { + String message = JSONUtils.toString(request) + tcpClientOption.getPackageEof(); ByteBuf byteBuf = channel.alloc().buffer(tcpClientOption.getPackageMaxLength()); byteBuf.writeBytes(message.getBytes()); diff --git a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java index f8e12c3..a6c797f 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java @@ -1,10 +1,9 @@ package com.sunquakes.jsonrpc4j.discovery; -import com.alibaba.fastjson2.JSONArray; -import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.annotation.JSONField; import com.sunquakes.jsonrpc4j.JsonRpcProtocol; import com.sunquakes.jsonrpc4j.utils.AddressUtils; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; @@ -70,7 +69,7 @@ public boolean register(String name, String protocol, String hostname, int port) .path("/v1/agent/service/register") .build(); try { - FullHttpResponse res = client.put(fullUrl.getPath() + "?" + fullUrl.getQuery(), JSONObject.toJSONString(service)); + FullHttpResponse res = client.put(fullUrl.getPath() + "?" + fullUrl.getQuery(), JSONUtils.toString(service)); if (!res.status().equals(HttpResponseStatus.OK)) { return false; } @@ -101,7 +100,7 @@ private void checkRegister(String protocol, String hostname, int port, String na .path("/v1/agent/check/register") .build(); try { - FullHttpResponse res = client.put(fullUrl.getPath() + "?" + fullUrl.getQuery(), JSONObject.toJSONString(serviceCheck)); + FullHttpResponse res = client.put(fullUrl.getPath() + "?" + fullUrl.getQuery(), JSONUtils.toString(serviceCheck)); if (!res.status().equals(HttpResponseStatus.OK)) { log.error("Health check register failed."); } @@ -124,7 +123,7 @@ public String get(String name) { } ByteBuf content = res.content(); String body = content.toString(CharsetUtil.UTF_8); - List healthyServices = JSONArray.parseArray(body, HealthService.class); + List healthyServices = JSONUtils.parseList(body, HealthService.class); return healthyServices.stream().map(item -> AddressUtils.getUrl(item.getService().getAddress(), item.getService().getPort())).collect(Collectors.joining(",")); } catch (Exception e) { Thread.currentThread().interrupt(); diff --git a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java index c0e3749..ffa2cd7 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java @@ -1,7 +1,7 @@ package com.sunquakes.jsonrpc4j.discovery; -import com.alibaba.fastjson2.JSONObject; import com.sunquakes.jsonrpc4j.exception.JsonRpcException; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; @@ -98,7 +98,7 @@ public String get(String name) { } ByteBuf buf = res.content(); String json = buf.toString(CharsetUtil.UTF_8); - GetResp resp = JSONObject.parseObject(json, GetResp.class); + GetResp resp = JSONUtils.parseJavaObject(json, GetResp.class); return resp.getHosts().stream().filter(item -> item.healthy).map(item -> String.format("%s:%d", item.getIp(), item.getPort())).collect(Collectors.joining(",")); } catch (Exception e) { Thread.currentThread().interrupt(); diff --git a/src/main/java/com/sunquakes/jsonrpc4j/dto/RequestDto.java b/src/main/java/com/sunquakes/jsonrpc4j/dto/RequestDto.java index b3c8475..fae593d 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/dto/RequestDto.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/dto/RequestDto.java @@ -1,8 +1,12 @@ package com.sunquakes.jsonrpc4j.dto; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; @Data +@NoArgsConstructor +@AllArgsConstructor public class RequestDto { private String id; diff --git a/src/main/java/com/sunquakes/jsonrpc4j/exception/JSONException.java b/src/main/java/com/sunquakes/jsonrpc4j/exception/JSONException.java new file mode 100644 index 0000000..d4835ae --- /dev/null +++ b/src/main/java/com/sunquakes/jsonrpc4j/exception/JSONException.java @@ -0,0 +1,7 @@ +package com.sunquakes.jsonrpc4j.exception; + +public class JSONException extends RuntimeException { + public JSONException(String message) { + super(message); + } +} diff --git a/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerHandler.java b/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerHandler.java index 52a4429..753698a 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerHandler.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerHandler.java @@ -1,6 +1,6 @@ package com.sunquakes.jsonrpc4j.server; -import com.alibaba.fastjson2.JSON; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; @@ -43,7 +43,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception JsonRpcServerHandler jsonRpcServerHandler = new JsonRpcServerHandler(applicationContext); Object res = jsonRpcServerHandler.handle(body); - String output = JSON.toJSONString(res); + String output = JSONUtils.toString(res); send(ctx, output, HttpResponseStatus.OK, httpVersion); httpRequest.release(); diff --git a/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerHandler.java b/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerHandler.java index a20f679..ee42160 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerHandler.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerHandler.java @@ -1,7 +1,7 @@ package com.sunquakes.jsonrpc4j.server; -import com.alibaba.fastjson2.JSON; import com.sunquakes.jsonrpc4j.utils.ByteArrayUtils; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; @@ -67,7 +67,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception if (bytes.length > 0) { JsonRpcServerHandler jsonRpcServerHandler = new JsonRpcServerHandler(applicationContext); Object res = jsonRpcServerHandler.handle(new String(bytes)); - byte[] output = ByteArrayUtils.merge(JSON.toJSONBytes(res), packageEof.getBytes()); + byte[] output = ByteArrayUtils.merge(JSONUtils.toBytes(res), packageEof.getBytes()); ctx.writeAndFlush(output); bytes = initBytes; } diff --git a/src/main/java/com/sunquakes/jsonrpc4j/utils/JSONUtils.java b/src/main/java/com/sunquakes/jsonrpc4j/utils/JSONUtils.java new file mode 100644 index 0000000..1dba846 --- /dev/null +++ b/src/main/java/com/sunquakes/jsonrpc4j/utils/JSONUtils.java @@ -0,0 +1,89 @@ +package com.sunquakes.jsonrpc4j.utils; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import com.sunquakes.jsonrpc4j.exception.JSONException; +import lombok.experimental.UtilityClass; + +import java.util.ArrayList; +import java.util.List; + +@UtilityClass +public class JSONUtils { + + public String toString(Object object) { + return JSON.toJSONString(object); + } + + public T toJavaObject(Class clazz, Object object) { + return JSON.to(clazz, object); + } + + public byte[] toBytes(Object object) { + return JSON.toJSONBytes(object); + } + + public T parseJavaObject(String object, Class clazz) { + return JSONObject.parseObject(object, clazz); + } + + public Object parseJSONObject(String object) { + return JSONObject.parseObject(object); + } + + public List parseList(String object, Class clazz) { + return JSONArray.parseArray(object, clazz); + } + + public Object parse(String object) { + return JSON.parse(object); + } + + public boolean isArray(Object object) { + return object instanceof JSONArray; + } + + public boolean isObject(Object object) { + return object instanceof JSONObject; + } + + public List toList(Object object, Callback callback) { + JSONArray jsonArray = (JSONArray) object; + List list = new ArrayList<>(); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + list.add(callback.call(i, jsonObject)); + } + return list; + } + + public boolean containsKey(Object object, String key) { + JSONObject jsonObject = (JSONObject) object; + return jsonObject.containsKey(key); + } + + public Object[] toArray(Object object, int length, Callback callback) { + JSONArray jsonArray = (JSONArray) object; + Object[] arr = new Object[length]; + for (int i = 0; i < length; i++) { + Object item = jsonArray.get(i); + arr[i] = callback.call(i, item); + } + return arr; + } + + public Object get(Object object, String key) { + JSONObject jsonObject = (JSONObject) object; + return jsonObject.get(key); + } + + public Object[] toArray(Object object) { + JSONArray jsonArray = (JSONArray) object; + return jsonArray.toArray(); + } + + interface Callback { + Object call(int index, Object object) throws JSONException; + } +} diff --git a/src/main/java/com/sunquakes/jsonrpc4j/utils/RequestUtils.java b/src/main/java/com/sunquakes/jsonrpc4j/utils/RequestUtils.java index 4ccd7ee..ec41520 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/utils/RequestUtils.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/utils/RequestUtils.java @@ -1,12 +1,10 @@ package com.sunquakes.jsonrpc4j.utils; -import com.alibaba.fastjson2.JSON; -import com.alibaba.fastjson2.JSONArray; -import com.alibaba.fastjson2.JSONObject; import com.sunquakes.jsonrpc4j.dto.NotifyRequestDto; import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.exception.InvalidParamsException; import com.sunquakes.jsonrpc4j.exception.InvalidRequestException; +import com.sunquakes.jsonrpc4j.exception.JSONException; import com.sunquakes.jsonrpc4j.exception.MethodNotFoundException; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; @@ -16,9 +14,7 @@ import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; -import java.util.ArrayList; import java.util.Enumeration; -import java.util.List; import java.util.UUID; /** @@ -36,26 +32,21 @@ public class RequestUtils { public static final String JSONRPC = "2.0"; public Object parseRequestBody(String json) throws InvalidRequestException { - Object typeObject = JSON.parse(json); - if (typeObject instanceof JSONArray jsonArray) { - List list = new ArrayList<>(); - for (int i = 0; i < jsonArray.size(); i++) { - JSONObject jsonObject = jsonArray.getJSONObject(i); - list.add(parseSingleRequestBody(jsonObject)); - } - return list; - } else if (typeObject instanceof JSONObject jsonObject) { - return parseSingleRequestBody(jsonObject); + Object typeObject = JSONUtils.parse(json); + if (JSONUtils.isArray(typeObject)) { + return JSONUtils.toList(typeObject, (int index, Object item) -> parseSingleRequestBody(item)); + } else if (JSONUtils.isObject(typeObject)) { + return parseSingleRequestBody(typeObject); } else { throw new InvalidRequestException(); } } - public Object parseSingleRequestBody(JSONObject jsonObject) { - if (jsonObject.containsKey("id")) { - return jsonObject.toJavaObject(RequestDto.class); + public Object parseSingleRequestBody(Object jsonObject) { + if (JSONUtils.containsKey(jsonObject, "id")) { + return JSONUtils.toJavaObject(RequestDto.class, jsonObject); } else { - return jsonObject.toJavaObject(NotifyRequestDto.class); + return JSONUtils.toJavaObject(NotifyRequestDto.class, jsonObject); } } @@ -79,13 +70,13 @@ public String[] parseMethod(String method) throws MethodNotFoundException { } public Object[] parseParams(Object params, String[] names) throws InvalidParamsException { - if (params instanceof JSONArray jsonArray) { - return jsonArray.toArray(); - } else if (params instanceof JSONObject jsonObject) { + if (JSONUtils.isArray(params)) { + return JSONUtils.toArray(params); + } else if (JSONUtils.isObject(params)) { int l = names.length; Object[] res = new Object[l]; for (int i = 0; i < l; i++) { - res[i] = jsonObject.get(names[i]); + res[i] = JSONUtils.get(params, names[i]); } return res; } else { @@ -95,23 +86,22 @@ public Object[] parseParams(Object params, String[] names) throws InvalidParamsE public Object[] parseParams(Object params, Parameter[] paramsReflect) throws InvalidParamsException { int l = paramsReflect.length; - if (params instanceof JSONArray jsonArray) { - Object[] res = new Object[l]; - for (int i = 0; i < l; i++) { - Object item = jsonArray.get(i); - res[i] = JSON.to(paramsReflect[i].getType(), item); - } - return res; - } else if (params instanceof JSONObject jsonObject) { - Object[] res = new Object[l]; - for (int i = 0; i < l; i++) { - String key = paramsReflect[i].getName(); - if (!jsonObject.containsKey(key)) { - throw new InvalidParamsException(); + if (JSONUtils.isArray(params)) { + return JSONUtils.toArray(params, l, (int index, Object item) -> JSONUtils.toJavaObject(paramsReflect[index].getType(), item)); + } else if (JSONUtils.isObject(params)) { + try { + Object[] res = new Object[l]; + for (int i = 0; i < l; i++) { + String key = paramsReflect[i].getName(); + if (!JSONUtils.containsKey(params, key)) { + throw new InvalidParamsException(); + } + res[i] = JSONUtils.toJavaObject(paramsReflect[i].getType(), JSONUtils.get(params, key)); } - res[i] = JSON.to(paramsReflect[i].getType(), jsonObject.get(key)); + return res; + } catch (JSONException e) { + throw new InvalidParamsException(); } - return res; } else { throw new InvalidParamsException(); } diff --git a/src/test/java/com/sunquakes/jsonrpc4j/JsonTest.java b/src/test/java/com/sunquakes/jsonrpc4j/JsonTest.java index 0bad8e8..8e0d64b 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/JsonTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/JsonTest.java @@ -1,7 +1,7 @@ package com.sunquakes.jsonrpc4j; -import com.alibaba.fastjson2.JSONObject; import com.sunquakes.jsonrpc4j.discovery.Nacos; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -14,7 +14,7 @@ class JsonTest { @Test void testUnescape() { String json = "{\"name\":\"DEFAULT_GROUP@@php_http\",\"groupName\":\"DEFAULT_GROUP\",\"clusters\":\"\",\"cacheMillis\":10000,\"hosts\":[{\"instanceId\":\"10.222.1.164#9504#DEFAULT#DEFAULT_GROUP@@php_http\",\"ip\":\"10.222.1.164\",\"port\":9504,\"weight\":1.0,\"healthy\":true,\"enabled\":true,\"ephemeral\":false,\"clusterName\":\"DEFAULT\",\"serviceName\":\"DEFAULT_GROUP@@php_http\",\"metadata\":{\"server\":\"jsonrpc-http\",\"protocol\":\"jsonrpc-http\",\"className\":\"App\\\\JsonRpc\\\\PhpHttpService\",\"publishTo\":\"nacos\"},\"ipDeleteTimeout\":30000,\"instanceHeartBeatInterval\":5000,\"instanceHeartBeatTimeOut\":15000}],\"lastRefTime\":1675518467553,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false,\"valid\":true}"; - Nacos.GetResp resp = JSONObject.parseObject(json, Nacos.GetResp.class); + Nacos.GetResp resp = JSONUtils.parseJavaObject(json, Nacos.GetResp.class); assertNotNull(resp); } } diff --git a/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java b/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java index 5234c2a..252b63c 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java @@ -1,6 +1,9 @@ package com.sunquakes.jsonrpc4j.client; -import com.alibaba.fastjson2.JSONObject; +import com.sunquakes.jsonrpc4j.dto.RequestDto; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; +import lombok.AllArgsConstructor; +import lombok.Data; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; @@ -50,14 +53,15 @@ public void beforeTest() throws UnsupportedEncodingException { @Test void testRequest() throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { - JSONObject params = new JSONObject(); - params.put("a", 1); - params.put("b", 2); - JSONObject request = new JSONObject(); - request.put("id", "1234567890"); - request.put("jsonrpc", "2.0"); - request.put("method", "JsonRpc/add"); - request.put("params", params); + @Data + @AllArgsConstructor + class Params { + int a; + int b; + } + Params params = new Params(1, 2); + RequestDto requestDto = new RequestDto("1234567890", "2.0", "JsonRpc/add", params); + String request = JSONUtils.toString(requestDto); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustStrategy() { @@ -69,7 +73,7 @@ public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws Ce SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpPost httpPost = new HttpPost("https://localhost:3205"); - httpPost.setEntity(new StringEntity(request.toString(), ContentType.APPLICATION_JSON)); + httpPost.setEntity(new StringEntity(request, ContentType.APPLICATION_JSON)); HttpResponse response = httpClient.execute(httpPost); assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":3}", EntityUtils.toString(response.getEntity())); } diff --git a/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java b/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java index 7ebe704..c052e02 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java @@ -1,6 +1,9 @@ package com.sunquakes.jsonrpc4j.server; -import com.alibaba.fastjson2.JSONObject; +import com.sunquakes.jsonrpc4j.dto.RequestDto; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; +import lombok.AllArgsConstructor; +import lombok.Data; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; @@ -23,33 +26,32 @@ @ContextConfiguration("classpath:applicationContext.xml") class JsonRpcHttpServerTest { + @Data + @AllArgsConstructor + class Params { + int a; + int b; + } + @Test void testHandle() throws IOException { - JSONObject params = new JSONObject(); - params.put("a", 1); - params.put("b", 2); - JSONObject request = new JSONObject(); - request.put("id", "1234567890"); - request.put("jsonrpc", "2.0"); - request.put("method", "JsonRpc/add"); - request.put("params", params); + Params params = new Params(1, 2); + RequestDto requestDto = new RequestDto("1234567890", "2.0", "JsonRpc/add", params); + String request = JSONUtils.toString(requestDto); + CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:3200"); - httpPost.setEntity(new StringEntity(request.toString(), ContentType.APPLICATION_JSON)); + httpPost.setEntity(new StringEntity(request, ContentType.APPLICATION_JSON)); HttpResponse response = httpClient.execute(httpPost); assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":3}", EntityUtils.toString(response.getEntity())); } @Test void testMethod() throws IOException { - JSONObject params = new JSONObject(); - params.put("a", 3); - params.put("b", 4); - JSONObject request = new JSONObject(); - request.put("id", "1234567890"); - request.put("jsonrpc", "2.0"); - request.put("method", "json_rpc/add"); - request.put("params", params); + Params params = new Params(3, 4); + RequestDto requestDto = new RequestDto("1234567890", "2.0", "json_rpc/add", params); + String request = JSONUtils.toString(requestDto); + CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:3200"); httpPost.setEntity(new StringEntity(request.toString(), ContentType.APPLICATION_JSON)); diff --git a/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerTest.java b/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerTest.java index 3105cac..4ab5e22 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcTcpServerTest.java @@ -1,8 +1,11 @@ package com.sunquakes.jsonrpc4j.server; -import com.alibaba.fastjson2.JSONObject; +import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.dto.ResponseDto; import com.sunquakes.jsonrpc4j.utils.ByteArrayUtils; +import com.sunquakes.jsonrpc4j.utils.JSONUtils; +import lombok.AllArgsConstructor; +import lombok.Data; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; @@ -29,14 +32,16 @@ class JsonRpcTcpServerTest { @Test void testHandle() throws IOException { - JSONObject params = new JSONObject(); - params.put("a", 1); - params.put("b", 2); - JSONObject request = new JSONObject(); - request.put("id", "1234567890"); - request.put("jsonrpc", "2.0"); - request.put("method", "JsonRpc/add"); - request.put("params", params); + + @Data + @AllArgsConstructor + class Params { + int a; + int b; + } + Params params = new Params(1, 2); + RequestDto requestDto = new RequestDto("1234567890", "2.0", "JsonRpc/add", params); + String request = JSONUtils.toString(requestDto); Socket s = new Socket("localhost", 3201); try { @@ -69,10 +74,10 @@ void testHandle() throws IOException { } } String sb = new String(bytes); - ResponseDto responseDto = JSONObject.parseObject(sb, ResponseDto.class); + ResponseDto responseDto = JSONUtils.parseJavaObject(sb, ResponseDto.class); assertEquals(3, responseDto.getResult()); - responseDto = JSONObject.parseObject(sb.toString(), ResponseDto.class); + responseDto = JSONUtils.toJavaObject(ResponseDto.class, sb.toString()); assertEquals(3, responseDto.getResult()); } catch (IOException e) { e.printStackTrace(); diff --git a/src/test/java/com/sunquakes/jsonrpc4j/utils/JSONUtilsTest.java b/src/test/java/com/sunquakes/jsonrpc4j/utils/JSONUtilsTest.java new file mode 100644 index 0000000..ee4a837 --- /dev/null +++ b/src/test/java/com/sunquakes/jsonrpc4j/utils/JSONUtilsTest.java @@ -0,0 +1,95 @@ +package com.sunquakes.jsonrpc4j.utils; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.junit.jupiter.api.Test; +import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JSONUtilsTest { + + @Data + @AllArgsConstructor + class TestObject { + private String name; + } + + @Test + void testToString() { + assertEquals("{\"name\":\"sunquakes\"}", JSONUtils.toString(new TestObject("sunquakes"))); + } + + @Test + void testToJavaObject() { + TestObject testObject = JSONUtils.toJavaObject(TestObject.class, "{\"name\":\"sunquakes\"}"); + assertEquals("sunquakes", testObject.name); + } + + @Test + void testToBytes() { + byte[] bytes = JSONUtils.toBytes(new TestObject("sunquakes")); + assertEquals(20, bytes.length); + } + + @Test + void testParseJavaObject() { + TestObject testObject = JSONUtils.parseJavaObject("{\"name\":\"sunquakes\"}", TestObject.class); + assertEquals("sunquakes", testObject.name); + } + + @Test + void testParseJSONObject() { + Object object = JSONUtils.parseJSONObject("{\"name\":\"sunquakes\"}"); + assertEquals("sunquakes", JSONUtils.get(object, "name")); + } + + @Test + void testParseList() { + List testObjectList = JSONUtils.parseList("[{\"name\":\"sunquakes\"}]", TestObject.class); + assertEquals("sunquakes", testObjectList.get(0).name); + } + + @Test + void testParse() { + Object object = JSONUtils.parse("{\"name\":\"sunquakes\"}"); + assertEquals("sunquakes", JSONUtils.get(object, "name")); + } + + @Test + void testIsArray() { + assertEquals(true, JSONUtils.isArray(JSONUtils.parse("[]"))); + } + + @Test + void testIsObject() { + assertEquals(true, JSONUtils.isObject(JSONUtils.parse("{}"))); + } + + @Test + void testToList() { + List objects = JSONUtils.toList(JSONUtils.parse("[{\"name\":\"sunquakes\"}]"), (index, object) -> object); + assertEquals("{\"name\":\"sunquakes\"}", objects.get(0).toString()); + } + + @Test + void testContainsKey() { + assertEquals(true, JSONUtils.containsKey(JSONUtils.parse("{\"name\":\"sunquakes\"}"), "name")); + } + + @Test + void testToArray() { + Object[] objects = JSONUtils.toArray(JSONUtils.parse("[\"sunquakes\"]"), 1, (index, object) -> object); + assertEquals("sunquakes", objects[0]); + } + + @Test + void testGet() { + assertEquals("sunquakes", JSONUtils.get(JSONUtils.parse("{\"name\":\"sunquakes\"}"), "name")); + } + + @Test + void testToArray2() { + Object[] objects = JSONUtils.toArray(JSONUtils.parse("[\"sunquakes\"]")); + assertEquals("sunquakes", objects[0]); + } +} From 89602bdec4605e332087a66a35d79525c309c7b8 Mon Sep 17 00:00:00 2001 From: Shing Rui Date: Sat, 19 Oct 2024 10:01:36 +0800 Subject: [PATCH 2/3] Ignore consul request bean sonarlint check. --- .../sunquakes/jsonrpc4j/discovery/Consul.java | 74 ++++++++----------- 1 file changed, 29 insertions(+), 45 deletions(-) diff --git a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java index a6c797f..4a18ff1 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java @@ -1,6 +1,5 @@ package com.sunquakes.jsonrpc4j.discovery; -import com.alibaba.fastjson2.annotation.JSONField; import com.sunquakes.jsonrpc4j.JsonRpcProtocol; import com.sunquakes.jsonrpc4j.utils.AddressUtils; import com.sunquakes.jsonrpc4j.utils.JSONUtils; @@ -86,9 +85,9 @@ private void checkRegister(String protocol, String hostname, int port, String na Check serviceCheck = new Check(); serviceCheck.setName(name); if (protocol.equals(JsonRpcProtocol.TCP.name())) { - serviceCheck.setTcp(AddressUtils.getUrl(hostname, port)); + serviceCheck.setTCP(AddressUtils.getUrl(hostname, port)); } else { - serviceCheck.setHttp(String.format("%s://%s:%d", protocol, hostname, port)); + serviceCheck.setHTTP(String.format("%s://%s:%d", protocol, hostname, port)); } serviceCheck.setInterval(checkInterval); // Set the init status passing @@ -156,81 +155,66 @@ private NettyHttpClient getClient() { @Data @AllArgsConstructor @NoArgsConstructor - public class HealthService { + @SuppressWarnings({"java:S116"}) + static public class HealthService { - @JSONField(name = "AggregatedStatus") - private String aggregatedStatus; + private String AggregatedStatus; - @JSONField(name = "Service") - private NewService service; + private NewService Service; } @Data @AllArgsConstructor @NoArgsConstructor - public class NewService { + @SuppressWarnings({"java:S116"}) + static public class NewService { - @JSONField(name = "ID") - private String id; + private String ID; - @JSONField(name = "Service") - private String service; + private String Service; - @JSONField(name = "Port") - private Integer port; + private Integer Port; - @JSONField(name = "Address") - private String address; + private String Address; } @Data @AllArgsConstructor @NoArgsConstructor - public class RegisterService { + @SuppressWarnings({"java:S116"}) + static public class RegisterService { - @JSONField(name = "ID") - private String id; + private String ID; - @JSONField(name = "Name") - private String name; + private String Name; - @JSONField(name = "Port") - private Integer port; + private Integer Port; - @JSONField(name = "Address") - private String address; + private String Address; } @Data @AllArgsConstructor @NoArgsConstructor - public class Check { + @SuppressWarnings({"java:S116"}) + static public class Check { - @JSONField(name = "ID") - private String id; + private String ID; - @JSONField(name = "Name") - private String name; + private String Name; - @JSONField(name = "Status") - private String status; + private String Status; - @JSONField(name = "ServiceID") - private String serviceID; + private String ServiceID; - @JSONField(name = "HTTP") - private String http; + private String HTTP; - @JSONField(name = "Method") - private String method; + private String Method; - @JSONField(name = "TCP") - private String tcp; + private String TCP; - @JSONField(name = "Interval") - private String interval; + private String Interval; - @JSONField(name = "Timeout") - private String timeout; + private String Timeout; } } From c95671cea10a0ec48276ea70fe3fe7946ca6ebb9 Mon Sep 17 00:00:00 2001 From: Shing Rui Date: Sat, 19 Oct 2024 13:24:05 +0800 Subject: [PATCH 3/3] Replace apache httpclient with NettyHttpClient in test cases. --- .../NettyHttpClient.java | 8 ++-- .../sunquakes/jsonrpc4j/discovery/Consul.java | 1 + .../sunquakes/jsonrpc4j/discovery/Nacos.java | 5 ++- .../client/JsonRpcHttpsClientTest.java | 41 +++++++------------ .../discovery/NettyHttpClientTest.java | 1 + .../server/JsonRpcHttpServerTest.java | 39 ++++++++---------- 6 files changed, 41 insertions(+), 54 deletions(-) rename src/main/java/com/sunquakes/jsonrpc4j/{discovery => client}/NettyHttpClient.java (95%) diff --git a/src/main/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClient.java b/src/main/java/com/sunquakes/jsonrpc4j/client/NettyHttpClient.java similarity index 95% rename from src/main/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClient.java rename to src/main/java/com/sunquakes/jsonrpc4j/client/NettyHttpClient.java index da9bd74..7a45230 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClient.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/client/NettyHttpClient.java @@ -1,4 +1,4 @@ -package com.sunquakes.jsonrpc4j.discovery; +package com.sunquakes.jsonrpc4j.client; import com.sunquakes.jsonrpc4j.JsonRpcProtocol; import com.sunquakes.jsonrpc4j.utils.RequestUtils; @@ -30,9 +30,9 @@ public class NettyHttpClient { private static final int DEFAULT_HTTPS_PORT = 443; - private URI uri; + private final URI uri; - NettyHttpClient(String host) { + public NettyHttpClient(String host) { uri = URI.create(host); } @@ -107,7 +107,7 @@ protected void initChannel(Channel ch) throws Exception { } } - class HttpResponseHandler extends SimpleChannelInboundHandler { + static class HttpResponseHandler extends SimpleChannelInboundHandler { Promise promise; diff --git a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java index 4a18ff1..2d416fe 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Consul.java @@ -1,6 +1,7 @@ package com.sunquakes.jsonrpc4j.discovery; import com.sunquakes.jsonrpc4j.JsonRpcProtocol; +import com.sunquakes.jsonrpc4j.client.NettyHttpClient; import com.sunquakes.jsonrpc4j.utils.AddressUtils; import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.buffer.ByteBuf; diff --git a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java index ffa2cd7..24b9114 100644 --- a/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java +++ b/src/main/java/com/sunquakes/jsonrpc4j/discovery/Nacos.java @@ -1,5 +1,6 @@ package com.sunquakes.jsonrpc4j.discovery; +import com.sunquakes.jsonrpc4j.client.NettyHttpClient; import com.sunquakes.jsonrpc4j.exception.JsonRpcException; import com.sunquakes.jsonrpc4j.utils.JSONUtils; import io.netty.buffer.ByteBuf; @@ -43,7 +44,7 @@ public class Nacos implements Driver { private String ephemeral = "true"; - private List> heartbeatList = new ArrayList<>(); + private final List> heartbeatList = new ArrayList<>(); @Override public Nacos newClient(String url) { @@ -163,7 +164,7 @@ public class GetResp { @Data @AllArgsConstructor @NoArgsConstructor - public class Service { + public static class Service { private String ip; private Integer port; private String instanceId; diff --git a/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java b/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java index 252b63c..039248b 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/client/JsonRpcHttpsClientTest.java @@ -2,18 +2,11 @@ import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.utils.JSONUtils; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.util.CharsetUtil; import lombok.AllArgsConstructor; import lombok.Data; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustStrategy; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,12 +15,14 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import javax.annotation.Resource; -import java.io.*; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; +import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -52,7 +47,7 @@ public void beforeTest() throws UnsupportedEncodingException { } @Test - void testRequest() throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + void testRequest() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, ExecutionException, InterruptedException { @Data @AllArgsConstructor class Params { @@ -63,19 +58,11 @@ class Params { RequestDto requestDto = new RequestDto("1234567890", "2.0", "JsonRpc/add", params); String request = JSONUtils.toString(requestDto); - SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustStrategy() { - @Override - public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { - return true; - } - }); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); - HttpPost httpPost = new HttpPost("https://localhost:3205"); - httpPost.setEntity(new StringEntity(request, ContentType.APPLICATION_JSON)); - HttpResponse response = httpClient.execute(httpPost); - assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":3}", EntityUtils.toString(response.getEntity())); + NettyHttpClient httpClient = new NettyHttpClient("https://localhost:3205"); + FullHttpResponse res = httpClient.post("", request); + ByteBuf buf = res.content(); + String body = buf.toString(CharsetUtil.UTF_8); + assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":3}", body); } @Test diff --git a/src/test/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClientTest.java b/src/test/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClientTest.java index 28c8c2e..6bb44e3 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClientTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/discovery/NettyHttpClientTest.java @@ -1,5 +1,6 @@ package com.sunquakes.jsonrpc4j.discovery; +import com.sunquakes.jsonrpc4j.client.NettyHttpClient; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; diff --git a/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java b/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java index c052e02..93243a9 100644 --- a/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java +++ b/src/test/java/com/sunquakes/jsonrpc4j/server/JsonRpcHttpServerTest.java @@ -1,23 +1,20 @@ package com.sunquakes.jsonrpc4j.server; +import com.sunquakes.jsonrpc4j.client.NettyHttpClient; import com.sunquakes.jsonrpc4j.dto.RequestDto; import com.sunquakes.jsonrpc4j.utils.JSONUtils; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.util.CharsetUtil; import lombok.AllArgsConstructor; import lombok.Data; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -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 org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.io.IOException; +import java.util.concurrent.ExecutionException; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -28,34 +25,34 @@ class JsonRpcHttpServerTest { @Data @AllArgsConstructor - class Params { + static class Params { int a; int b; } @Test - void testHandle() throws IOException { + void testHandle() throws ExecutionException, InterruptedException { Params params = new Params(1, 2); RequestDto requestDto = new RequestDto("1234567890", "2.0", "JsonRpc/add", params); String request = JSONUtils.toString(requestDto); - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost("http://localhost:3200"); - httpPost.setEntity(new StringEntity(request, ContentType.APPLICATION_JSON)); - HttpResponse response = httpClient.execute(httpPost); - assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":3}", EntityUtils.toString(response.getEntity())); + NettyHttpClient httpClient = new NettyHttpClient("http://localhost:3200"); + FullHttpResponse res = httpClient.post("", request); + ByteBuf buf = res.content(); + String body = buf.toString(CharsetUtil.UTF_8); + assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":3}", body); } @Test - void testMethod() throws IOException { + void testMethod() throws ExecutionException, InterruptedException { Params params = new Params(3, 4); RequestDto requestDto = new RequestDto("1234567890", "2.0", "json_rpc/add", params); String request = JSONUtils.toString(requestDto); - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost("http://localhost:3200"); - httpPost.setEntity(new StringEntity(request.toString(), ContentType.APPLICATION_JSON)); - HttpResponse response = httpClient.execute(httpPost); - assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":7}", EntityUtils.toString(response.getEntity())); + NettyHttpClient httpClient = new NettyHttpClient("http://localhost:3200"); + FullHttpResponse res = httpClient.post("", request); + ByteBuf buf = res.content(); + String body = buf.toString(CharsetUtil.UTF_8); + assertEquals("{\"id\":\"1234567890\",\"jsonrpc\":\"2.0\",\"result\":7}", body); } }