From 092a08971fa4da6cf673e2fab52d2c4d7d048ca2 Mon Sep 17 00:00:00 2001 From: "mai.jh" Date: Mon, 13 Jul 2020 11:34:00 +0800 Subject: [PATCH] [ISSUE #3210] Enhanced nacos resttemplate response handler (#3212) * Enhanced nacos resttemplate response handler * Enhanced nacos resttemplate response handler * Add license * [#3212] Modify some class name and comment * [#3212] Modify some class name and comment * [#3212] Modify some class name and comment * [#3212] change the name of property * Fix code style issue --- .../nacos/api/exception/NacosException.java | 6 ++ .../common/constant/ResponseHandlerType.java | 32 ++++++++ .../nacos/common/http/HttpRestResult.java | 4 +- .../client/AbstractNacosRestTemplate.java | 76 +++++++++++++++++++ .../http/client/AbstractResponseHandler.java | 64 ++++++++++++++++ .../http/client/AsyncHttpClientRequest.java | 7 +- .../http/client/BeanResponseHandler.java | 41 ++++++++++ .../client/DefaultAsyncHttpClientRequest.java | 6 +- .../http/client/NacosAsyncRestTemplate.java | 9 ++- .../common/http/client/NacosRestTemplate.java | 8 +- .../common/http/client/ResponseHandler.java | 47 ++++++++++++ .../client/RestResultResponseHandler.java | 53 +++++++++++++ .../http/client/StringResponseHandler.java | 38 ++++++++++ .../common/http/handler/ResponseHandler.java | 64 ---------------- .../nacos/common/utils/JacksonUtils.java | 11 +++ .../test/common/NacosRestTemplate_ITCase.java | 8 +- 16 files changed, 393 insertions(+), 81 deletions(-) create mode 100644 common/src/main/java/com/alibaba/nacos/common/constant/ResponseHandlerType.java create mode 100644 common/src/main/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplate.java create mode 100644 common/src/main/java/com/alibaba/nacos/common/http/client/AbstractResponseHandler.java create mode 100644 common/src/main/java/com/alibaba/nacos/common/http/client/BeanResponseHandler.java create mode 100644 common/src/main/java/com/alibaba/nacos/common/http/client/ResponseHandler.java create mode 100644 common/src/main/java/com/alibaba/nacos/common/http/client/RestResultResponseHandler.java create mode 100644 common/src/main/java/com/alibaba/nacos/common/http/client/StringResponseHandler.java diff --git a/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java b/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java index be9b6af2c2e..28f0276efb5 100644 --- a/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java +++ b/api/src/main/java/com/alibaba/nacos/api/exception/NacosException.java @@ -154,4 +154,10 @@ public String toString() { public static final int OVER_THRESHOLD = 503; public static final int RESOURCE_NOT_FOUND = -404; + + /** + * http client error code, + * ome exceptions that occurred when the use the Nacos RestTemplate and Nacos AsyncRestTemplate. + */ + public static final int HTTP_CLIENT_ERROR_CODE = -500; } diff --git a/common/src/main/java/com/alibaba/nacos/common/constant/ResponseHandlerType.java b/common/src/main/java/com/alibaba/nacos/common/constant/ResponseHandlerType.java new file mode 100644 index 00000000000..e46a9b88164 --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/constant/ResponseHandlerType.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.constant; + +/** + * Response Handler Type. + * + * @author mai.jh + */ +public final class ResponseHandlerType { + + public static final String STRING_TYPE = "java.lang.String"; + + public static final String RESTRESULT_TYPE = "com.alibaba.nacos.common.model.RestResult"; + + public static final String DEFAULT_BEAN_TYPE = "default_bean_handler"; + +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/HttpRestResult.java b/common/src/main/java/com/alibaba/nacos/common/http/HttpRestResult.java index 6e2ec75a1b3..2cf88e114e7 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/HttpRestResult.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/HttpRestResult.java @@ -33,8 +33,8 @@ public class HttpRestResult extends RestResult { public HttpRestResult() { } - public HttpRestResult(Header header, int code, T data) { - super(code, data); + public HttpRestResult(Header header, int code, T data, String message) { + super(code, message, data); this.header = header; } diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplate.java b/common/src/main/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplate.java new file mode 100644 index 00000000000..5c91f874257 --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplate.java @@ -0,0 +1,76 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.http.client; + +import com.alibaba.nacos.common.constant.ResponseHandlerType; +import com.alibaba.nacos.common.utils.JacksonUtils; +import com.fasterxml.jackson.databind.JavaType; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +/** + * For NacosRestTemplate and NacosAsyncRestTemplate, provide initialization and register of response converter. + * + * @author mai.jh + */ +public abstract class AbstractNacosRestTemplate { + + private final Map responseHandlerMap = new HashMap(); + + public AbstractNacosRestTemplate() { + // init response handler + responseHandlerMap.put(ResponseHandlerType.STRING_TYPE, new StringResponseHandler()); + responseHandlerMap.put(ResponseHandlerType.RESTRESULT_TYPE, new RestResultResponseHandler()); + responseHandlerMap.put(ResponseHandlerType.DEFAULT_BEAN_TYPE, new BeanResponseHandler()); + } + + /** + * register customization Response Handler. + * + * @param responseHandler {@link ResponseHandler} + */ + public void registerResponseHandler(String responseHandlerType, ResponseHandler responseHandler) { + responseHandlerMap.put(responseHandlerType, responseHandler); + } + + /** + * Select a response handler by responseType. + * + * @param responseType responseType + * @return ResponseHandler + */ + protected ResponseHandler selectResponseHandler(Type responseType) { + ResponseHandler responseHandler = null; + if (responseType == null) { + responseHandler = responseHandlerMap.get(ResponseHandlerType.STRING_TYPE); + } + if (responseHandler == null) { + JavaType javaType = JacksonUtils.constructJavaType(responseType); + String name = javaType.getRawClass().getName(); + responseHandler = responseHandlerMap.get(name); + } + // When the corresponding type of response handler cannot be obtained, + // the default bean response handler is used + if (responseHandler == null) { + responseHandler = responseHandlerMap.get(ResponseHandlerType.DEFAULT_BEAN_TYPE); + } + responseHandler.setResponseType(responseType); + return responseHandler; + } +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/AbstractResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/client/AbstractResponseHandler.java new file mode 100644 index 00000000000..698ddb9150f --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/AbstractResponseHandler.java @@ -0,0 +1,64 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.http.client; + +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.utils.IoUtils; +import org.apache.http.HttpStatus; + +import java.lang.reflect.Type; + +/** + * Abstract response handler. + * + * @author mai.jh + */ +public abstract class AbstractResponseHandler implements ResponseHandler { + + private Type responseType; + + @Override + public final void setResponseType(Type responseType) { + this.responseType = responseType; + } + + @Override + public final HttpRestResult handle(HttpClientResponse response) throws Exception { + if (HttpStatus.SC_OK != response.getStatusCode()) { + return handleError(response); + } + return convertResult(response, this.responseType); + } + + private HttpRestResult handleError(HttpClientResponse response) throws Exception { + Header headers = response.getHeaders(); + String message = IoUtils.toString(response.getBody(), headers.getCharset()); + return new HttpRestResult(headers, response.getStatusCode(), null, message); + } + + /** + * Abstract convertResult method, Different types of converters for expansion. + * + * @param response http client response + * @param responseType responseType + * @return HttpRestResult + * @throws Exception ex + */ + public abstract HttpRestResult convertResult(HttpClientResponse response, Type responseType) throws Exception; + +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/AsyncHttpClientRequest.java b/common/src/main/java/com/alibaba/nacos/common/http/client/AsyncHttpClientRequest.java index 4355f56567c..3d2b4d93b3e 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/AsyncHttpClientRequest.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/AsyncHttpClientRequest.java @@ -20,7 +20,6 @@ import com.alibaba.nacos.common.model.RequestHttpEntity; import java.io.Closeable; -import java.lang.reflect.Type; import java.net.URI; /** @@ -37,10 +36,10 @@ public interface AsyncHttpClientRequest extends Closeable { * @param uri http url * @param httpMethod http request method * @param requestHttpEntity http request entity - * @param responseType http response type + * @param responseHandler http response handler * @param callback http response callback * @throws Exception ex */ - void execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity, final Type responseType, - final Callback callback) throws Exception; + void execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity, + final ResponseHandler responseHandler, final Callback callback) throws Exception; } diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/BeanResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/client/BeanResponseHandler.java new file mode 100644 index 00000000000..4a667e57d64 --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/BeanResponseHandler.java @@ -0,0 +1,41 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.http.client; + +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.utils.JacksonUtils; + +import java.io.InputStream; +import java.lang.reflect.Type; + +/** + * bean response handler, + * Mainly converter response type as bean type. + * + * @author mai.jh + */ +public class BeanResponseHandler extends AbstractResponseHandler { + + @Override + public HttpRestResult convertResult(HttpClientResponse response, Type responseType) throws Exception { + final Header headers = response.getHeaders(); + InputStream body = response.getBody(); + T extractBody = JacksonUtils.toObj(body, responseType); + return new HttpRestResult(headers, response.getStatusCode(), extractBody, null); + } +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/DefaultAsyncHttpClientRequest.java b/common/src/main/java/com/alibaba/nacos/common/http/client/DefaultAsyncHttpClientRequest.java index acae4c1efbe..7b5d2f5ed2b 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/DefaultAsyncHttpClientRequest.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/DefaultAsyncHttpClientRequest.java @@ -18,7 +18,6 @@ import com.alibaba.nacos.common.http.Callback; import com.alibaba.nacos.common.http.HttpRestResult; -import com.alibaba.nacos.common.http.handler.ResponseHandler; import com.alibaba.nacos.common.model.RequestHttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpRequestBase; @@ -26,7 +25,6 @@ import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import java.io.IOException; -import java.lang.reflect.Type; import java.net.URI; /** @@ -46,7 +44,7 @@ public DefaultAsyncHttpClientRequest(CloseableHttpAsyncClient asyncClient) { } @Override - public void execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity, final Type responseType, + public void execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity, final ResponseHandler responseHandler, final Callback callback) throws Exception { HttpRequestBase httpRequestBase = DefaultHttpClientRequest.build(uri, httpMethod, requestHttpEntity); asyncClient.execute(httpRequestBase, new FutureCallback() { @@ -54,7 +52,7 @@ public void execute(URI uri, String httpMethod, RequestHttpEntity requestHtt public void completed(HttpResponse result) { DefaultClientHttpResponse response = new DefaultClientHttpResponse(result); try { - HttpRestResult httpRestResult = ResponseHandler.responseEntityExtractor(response, responseType); + HttpRestResult httpRestResult = responseHandler.handle(response); callback.onReceive(httpRestResult); } catch (Exception e) { callback.onError(e); diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java index 38566fac08f..3c317f3ce85 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java @@ -37,13 +37,14 @@ * @see AsyncHttpClientRequest * @see HttpClientResponse */ -public class NacosAsyncRestTemplate { +public class NacosAsyncRestTemplate extends AbstractNacosRestTemplate { private static final Logger LOGGER = LoggerFactory.getLogger(NacosAsyncRestTemplate.class); private AsyncHttpClientRequest clientRequest; public NacosAsyncRestTemplate(AsyncHttpClientRequest clientRequest) { + super(); this.clientRequest = clientRequest; } @@ -330,13 +331,15 @@ public void postForm(String url, Header header, Map paramVal } - private void execute(String url, String httpMethod, RequestHttpEntity requestEntity, Type responseType, + @SuppressWarnings("unchecked") + private void execute(String url, String httpMethod, RequestHttpEntity requestEntity, Type type, Callback callback) throws Exception { URI uri = HttpUtils.buildUri(url, requestEntity.getQuery()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP " + httpMethod + " " + url); } - clientRequest.execute(uri, httpMethod, requestEntity, responseType, callback); + ResponseHandler responseHandler = super.selectResponseHandler(type); + clientRequest.execute(uri, httpMethod, requestEntity, responseHandler, callback); } /** diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java index 85b0ffc0758..b455050c6ac 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java @@ -18,7 +18,6 @@ import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.HttpUtils; -import com.alibaba.nacos.common.http.handler.ResponseHandler; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.MediaType; import com.alibaba.nacos.common.http.param.Query; @@ -38,13 +37,14 @@ * @see HttpClientRequest * @see HttpClientResponse */ -public class NacosRestTemplate { +public class NacosRestTemplate extends AbstractNacosRestTemplate { private static final Logger LOGGER = LoggerFactory.getLogger(NacosRestTemplate.class); private HttpClientRequest requestClient; public NacosRestTemplate(HttpClientRequest requestClient) { + super(); this.requestClient = requestClient; } @@ -319,16 +319,18 @@ public HttpRestResult exchangeForm(String url, Header header, Map HttpRestResult execute(String url, String httpMethod, RequestHttpEntity requestEntity, Type responseType) throws Exception { URI uri = HttpUtils.buildUri(url, requestEntity.getQuery()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP " + httpMethod + " " + url); } + ResponseHandler responseHandler = super.selectResponseHandler(responseType); HttpClientResponse response = null; try { response = requestClient.execute(uri, httpMethod, requestEntity); - return ResponseHandler.responseEntityExtractor(response, responseType); + return responseHandler.handle(response); } finally { if (response != null) { response.close(); diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/ResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/client/ResponseHandler.java new file mode 100644 index 00000000000..8508d1d8cd2 --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/ResponseHandler.java @@ -0,0 +1,47 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.http.client; + +import com.alibaba.nacos.common.http.HttpRestResult; + +import java.lang.reflect.Type; + +/** + * Response Handler abstract interface, + * the actual processing of the response conversion is done by a concrete implementation class. + * + * @author mai.jh + */ +public interface ResponseHandler { + + /** + * set response type. + * + * @param responseType responseType + */ + void setResponseType(Type responseType); + + /** + * handle response convert to HttpRestResult. + * + * @param response http response + * @return HttpRestResult {@link HttpRestResult} + * @throws Exception ex + */ + HttpRestResult handle(HttpClientResponse response) throws Exception; + +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/RestResultResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/client/RestResultResponseHandler.java new file mode 100644 index 00000000000..bb9da540bc1 --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/RestResultResponseHandler.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.http.client; + +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.utils.JacksonUtils; + +import java.io.InputStream; +import java.lang.reflect.Type; + +/** + * RestResult response handler, Mainly converter response type as {@link RestResult} type. + * + * @author mai.jh + */ +public class RestResultResponseHandler extends AbstractResponseHandler { + + @Override + @SuppressWarnings("unchecked") + public HttpRestResult convertResult(HttpClientResponse response, Type responseType) throws Exception { + final Header headers = response.getHeaders(); + InputStream body = response.getBody(); + T extractBody = JacksonUtils.toObj(body, responseType); + HttpRestResult httpRestResult = convert((RestResult) extractBody); + httpRestResult.setHeader(headers); + return httpRestResult; + } + + private static HttpRestResult convert(RestResult restResult) { + HttpRestResult httpRestResult = new HttpRestResult(); + httpRestResult.setCode(restResult.getCode()); + httpRestResult.setData(restResult.getData()); + httpRestResult.setMessage(restResult.getMessage()); + return httpRestResult; + } + +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/StringResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/client/StringResponseHandler.java new file mode 100644 index 00000000000..ba1020d5afc --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/StringResponseHandler.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.http.client; + +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.utils.IoUtils; + +import java.lang.reflect.Type; + +/** + * string response handler, Mainly converter response type as string type. + * + * @author mai.jh + */ +public class StringResponseHandler extends AbstractResponseHandler { + + @Override + public HttpRestResult convertResult(HttpClientResponse response, Type responseType) throws Exception { + final Header headers = response.getHeaders(); + String extractBody = IoUtils.toString(response.getBody(), headers.getCharset()); + return new HttpRestResult(headers, response.getStatusCode(), extractBody, null); + } +} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java index 57ad28c4ea4..2c9a7741949 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java @@ -16,18 +16,7 @@ package com.alibaba.nacos.common.http.handler; -import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException; -import com.alibaba.nacos.common.constant.HttpHeaderConsts; -import com.alibaba.nacos.common.http.HttpRestResult; -import com.alibaba.nacos.common.http.client.HttpClientResponse; -import com.alibaba.nacos.common.http.param.Header; -import com.alibaba.nacos.common.http.param.MediaType; -import com.alibaba.nacos.common.model.RestResult; -import com.alibaba.nacos.common.utils.IoUtils; import com.alibaba.nacos.common.utils.JacksonUtils; -import org.apache.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.InputStream; import java.lang.reflect.Type; @@ -39,8 +28,6 @@ */ public final class ResponseHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(ResponseHandler.class); - public static T convert(String s, Class cls) throws Exception { return JacksonUtils.toObj(s, cls); } @@ -52,55 +39,4 @@ public static T convert(String s, Type type) throws Exception { public static T convert(InputStream inputStream, Type type) throws Exception { return JacksonUtils.toObj(inputStream, type); } - - private static HttpRestResult convert(RestResult restResult) { - HttpRestResult httpRestResult = new HttpRestResult(); - httpRestResult.setCode(restResult.getCode()); - httpRestResult.setData(restResult.getData()); - httpRestResult.setMessage(restResult.getMessage()); - return httpRestResult; - } - - /** - * Extract response entity to {@link HttpRestResult}. - * - * @param response response - * @param type type - * @param general type - * @return {@link HttpRestResult} - * @throws Exception exception - */ - @SuppressWarnings({"unchecked", "rawtypes", "resource"}) - public static HttpRestResult responseEntityExtractor(HttpClientResponse response, Type type) - throws Exception { - Header headers = response.getHeaders(); - String contentType = headers.getValue(HttpHeaderConsts.CONTENT_TYPE); - InputStream body = response.getBody(); - T extractBody = null; - final boolean typeToStr = String.class.toString().equals(type.toString()); - if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON) && HttpStatus.SC_OK == response - .getStatusCode()) { - // When the type is string type and the response contentType is [application/json], - // then it should be serialized as string - if (typeToStr) { - extractBody = (T) IoUtils.toString(body, headers.getCharset()); - } else { - extractBody = convert(body, type); - } - } - if (extractBody == null) { - if (!typeToStr) { - LOGGER.error( - "if the response contentType is not [application/json]," + " only support to java.lang.String"); - throw new NacosDeserializationException(type); - } - extractBody = (T) IoUtils.toString(body, headers.getCharset()); - } - if (extractBody instanceof RestResult) { - HttpRestResult httpRestResult = convert((RestResult) extractBody); - httpRestResult.setHeader(headers); - return httpRestResult; - } - return new HttpRestResult(response.getHeaders(), response.getStatusCode(), extractBody); - } } diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/JacksonUtils.java b/common/src/main/java/com/alibaba/nacos/common/utils/JacksonUtils.java index 845241527df..31a3f15bc0e 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/JacksonUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/JacksonUtils.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; @@ -264,4 +265,14 @@ public static ArrayNode createEmptyArrayNode() { public static JsonNode transferToJsonNode(Object obj) { return mapper.valueToTree(obj); } + + /** + * construct java type -> Jackson Java Type. + * + * @param type java type + * @return JavaType {@link JavaType} + */ + public static JavaType constructJavaType(Type type) { + return mapper.constructType(type); + } } diff --git a/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java index 296220f3b3f..72475b8a3fc 100644 --- a/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java @@ -17,12 +17,18 @@ import com.alibaba.nacos.Nacos; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.client.config.http.ServerHttpAgent; import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.utils.JacksonUtils; +import com.alibaba.nacos.config.server.model.ConfigInfo4Beta; +import com.alibaba.nacos.config.server.utils.JSONUtils; +import com.alibaba.nacos.core.utils.GenericType; +import com.fasterxml.jackson.core.type.TypeReference; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; @@ -79,7 +85,7 @@ public void test_url_post_config() throws Exception { public void test_url_get_return_restResult() throws Exception{ String url = IP + CONFIG_PATH + "/configs"; Query query = Query.newInstance().addParam("beta", true).addParam("dataId","test-1").addParam("group", "DEFAULT_GROUP"); - HttpRestResult restResult = nacosRestTemplate.get(url, Header.newInstance(), query, RestResult.class); + HttpRestResult restResult = nacosRestTemplate.get(url, Header.newInstance(), query, new TypeReference>(){}.getType()); Assert.assertTrue(restResult.ok()); System.out.println(restResult.getData()); System.out.println(restResult.getHeader());