This is an automated email from the ASF dual-hosted git repository.
liubao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/servicecomb-java-chassis.git
The following commit(s) were added to refs/heads/master by this push:
new b635644fc [SCB-2783]remove load balance handler and use filter (#3671)
b635644fc is described below
commit b635644fc2da818543d3e70ab3403adf5af7c46c
Author: liubao68 <[email protected]>
AuthorDate: Mon Feb 27 12:59:13 2023 +0800
[SCB-2783]remove load balance handler and use filter (#3671)
---
.../common/rest/AbstractRestInvocation.java | 344 --------
.../common/rest/RestProducerInvocation.java | 71 --
.../common/rest/VertxRestInvocation.java | 43 -
.../rest/RestProducerInvocationCreatorTest.java | 10 +-
.../common/rest/TestAbstractRestInvocation.java | 917 ---------------------
.../common/rest/TestRestProducerInvocation.java | 186 -----
.../common/rest/VertxRestInvocationTest.java | 44 -
.../filter/inner/RestServerCodecFilterTest.java | 16 +-
.../java/org/apache/servicecomb/core/Handler.java | 25 -
.../org/apache/servicecomb/core/Invocation.java | 35 -
.../servicecomb/core/NonSwaggerInvocation.java | 12 +-
.../core/definition/MicroserviceMeta.java | 37 -
.../servicecomb/core/definition/OperationMeta.java | 9 -
.../servicecomb/core/handler/config/Config.java | 50 --
.../core/handler/config/HandlerConfig.java | 51 --
.../edge/core/AbstractEdgeDispatcher.java | 4 -
.../servicecomb/edge/core/EdgeInvocation.java | 127 ---
.../edge/core/EdgeInvocationCreator.java | 4 +-
.../edge/core/EdgeRestTransportClient.java | 3 +-
.../edge/core/TestURLMappedEdgeDispatcher.java | 3 -
.../loadbalance/TestLoadBalanceFilter2.java | 6 +-
.../transport/highway/HighwayServerInvoke.java | 220 -----
.../rest/client/http/TestRestClientInvocation.java | 78 +-
.../servlet/RestServletProducerInvocation.java | 50 --
.../servlet/TestRestServletProducerInvocation.java | 101 ---
.../transport/rest/vertx/VertxRestDispatcher.java | 23 +-
.../rest/vertx/TestVertxRestDispatcher.java | 71 --
27 files changed, 22 insertions(+), 2518 deletions(-)
diff --git
a/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/AbstractRestInvocation.java
b/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/AbstractRestInvocation.java
deleted file mode 100644
index b961bbb6c..000000000
---
a/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/AbstractRestInvocation.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.common.rest;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response.Status;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.servicecomb.common.rest.codec.produce.ProduceProcessor;
-import
org.apache.servicecomb.common.rest.codec.produce.ProduceProcessorManager;
-import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import
org.apache.servicecomb.common.rest.filter.HttpServerFilterBeforeSendResponseExecutor;
-import org.apache.servicecomb.common.rest.filter.inner.RestServerCodecFilter;
-import org.apache.servicecomb.common.rest.locator.OperationLocator;
-import org.apache.servicecomb.common.rest.locator.ServicePathManager;
-import org.apache.servicecomb.config.YAMLUtil;
-import org.apache.servicecomb.core.Const;
-import org.apache.servicecomb.core.Invocation;
-import org.apache.servicecomb.core.definition.MicroserviceMeta;
-import org.apache.servicecomb.core.definition.OperationMeta;
-import org.apache.servicecomb.foundation.common.utils.JsonUtils;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
-import org.apache.servicecomb.swagger.invocation.Response;
-import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.netflix.config.DynamicPropertyFactory;
-
-public abstract class AbstractRestInvocation {
- private static final Logger LOGGER =
LoggerFactory.getLogger(AbstractRestInvocation.class);
-
- public static final String UNKNOWN_OPERATION_ID = "UNKNOWN_OPERATION";
-
- private final Map<String, Object> headerContextMappers;
-
- private final Map<String, Object> queryContextMappers;
-
- protected long start;
-
- protected RestOperationMeta restOperationMeta;
-
- protected Invocation invocation;
-
- protected HttpServletRequestEx requestEx;
-
- protected HttpServletResponseEx responseEx;
-
- protected ProduceProcessor produceProcessor;
-
- protected List<HttpServerFilter> httpServerFilters = Collections.emptyList();
-
- public AbstractRestInvocation() {
- this.start = System.nanoTime();
-
- String headerContextMapper = DynamicPropertyFactory.getInstance()
- .getStringProperty(RestConst.HEADER_CONTEXT_MAPPER, null).get();
- String queryContextMapper = DynamicPropertyFactory.getInstance()
- .getStringProperty(RestConst.QUERY_CONTEXT_MAPPER, null).get();
-
- if (headerContextMapper != null) {
- headerContextMappers = YAMLUtil.yaml2Properties(headerContextMapper);
- } else {
- headerContextMappers = new HashMap<>();
- }
-
- if (queryContextMapper != null) {
- queryContextMappers = YAMLUtil.yaml2Properties(queryContextMapper);
- } else {
- queryContextMappers = new HashMap<>();
- }
- }
-
- public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) {
- this.httpServerFilters = httpServerFilters;
- }
-
- protected void findRestOperation(MicroserviceMeta microserviceMeta) {
- ServicePathManager servicePathManager =
ServicePathManager.getServicePathManager(microserviceMeta);
- if (servicePathManager == null) {
- LOGGER.error("No schema defined for {}:{}.",
microserviceMeta.getAppId(), microserviceMeta.getMicroserviceName());
- throw new InvocationException(Status.NOT_FOUND,
Status.NOT_FOUND.getReasonPhrase());
- }
-
- OperationLocator locator = locateOperation(servicePathManager);
- requestEx.setAttribute(RestConst.PATH_PARAMETERS, locator.getPathVarMap());
- this.restOperationMeta = locator.getOperation();
- }
-
- protected void initProduceProcessor() {
- produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx);
- if (produceProcessor == null) {
- LOGGER.error("Accept {} is not supported, operation={}.",
requestEx.getHeader(HttpHeaders.ACCEPT),
- restOperationMeta.getOperationMeta().getMicroserviceQualifiedName());
- String msg = String.format("Accept %s is not supported",
requestEx.getHeader(HttpHeaders.ACCEPT));
- throw new InvocationException(Status.NOT_ACCEPTABLE, msg);
- }
- }
-
- @VisibleForTesting
- public void setContext() throws Exception {
- String strCseContext = requestEx.getHeader(Const.CSE_CONTEXT);
- if (StringUtils.isEmpty(strCseContext)) {
- return;
- }
-
- @SuppressWarnings("unchecked")
- Map<String, String> cseContext =
- JsonUtils.readValue(strCseContext.getBytes(StandardCharsets.UTF_8),
Map.class);
- invocation.mergeContext(cseContext);
-
- addParameterContext();
- }
-
- protected void addParameterContext() {
- headerContextMappers.forEach((k, v) -> {
- if (v instanceof String && requestEx.getHeader(k) != null) {
- invocation.addContext((String) v, requestEx.getHeader(k));
- }
- });
- queryContextMappers.forEach((k, v) -> {
- if (v instanceof String && requestEx.getParameter(k) != null) {
- invocation.addContext((String) v, requestEx.getParameter(k));
- }
- });
- }
-
- public String getContext(String key) {
- if (null == invocation || null == invocation.getContext()) {
- return null;
- }
-
- return invocation.getContext(key);
- }
-
- protected void scheduleInvocation() {
- try {
- createInvocation();
- } catch (Throwable e) {
- sendFailResponse(e);
- return;
- }
-
- try {
- this.setContext();
- } catch (Exception e) {
- LOGGER.error("failed to set invocation context", e);
- sendFailResponse(e);
- return;
- }
-
- invocation.onStart(requestEx, start);
- invocation.getInvocationStageTrace().startSchedule();
- OperationMeta operationMeta = restOperationMeta.getOperationMeta();
-
- try {
- operationMeta.getExecutor().execute(() -> {
- synchronized (this.requestEx) {
- try {
- if (isInQueueTimeout()) {
- throw new InvocationException(Status.INTERNAL_SERVER_ERROR,
"Timeout when processing the request.");
- }
- if (requestEx.getAttribute(RestConst.REST_REQUEST) != requestEx) {
- // already timeout
- // in this time, request maybe recycled and reused by web
container, do not use requestEx
- LOGGER.error("Rest request already timeout, abandon execute,
method {}, operation {}.",
- operationMeta.getHttpMethod(),
- operationMeta.getMicroserviceQualifiedName());
- return;
- }
-
- runOnExecutor();
- } catch (InvocationException e) {
- LOGGER.error("Invocation failed, cause={}", e.getMessage());
- sendFailResponse(e);
- } catch (Throwable e) {
- LOGGER.error("Processing rest server request error", e);
- sendFailResponse(e);
- }
- }
- });
- } catch (Throwable e) {
- LOGGER.error("failed to schedule invocation, message={}, executor={}.",
e.getMessage(), e.getClass().getName());
- sendFailResponse(e);
- }
- }
-
- private boolean isInQueueTimeout() {
- return System.nanoTime() - invocation.getInvocationStageTrace().getStart()
>
-
invocation.getOperationMeta().getConfig().getNanoRestRequestWaitInPoolTimeout();
- }
-
- protected void runOnExecutor() {
- invocation.onExecuteStart();
-
- invoke();
- }
-
- protected abstract OperationLocator locateOperation(ServicePathManager
servicePathManager);
-
- // create a invocation without args setted
- protected abstract void createInvocation();
-
- public void invoke() {
- try {
- Response response = prepareInvoke();
- if (response != null) {
- sendResponseQuietly(response);
- return;
- }
-
- doInvoke();
- } catch (InvocationException e) {
- LOGGER.error("Invocation failed, cause={}", e.getMessage());
- sendFailResponse(e);
- } catch (Throwable e) {
- LOGGER.error("Processing rest server request error", e);
- sendFailResponse(e);
- }
- }
-
- protected Response prepareInvoke() throws Throwable {
- this.initProduceProcessor();
- invocation.getHandlerContext().put(RestConst.REST_REQUEST, requestEx);
-
- invocation.getInvocationStageTrace().startServerFiltersRequest();
- for (HttpServerFilter filter : httpServerFilters) {
- if (filter.enabled()) {
- Response response = filter.afterReceiveRequest(invocation, requestEx);
- if (response != null) {
- return response;
- }
- }
- }
-
- return null;
- }
-
- protected void doInvoke() throws Throwable {
- invocation.onStartHandlersRequest();
- invocation.next(this::sendResponseQuietly);
- }
-
- public void sendFailResponse(Throwable throwable) {
- if (produceProcessor == null) {
- produceProcessor =
ProduceProcessorManager.INSTANCE.findDefaultProcessor();
- }
-
- Response response = Response.createProducerFail(throwable);
- sendResponseQuietly(response);
- }
-
- protected void sendResponseQuietly(Response response) {
- if (invocation != null) {
- invocation.getInvocationStageTrace().finishHandlersResponse();
- }
- try {
- sendResponse(response);
- } catch (Throwable e) {
- LOGGER.error("Failed to send rest response, operation:{}, request
uri:{}",
- getMicroserviceQualifiedName(), requestEx.getRequestURI(), e);
- }
- }
-
- @SuppressWarnings("deprecation")
- protected void sendResponse(Response response) {
- RestServerCodecFilter.copyHeadersToHttpResponse(response.getHeaders(),
responseEx);
-
- responseEx.setStatus(response.getStatusCode(), response.getReasonPhrase());
- responseEx.setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE, response);
- responseEx.setAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR,
produceProcessor);
-
- executeHttpServerFilters(response);
- }
-
- protected void executeHttpServerFilters(Response response) {
- HttpServerFilterBeforeSendResponseExecutor exec =
- new HttpServerFilterBeforeSendResponseExecutor(httpServerFilters,
invocation, responseEx);
- CompletableFuture<Void> future = exec.run();
- future.whenComplete((v, e) -> {
- if (invocation != null) {
- invocation.getInvocationStageTrace().finishServerFiltersResponse();
- }
-
- onExecuteHttpServerFiltersFinish(response, e);
- });
- }
-
- protected void onExecuteHttpServerFiltersFinish(Response response, Throwable
e) {
- if (e != null) {
- LOGGER.error("Failed to execute HttpServerFilters, operation:{}, request
uri:{}",
- getMicroserviceQualifiedName(), requestEx.getRequestURI(), e);
- }
-
- try {
- responseEx.flushBuffer();
- } catch (Throwable flushException) {
- LOGGER.error("Failed to flush rest response, operation:{}, request
uri:{}",
- getMicroserviceQualifiedName(), requestEx.getRequestURI(),
flushException);
- }
-
- try {
- requestEx.getAsyncContext().complete();
- } catch (Throwable completeException) {
- LOGGER.error("Failed to complete async rest response, operation:{},
request uri:{}",
- getMicroserviceQualifiedName(), requestEx.getRequestURI(),
completeException);
- }
-
- // if failed to locate path, then will not create invocation
- // TODO: statistics this case
- if (invocation != null) {
- invocation.onFinish(response);
- }
- }
-
- private String getMicroserviceQualifiedName() {
- return null == invocation ? UNKNOWN_OPERATION_ID :
invocation.getMicroserviceQualifiedName();
- }
-}
diff --git
a/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/RestProducerInvocation.java
b/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/RestProducerInvocation.java
deleted file mode 100644
index 965cebf13..000000000
---
a/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/RestProducerInvocation.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.common.rest;
-
-import java.util.List;
-
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import org.apache.servicecomb.common.rest.locator.OperationLocator;
-import org.apache.servicecomb.common.rest.locator.ServicePathManager;
-import org.apache.servicecomb.core.SCBEngine;
-import org.apache.servicecomb.core.Transport;
-import org.apache.servicecomb.core.definition.MicroserviceMeta;
-import org.apache.servicecomb.core.invocation.InvocationFactory;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
-import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
-
-public class RestProducerInvocation extends AbstractRestInvocation {
-
- protected Transport transport;
-
- public void invoke(Transport transport, HttpServletRequestEx requestEx,
HttpServletResponseEx responseEx,
- List<HttpServerFilter> httpServerFilters) {
- this.transport = transport;
- this.requestEx = requestEx;
- this.responseEx = responseEx;
- this.httpServerFilters = httpServerFilters;
- requestEx.setAttribute(RestConst.REST_REQUEST, requestEx);
-
- try {
- findRestOperation();
- } catch (InvocationException e) {
- sendFailResponse(e);
- return;
- }
-
- scheduleInvocation();
- }
-
- protected void findRestOperation() {
- MicroserviceMeta selfMicroserviceMeta =
SCBEngine.getInstance().getProducerMicroserviceMeta();
- findRestOperation(selfMicroserviceMeta);
- }
-
- @Override
- protected OperationLocator locateOperation(ServicePathManager
servicePathManager) {
- return
servicePathManager.producerLocateOperation(requestEx.getRequestURI(),
requestEx.getMethod());
- }
-
- @Override
- protected void createInvocation() {
- this.invocation = InvocationFactory.forProvider(transport.getEndpoint(),
- restOperationMeta.getOperationMeta(),
- null);
- }
-}
diff --git
a/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/VertxRestInvocation.java
b/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/VertxRestInvocation.java
deleted file mode 100644
index a0c45a1a2..000000000
---
a/common/common-rest/src/main/java/org/apache/servicecomb/common/rest/VertxRestInvocation.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.common.rest;
-
-import
org.apache.servicecomb.foundation.vertx.http.VertxServerRequestToHttpServletRequest;
-
-import io.vertx.ext.web.RoutingContext;
-
-public class VertxRestInvocation extends RestProducerInvocation {
- @Override
- protected void createInvocation() {
- callParentCreateInvocation();
-
- RoutingContext routingContext = ((VertxServerRequestToHttpServletRequest)
this.requestEx).getContext();
- VertxHttpTransportContext transportContext = new
VertxHttpTransportContext(routingContext, requestEx, responseEx,
- produceProcessor);
-
- invocation.setTransportContext(transportContext);
- routingContext.put(RestConst.REST_INVOCATION_CONTEXT, this.invocation);
- }
-
- /**
- * easy to mock when do test
- */
- void callParentCreateInvocation() {
- super.createInvocation();
- }
-}
diff --git
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/RestProducerInvocationCreatorTest.java
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/RestProducerInvocationCreatorTest.java
index 12877bc4a..4d7d54430 100644
---
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/RestProducerInvocationCreatorTest.java
+++
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/RestProducerInvocationCreatorTest.java
@@ -43,9 +43,6 @@ import
org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
import org.apache.servicecomb.swagger.invocation.exception.CommonExceptionData;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
-
-import io.vertx.core.json.Json;
-import io.vertx.ext.web.RoutingContext;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -53,7 +50,8 @@ import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
-import java.util.ArrayList;
+import io.vertx.core.json.Json;
+import io.vertx.ext.web.RoutingContext;
public class RestProducerInvocationCreatorTest {
@@ -131,7 +129,6 @@ public class RestProducerInvocationCreatorTest {
Mockito.when(operationMeta.buildBaseProviderRuntimeType()).thenReturn(invocationRuntimeType);
Mockito.when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
Mockito.when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
- Mockito.when(microserviceMeta.getHandlerChain()).thenReturn(new
ArrayList<>());
InvocationException throwable = (InvocationException) catchThrowable(()
-> creator.createAsync().join());
CommonExceptionData data = (CommonExceptionData)
throwable.getErrorData();
@@ -152,7 +149,6 @@ public class RestProducerInvocationCreatorTest {
Mockito.when(operationMeta.buildBaseProviderRuntimeType()).thenReturn(invocationRuntimeType);
Mockito.when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
Mockito.when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
- Mockito.when(microserviceMeta.getHandlerChain()).thenReturn(new
ArrayList<>());
Mockito.doNothing().when(creator).initProduceProcessor();
Invocation invocation = creator.createAsync().join();
@@ -172,7 +168,6 @@ public class RestProducerInvocationCreatorTest {
Mockito.when(operationMeta.buildBaseProviderRuntimeType()).thenReturn(invocationRuntimeType);
Mockito.when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
Mockito.when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
- Mockito.when(microserviceMeta.getHandlerChain()).thenReturn(new
ArrayList<>());
Mockito.doNothing().when(creator).initProduceProcessor();
creator.createAsync().join();
@@ -191,7 +186,6 @@ public class RestProducerInvocationCreatorTest {
Mockito.when(operationMeta.buildBaseProviderRuntimeType()).thenReturn(invocationRuntimeType);
Mockito.when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
Mockito.when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
- Mockito.when(microserviceMeta.getHandlerChain()).thenReturn(new
ArrayList<>());
Mockito.doNothing().when(creator).initProduceProcessor();
Mockito.when(requestEx.getHeader(Const.CSE_CONTEXT)).thenReturn("{\"k\":\"v\"}");
diff --git
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestAbstractRestInvocation.java
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestAbstractRestInvocation.java
deleted file mode 100644
index 34e2f148a..000000000
---
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestAbstractRestInvocation.java
+++ /dev/null
@@ -1,917 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.common.rest;
-
-import static com.google.common.net.HttpHeaders.CONTENT_LENGTH;
-import static com.google.common.net.HttpHeaders.TRANSFER_ENCODING;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.Executor;
-import java.util.concurrent.RejectedExecutionException;
-
-import javax.servlet.AsyncContext;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response.Status;
-
-import
org.apache.servicecomb.common.rest.codec.produce.ProduceProcessorManager;
-import org.apache.servicecomb.common.rest.definition.RestMetaUtils;
-import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilterBaseForTest;
-import org.apache.servicecomb.common.rest.locator.OperationLocator;
-import org.apache.servicecomb.common.rest.locator.ServicePathManager;
-import org.apache.servicecomb.common.rest.locator.TestPathSchema;
-import org.apache.servicecomb.config.ConfigUtil;
-import org.apache.servicecomb.core.Const;
-import org.apache.servicecomb.core.Invocation;
-import org.apache.servicecomb.core.SCBEngine;
-import org.apache.servicecomb.core.bootstrap.SCBBootstrap;
-import org.apache.servicecomb.core.definition.MicroserviceMeta;
-import org.apache.servicecomb.core.definition.OperationMeta;
-import org.apache.servicecomb.core.event.InvocationFinishEvent;
-import org.apache.servicecomb.core.event.InvocationStartEvent;
-import org.apache.servicecomb.core.executor.ReactiveExecutor;
-import org.apache.servicecomb.core.provider.consumer.ReferenceConfig;
-import org.apache.servicecomb.foundation.common.Holder;
-import org.apache.servicecomb.foundation.common.event.EventManager;
-import org.apache.servicecomb.foundation.common.utils.JsonUtils;
-import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils;
-import org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils;
-import
org.apache.servicecomb.foundation.test.scaffolding.exception.RuntimeExceptionWithoutStackTrace;
-import org.apache.servicecomb.foundation.vertx.http.AbstractHttpServletRequest;
-import
org.apache.servicecomb.foundation.vertx.http.AbstractHttpServletResponse;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
-import
org.apache.servicecomb.foundation.vertx.http.StandardHttpServletResponseEx;
-import org.apache.servicecomb.swagger.invocation.Response;
-import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
-import org.hamcrest.MatcherAssert;
-import org.hamcrest.Matchers;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.MockedStatic;
-import org.mockito.Mockito;
-
-import com.google.common.eventbus.Subscribe;
-
-import io.vertx.core.MultiMap;
-import io.vertx.core.buffer.Buffer;
-
-@SuppressWarnings("deprecation")
-public class TestAbstractRestInvocation {
-
- HttpServletRequestEx requestEx = Mockito.mock(HttpServletRequestEx.class);
-
- final HttpServletResponse servletResponse =
Mockito.mock(HttpServletResponse.class);
-
- HttpServletResponseEx responseEx;
-
- final ReferenceConfig endpoint = Mockito.mock(ReferenceConfig.class);
-
- Map<String, Object> arguments = new HashMap<>();
-
- Invocation invocation;
-
- static SCBEngine scbEngine;
-
- static OperationMeta operationMeta;
-
- static RestOperationMeta restOperation;
-
- static class AbstractHttpServletRequestForTest extends
AbstractHttpServletRequest {
- @Override
- public String getHeader(String name) {
- return null;
- }
- }
-
- class AbstractRestInvocationForTest extends AbstractRestInvocation {
- @Override
- protected OperationLocator locateOperation(ServicePathManager
servicePathManager) {
- return null;
- }
-
- @Override
- protected void createInvocation() {
- this.invocation = TestAbstractRestInvocation.this.invocation;
- }
- }
-
- AbstractRestInvocation restInvocation = new AbstractRestInvocationForTest();
-
- @BeforeEach
- public void setup() {
- ConfigUtil.installDynamicConfig();
- scbEngine = SCBBootstrap.createSCBEngineForTest()
- .addProducerMeta("sid1", new TestPathSchema())
- .run();
- operationMeta =
scbEngine.getProducerMicroserviceMeta().operationMetas().get("test.sid1.dynamicId");
- restOperation = RestMetaUtils.getRestOperationMeta(operationMeta);
-
- if (responseEx == null) {
- responseEx = new StandardHttpServletResponseEx(servletResponse);
- }
- responseEx = Mockito.spy(responseEx);
- arguments = Mockito.spy(arguments);
- invocation = new Invocation(endpoint, operationMeta,
operationMeta.buildBaseConsumerRuntimeType(), arguments);
-
- initRestInvocation();
- List<HttpServerFilter> httpServerFilters =
SPIServiceUtils.getSortedService(HttpServerFilter.class);
- restInvocation.setHttpServerFilters(httpServerFilters);
- }
-
- @AfterEach
- public void teardown() {
- ArchaiusUtils.resetConfig();
- scbEngine.destroy();
- }
-
- private void initRestInvocation() {
- restInvocation.produceProcessor =
ProduceProcessorManager.INSTANCE.findDefaultJsonProcessor();
- restInvocation.requestEx = requestEx;
- restInvocation.responseEx = responseEx;
- restInvocation.invocation = invocation;
- restInvocation.restOperationMeta = restOperation;
- }
-
- @Test
- public void setHttpServerFilters() {
- List<HttpServerFilter> httpServerFilters = new ArrayList<>();
- httpServerFilters = Mockito.spy(httpServerFilters);
- restInvocation.setHttpServerFilters(httpServerFilters);
-
- Assertions.assertSame(httpServerFilters, restInvocation.httpServerFilters);
- }
-
- @Test
- public void initProduceProcessorNull() {
-
Mockito.when(requestEx.getHeader(HttpHeaders.ACCEPT)).thenReturn("notExistType");
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- public void sendFailResponse(Throwable throwable) {
- }
- };
- initRestInvocation();
-
- InvocationException exception =
Assertions.assertThrows(InvocationException.class,
- () -> restInvocation.initProduceProcessor());
- Assertions.assertEquals(
- "InvocationException: code=406;msg=CommonExceptionData [message=Accept
notExistType is not supported]",
- exception.getMessage());
- }
-
- @Test
- public void initProduceProcessorNormal() {
-
Mockito.when(requestEx.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON);
- // not throw exception
- restInvocation.initProduceProcessor();
- }
-
- @Test
- public void setContextNull() throws Exception {
- Mockito.when(requestEx.getHeader(Const.CSE_CONTEXT)).thenReturn(null);
-
- Map<String, String> context = invocation.getContext();
- restInvocation.setContext();
- Assertions.assertSame(context, invocation.getContext());
- }
-
- @Test
- public void setContextEmpty() throws Exception {
- Mockito.when(requestEx.getHeader(Const.CSE_CONTEXT)).thenReturn("");
-
- Map<String, String> context = invocation.getContext();
- restInvocation.setContext();
- Assertions.assertSame(context, invocation.getContext());
- }
-
- @Test
- public void setContextNormal() throws Exception {
- Map<String, String> context = new HashMap<>();
- context.put("name", "value");
-
Mockito.when(requestEx.getHeader(Const.CSE_CONTEXT)).thenReturn(JsonUtils.writeValueAsString(context));
-
- restInvocation.setContext();
- MatcherAssert.assertThat(invocation.getContext().size(), Matchers.is(1));
- MatcherAssert.assertThat(invocation.getContext(),
Matchers.hasEntry("name", "value"));
- }
-
- @Test
- public void setContextTraceId() throws Exception {
- Map<String, String> context = new HashMap<>();
-
Mockito.when(requestEx.getHeader(Const.CSE_CONTEXT)).thenReturn(JsonUtils.writeValueAsString(context));
- invocation.addContext("X-B3-traceId", "value1");
- //if request has no traceId, use invocation's traceId
- restInvocation.setContext();
- MatcherAssert.assertThat(invocation.getContext().size(), Matchers.is(1));
- MatcherAssert.assertThat(invocation.getContext(),
Matchers.hasEntry("X-B3-traceId", "value1"));
-
- context.put("X-B3-traceId", "value2");
-
Mockito.when(requestEx.getHeader(Const.CSE_CONTEXT)).thenReturn(JsonUtils.writeValueAsString(context));
- //if request has traceId, use request's traceId
- restInvocation.setContext();
- MatcherAssert.assertThat(invocation.getContext().size(), Matchers.is(1));
- MatcherAssert.assertThat(invocation.getContext(),
Matchers.hasEntry("X-B3-traceId", "value2"));
- }
-
- @Test
- public void getContext() {
- invocation.addContext("key", "test");
- Assertions.assertEquals("test", restInvocation.getContext("key"));
- }
-
- @Test
- public void getContextNull() {
- Assertions.assertNull(restInvocation.getContext("key"));
- }
-
- @Test
- public void invokeFilterHaveResponse() {
- HttpServerFilter filter = Mockito.mock(HttpServerFilter.class);
- Response response = Response.ok("");
- Mockito.when(filter.enabled()).thenReturn(true);
- Mockito.when(filter.afterReceiveRequest(invocation,
requestEx)).thenReturn(response);
-
- Holder<Response> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- result.value = Response.ok("not run to here");
- }
-
- @Override
- protected void sendResponseQuietly(Response response) {
- result.value = response;
- }
- };
- initRestInvocation();
- restInvocation.httpServerFilters = Arrays.asList(filter);
-
- restInvocation.invoke();
-
- Assertions.assertSame(response, result.value);
- }
-
- @Test
- public void invokeFilterNoResponse() {
- HttpServerFilter filter = Mockito.mock(HttpServerFilter.class);
- Mockito.when(filter.enabled()).thenReturn(true);
- Mockito.when(filter.afterReceiveRequest(invocation,
requestEx)).thenReturn(null);
-
- Holder<Boolean> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- result.value = true;
- }
- };
- initRestInvocation();
- restInvocation.httpServerFilters = Arrays.asList(filter);
-
- restInvocation.invoke();
-
- Assertions.assertTrue(result.value);
- }
-
- @Test
- public void invokeFilterNoResponseDisableFilter() {
- HttpServerFilter filter = Mockito.mock(HttpServerFilter.class);
- Mockito.when(filter.enabled()).thenReturn(false);
-
- Holder<Boolean> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- result.value = true;
- }
- };
- initRestInvocation();
- restInvocation.httpServerFilters = Arrays.asList(filter);
-
- restInvocation.invoke();
-
- Assertions.assertTrue(result.value);
- }
-
- @Test
- public void invokeFilterException() {
- HttpServerFilter filter = Mockito.mock(HttpServerFilter.class);
- Exception error = new RuntimeExceptionWithoutStackTrace();
- Mockito.when(filter.enabled()).thenReturn(true);
- Mockito.when(filter.afterReceiveRequest(invocation,
requestEx)).thenThrow(error);
-
- Holder<Throwable> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- public void sendFailResponse(Throwable throwable) {
- result.value = throwable;
- }
-
- @Override
- protected void doInvoke() {
-
- }
- };
- initRestInvocation();
- restInvocation.httpServerFilters = Arrays.asList(filter);
-
- restInvocation.invoke();
-
- Assertions.assertSame(error, result.value);
- }
-
- @Test
- public void invokeNormal() {
- HttpServerFilter filter = Mockito.mock(HttpServerFilter.class);
- Mockito.when(filter.enabled()).thenReturn(true);
- Mockito.when(filter.afterReceiveRequest(invocation,
requestEx)).thenReturn(null);
-
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- }
-
- @Override
- public void sendFailResponse(Throwable throwable) {
- Assertions.fail("must not fail");
- }
- };
- initRestInvocation();
- restInvocation.httpServerFilters = Arrays.asList(filter);
-
- restInvocation.invoke();
- }
-
- @Test
- public void sendFailResponseNoProduceProcessor() {
- invocation.onStart(0);
-
- restInvocation.produceProcessor = null;
- restInvocation.sendFailResponse(new RuntimeExceptionWithoutStackTrace());
-
-
Assertions.assertSame(ProduceProcessorManager.INSTANCE.findDefaultJsonProcessor(),
- restInvocation.produceProcessor);
- }
-
- @Test
- public void sendFailResponseHaveProduceProcessor() {
- Holder<Response> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- }
-
- @Override
- protected void sendResponseQuietly(Response response) {
- result.value = response;
- }
- };
- initRestInvocation();
- restInvocation.produceProcessor =
ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor();
-
- Throwable e = new InvocationException(Status.BAD_GATEWAY, "");
- restInvocation.sendFailResponse(e);
- Assertions.assertSame(e, result.value.getResult());
- Assertions.assertSame(
- ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(),
restInvocation.produceProcessor);
- }
-
- public static class SendResponseQuietlyNormalEventHandler {
- private final Holder<InvocationFinishEvent> eventHolder;
-
- public SendResponseQuietlyNormalEventHandler(Holder<InvocationFinishEvent>
eventHolder) {
- this.eventHolder = eventHolder;
- }
-
- @Subscribe
- public void onFinished(InvocationFinishEvent event) {
- eventHolder.value = event;
- }
- }
-
- @Test
- public void sendResponseQuietlyNormal() {
- Response response = Mockito.mock(Response.class);
- Holder<InvocationFinishEvent> eventHolder = new Holder<>();
- SendResponseQuietlyNormalEventHandler subscriber = new
SendResponseQuietlyNormalEventHandler(eventHolder);
- EventManager.register(subscriber);
-
- Holder<Response> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- }
-
- @Override
- protected void sendResponse(Response response) {
- result.value = response;
- super.sendResponse(response);
- }
- };
- invocation.onStart(0);
- initRestInvocation();
-
- restInvocation.sendResponseQuietly(response);
-
- EventManager.unregister(subscriber);
-
- Assertions.assertSame(invocation, eventHolder.value.getInvocation());
- Assertions.assertSame(response, result.value);
- }
-
- @Test
- public void sendResponseQuietlyException() {
- Response response = Mockito.mock(Response.class);
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- }
-
- @Override
- protected void sendResponse(Response response) {
- throw new RuntimeExceptionWithoutStackTrace();
- }
- };
- initRestInvocation();
-
- restInvocation.sendResponseQuietly(response);
-
- // just log, check nothing
- }
-
- @Test
- public void sendResponseQuietlyExceptionOnNullInvocation() {
- Response response = Mockito.mock(Response.class);
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void doInvoke() {
- }
-
- @Override
- protected void sendResponse(Response response) {
- throw new RuntimeExceptionWithoutStackTrace("");
- }
- };
- initRestInvocation();
- restInvocation.invocation = null;
-
- restInvocation.sendResponseQuietly(response);
-
- // just log, check nothing, and should not throw NPE
- }
-
- @Test
- public void executeHttpServerFiltersNullInvocation() {
- Response response = Mockito.mock(Response.class);
- Holder<Boolean> flag = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void onExecuteHttpServerFiltersFinish(Response response,
Throwable e) {
- super.onExecuteHttpServerFiltersFinish(response, e);
- flag.value = true;
- }
- };
- initRestInvocation();
- restInvocation.invocation = null;
-
- restInvocation.executeHttpServerFilters(response);
-
- Assertions.assertTrue(flag.value);
- }
-
- @SuppressWarnings("deprecation")
- @Test
- public void sendResponseStatusAndContentTypeAndHeader() {
- Response response = Mockito.mock(Response.class);
- Mockito.when(response.getStatusCode()).thenReturn(123);
- Mockito.when(response.getReasonPhrase()).thenReturn("reason");
- Mockito.when(response.getResult()).thenReturn("result");
-
- Map<String, Object> result = new HashMap<>();
- Map<String, Object> attributes = new HashMap<>();
- Mockito.doAnswer(invocationOnMock -> {
- attributes.put(RestConst.INVOCATION_HANDLER_RESPONSE, response);
- return null;
- }).when(responseEx).setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE,
response);
-
Mockito.when(responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE)).thenReturn(response);
- Mockito.doAnswer(invocationOnMock -> {
- result.put("statusCode", 123);
- result.put("reasonPhrase", "reason");
- return null;
- }).when(responseEx).setStatus(123, "reason");
- Mockito.doAnswer(invocationOnMock -> {
- result.put("contentType", "application/json; charset=utf-8");
- return null;
- }).when(responseEx).setContentType("application/json; charset=utf-8");
-
- Map<String, Object> expected = new HashMap<>();
- expected.put("statusCode", 123);
- expected.put("reasonPhrase", "reason");
- expected.put("contentType", "application/json; charset=utf-8");
-
- invocation.onStart(0);
- initRestInvocation();
-
- restInvocation.sendResponse(response);
- Assertions.assertEquals(expected, result);
- }
-
- @Test
- public void
should_ignore_content_length_and_transfer_encoding_when_copy_header_to_http_response()
{
- Response response = Mockito.mock(Response.class);
- MultiMap headers = MultiMap.caseInsensitiveMultiMap()
- .set(CONTENT_LENGTH, "10")
- .set(TRANSFER_ENCODING, "encoding");
-
- Mockito.when(response.getResult()).thenThrow(new
RuntimeExceptionWithoutStackTrace("stop"));
- Mockito.when(response.getHeaders()).thenReturn(headers);
-
- MultiMap resultHeaders = MultiMap.caseInsensitiveMultiMap();
-
- invocation.onStart(0);
- initRestInvocation();
-
- restInvocation.sendResponse(response);
- assertThat(headers).isEmpty();
- assertThat(resultHeaders).isEmpty();
- }
-
- @Test
- public void testDoSendResponseHeaderNormal() {
- Response response = Mockito.mock(Response.class);
- MultiMap headers = MultiMap.caseInsensitiveMultiMap();
- headers.add("h1", "h1v1");
- headers.add("h1", "h1v2");
- headers.add("h2", "h2v");
-
- Mockito.when(response.getResult()).thenThrow(new
RuntimeExceptionWithoutStackTrace("stop"));
- Mockito.when(response.getHeaders()).thenReturn(headers);
-
- MultiMap resultHeaders = MultiMap.caseInsensitiveMultiMap();
- Map<String, Object> attributes = new HashMap<>();
- Mockito.doAnswer(invocationOnMock -> {
- attributes.put(RestConst.INVOCATION_HANDLER_RESPONSE, response);
- return null;
- }).when(responseEx).setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE,
response);
-
Mockito.when(responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE)).thenReturn(response);
- Mockito.doAnswer(invocationOnMock -> {
- resultHeaders.add("h1", "h1v1");
- return null;
- }).when(responseEx).addHeader("h1", "h1v1");
- Mockito.doAnswer(invocationOnMock -> {
- resultHeaders.add("h1", "h1v2");
- return null;
- }).when(responseEx).addHeader("h1", "h1v2");
- Mockito.doAnswer(invocationOnMock -> {
- resultHeaders.add("h2", "h2v");
- return null;
- }).when(responseEx).addHeader("h2", "h2v");
-
- invocation.onStart(0);
- initRestInvocation();
-
- try {
- restInvocation.sendResponse(response);
- Assertions.fail("must throw exception");
- } catch (Error e) {
- Assertions.assertEquals(headers.toString(), resultHeaders.toString());
- }
- }
-
- @Test
- public void testDoSendResponseResultOK() {
- Response response = Mockito.mock(Response.class);
- Mockito.when(response.getResult()).thenReturn("ok");
-
- Buffer buffer = Buffer.buffer();
- Map<String, Object> attributes = new HashMap<>();
- Mockito.doAnswer(invocationOnMock -> {
- attributes.put(RestConst.INVOCATION_HANDLER_RESPONSE, response);
- return null;
- }).when(responseEx).setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE,
response);
-
Mockito.when(responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE)).thenReturn(response);
- Mockito.doAnswer(invocationOnMock -> {
- buffer.appendBytes("\"ok\"".getBytes(StandardCharsets.UTF_8));
- return null;
- }).when(responseEx).setBodyBuffer(Mockito.any());
-
- invocation.onStart(0);
- initRestInvocation();
-
- restInvocation.sendResponse(response);
- Assertions.assertEquals("\"ok\"", buffer.toString());
- }
-
- @Test
- public void testDoSendResponseResultOKFilter() {
- Response response = Mockito.mock(Response.class);
- MultiMap headers = MultiMap.caseInsensitiveMultiMap();
- headers.set("Content-Type", "application/json");
- Mockito.when(response.getHeaders()).thenReturn(headers);
- Mockito.when(response.getStatusCode()).thenReturn(123);
- Mockito.when(response.getReasonPhrase()).thenReturn("reason");
- Mockito.when(response.getResult()).thenReturn("ok");
-
- Buffer buffer = Buffer.buffer();
- Map<String, Object> attributes = new HashMap<>();
- Mockito.doAnswer(invocationOnMock -> {
- attributes.put(RestConst.INVOCATION_HANDLER_RESPONSE, response);
- return null;
- }).when(responseEx).setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE,
response);
-
Mockito.when(responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE)).thenReturn(response);
- Mockito.doAnswer(invocationOnMock -> {
- buffer.appendBytes("\"ok\"".getBytes(StandardCharsets.UTF_8));
- return null;
- }).when(responseEx).setBodyBuffer(Mockito.any());
-
- HttpServerFilter filter = new HttpServerFilterBaseForTest() {
- @Override
- public CompletableFuture<Void> beforeSendResponseAsync(Invocation
invocation, HttpServletResponseEx responseEx) {
- buffer.appendString("-filter");
- return CompletableFuture.completedFuture(null);
- }
- };
-
- invocation.onStart(0);
- initRestInvocation();
- List<HttpServerFilter> httpServerFilters =
SPIServiceUtils.loadSortedService(HttpServerFilter.class);
- httpServerFilters.add(filter);
- restInvocation.setHttpServerFilters(httpServerFilters);
-
- restInvocation.sendResponse(response);
- Assertions.assertEquals("\"ok\"-filter", buffer.toString());
- }
-
- @Test
- public void findRestOperationServicePathManagerNull() {
- MicroserviceMeta microserviceMeta = Mockito.mock(MicroserviceMeta.class);
-
- try (MockedStatic<ServicePathManager> mockedStatic =
Mockito.mockStatic(ServicePathManager.class)) {
- mockedStatic.when(() ->
ServicePathManager.getServicePathManager(microserviceMeta)).thenReturn(null);
- InvocationException exception =
Assertions.assertThrows(InvocationException.class,
- () -> restInvocation.findRestOperation(microserviceMeta));
- Assertions.assertEquals("InvocationException:
code=404;msg=CommonExceptionData [message=Not Found]",
- exception.getMessage());
- }
- }
-
- @Test
- public void findRestOperationNormal() {
- try (MockedStatic<ServicePathManager> mockedStatic =
Mockito.mockStatic(ServicePathManager.class)) {
- ServicePathManager servicePathManager =
Mockito.mock(ServicePathManager.class);
- MicroserviceMeta microserviceMeta = Mockito.mock(MicroserviceMeta.class);
- OperationLocator locator = Mockito.mock(OperationLocator.class);
-
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected OperationLocator locateOperation(ServicePathManager
servicePathManager) {
- return locator;
- }
- };
-
- requestEx = new AbstractHttpServletRequest() {
- };
- restInvocation.requestEx = requestEx;
- Map<String, String> pathVars = new HashMap<>();
- mockedStatic.when(() ->
ServicePathManager.getServicePathManager(microserviceMeta))
- .thenReturn(servicePathManager);
- Mockito.when(locator.getPathVarMap()).thenReturn(pathVars);
- Mockito.when(locator.getOperation()).thenReturn(restOperation);
-
- restInvocation.findRestOperation(microserviceMeta);
- Assertions.assertSame(restOperation, restInvocation.restOperationMeta);
- Assertions.assertSame(pathVars,
requestEx.getAttribute(RestConst.PATH_PARAMETERS));
- }
- }
-
- @Test
- public void scheduleInvocationException() {
- OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
- restOperation = Mockito.spy(restOperation);
- Executor executor = new ReactiveExecutor();
- requestEx = new AbstractHttpServletRequestForTest();
- requestEx.setAttribute(RestConst.REST_REQUEST, requestEx);
- Mockito.when(restOperation.getOperationMeta()).thenReturn(operationMeta);
- Mockito.when(operationMeta.getExecutor()).thenReturn(executor);
-
- Holder<Throwable> result = new Holder<>();
- RuntimeException error = new RuntimeExceptionWithoutStackTrace("run on
executor");
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void runOnExecutor() {
- throw error;
- }
-
- @Override
- public void sendFailResponse(Throwable throwable) {
- result.value = throwable;
-
- invocation.onFinish(Response.ok(null));
- }
- };
- restInvocation.requestEx = requestEx;
- restInvocation.restOperationMeta = restOperation;
-
- restInvocation.scheduleInvocation();
-
- Assertions.assertSame(error, result.value);
- }
-
- @Test
- public void scheduleInvocationTimeout() {
- OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
- restOperation = Mockito.spy(restOperation);
- Executor executor = Runnable::run;
-
- Mockito.when(restOperation.getOperationMeta()).thenReturn(operationMeta);
- Mockito.when(operationMeta.getExecutor()).thenReturn(executor);
-
Mockito.when(operationMeta.getMicroserviceQualifiedName()).thenReturn("sayHi");
-
- requestEx = new AbstractHttpServletRequestForTest();
-
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void runOnExecutor() {
- throw new RuntimeExceptionWithoutStackTrace("run on executor");
- }
- };
- restInvocation.requestEx = requestEx;
- restInvocation.restOperationMeta = restOperation;
-
- // will not throw exception
- restInvocation.scheduleInvocation();
-
- invocation.onFinish(Response.ok(null));
- }
-
- @Test
- public void threadPoolReject() {
- OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
- restOperation = Mockito.spy(restOperation);
- RejectedExecutionException rejectedExecutionException = new
RejectedExecutionException("reject");
- Executor executor = (task) -> {
- throw rejectedExecutionException;
- };
-
- Mockito.when(restOperation.getOperationMeta()).thenReturn(operationMeta);
- Mockito.when(operationMeta.getExecutor()).thenReturn(executor);
-
- Holder<Throwable> holder = new Holder<>();
- requestEx = new AbstractHttpServletRequestForTest();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- public void sendFailResponse(Throwable throwable) {
- holder.value = throwable;
-
- invocation.onFinish(Response.ok(null));
- }
- };
- restInvocation.requestEx = requestEx;
- restInvocation.restOperationMeta = restOperation;
-
- restInvocation.scheduleInvocation();
-
- Assertions.assertSame(rejectedExecutionException, holder.value);
- }
-
- public static class ScheduleInvocationEventHandler {
- private final Holder<InvocationStartEvent> eventHolder;
-
- public ScheduleInvocationEventHandler(Holder<InvocationStartEvent>
eventHolder) {
- this.eventHolder = eventHolder;
- }
-
- @Subscribe
- public void onFinished(InvocationStartEvent event) {
- eventHolder.value = event;
- }
- }
-
- @Test
- public void scheduleInvocationNormal() {
- Holder<InvocationStartEvent> eventHolder = new Holder<>();
- Object subscriber = new ScheduleInvocationEventHandler(eventHolder);
- EventManager.register(subscriber);
-
- Executor executor = new ReactiveExecutor();
- requestEx = new AbstractHttpServletRequestForTest();
- requestEx = Mockito.spy(requestEx);
- responseEx = Mockito.spy(responseEx);
- restOperation = Mockito.spy(restOperation);
- operationMeta = Mockito.spy(operationMeta);
- Mockito.when(restOperation.getOperationMeta()).thenReturn(operationMeta);
- Mockito.when(operationMeta.getExecutor()).thenReturn(executor);
- Mockito.when(requestEx.getHeader(Const.TRACE_ID_NAME)).thenReturn("tid");
-
Mockito.when(requestEx.getAttribute(RestConst.REST_REQUEST)).thenReturn(requestEx);
-
- Holder<Boolean> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- protected void runOnExecutor() {
- result.value = true;
-
- invocation.onFinish(Response.ok(null));
- }
- };
- restInvocation.requestEx = requestEx;
- restInvocation.restOperationMeta = restOperation;
-
- restInvocation.scheduleInvocation();
- EventManager.unregister(subscriber);
-
- Assertions.assertTrue(result.value);
- Assertions.assertSame(invocation, eventHolder.value.getInvocation());
- Assertions.assertEquals("tid", invocation.getTraceId());
- }
-
- @Test
- public void runOnExecutor() {
-
- Holder<Boolean> result = new Holder<>();
- restInvocation = new AbstractRestInvocationForTest() {
- @Override
- public void invoke() {
- result.value = true;
- }
- };
- restInvocation.createInvocation();
- restInvocation.requestEx = requestEx;
- restInvocation.restOperationMeta = restOperation;
-
- restInvocation.runOnExecutor();
-
- Assertions.assertTrue(result.value);
- Assertions.assertSame(invocation, restInvocation.invocation);
- }
-
- @Test
- public void scheduleInvocation_invocationContextDeserializeError() {
- AsyncContext asyncContext = Mockito.mock(AsyncContext.class);
- requestEx = new AbstractHttpServletRequest() {
- @Override
- public String getHeader(String name) {
- return "{\"x-cse-src-microservice\":'source\"}";
- }
-
- @Override
- public AsyncContext getAsyncContext() {
- return asyncContext;
- }
- };
- Holder<Integer> status = new Holder<>();
- Holder<String> reasonPhrase = new Holder<>();
- Holder<Integer> endCount = new Holder<>(0);
- responseEx = new AbstractHttpServletResponse() {
- @SuppressWarnings("deprecation")
- @Override
- public void setStatus(int sc, String sm) {
- status.value = sc;
- reasonPhrase.value = sm;
- }
-
- @Override
- public void flushBuffer() {
- endCount.value = endCount.value + 1;
- }
-
- @Override
- public void setContentType(String type) {
- Assertions.assertEquals("application/json; charset=utf-8", type);
- }
- };
- restInvocation.requestEx = requestEx;
- restInvocation.responseEx = responseEx;
-
- restInvocation.scheduleInvocation();
-
- Assertions.assertEquals(Integer.valueOf(590), status.value);
- Assertions.assertEquals("Unexpected producer error, please check logs for
details", reasonPhrase.value);
- Assertions.assertEquals(Integer.valueOf(1), endCount.value);
- }
-}
diff --git
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestProducerInvocation.java
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestProducerInvocation.java
deleted file mode 100644
index fee6a0e1f..000000000
---
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestProducerInvocation.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.common.rest;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.servicecomb.common.rest.definition.RestMetaUtils;
-import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import org.apache.servicecomb.common.rest.locator.OperationLocator;
-import org.apache.servicecomb.common.rest.locator.ServicePathManager;
-import org.apache.servicecomb.common.rest.locator.TestPathSchema;
-import org.apache.servicecomb.config.ConfigUtil;
-import org.apache.servicecomb.core.SCBEngine;
-import org.apache.servicecomb.core.Transport;
-import org.apache.servicecomb.core.bootstrap.SCBBootstrap;
-import org.apache.servicecomb.core.definition.MicroserviceMeta;
-import org.apache.servicecomb.core.definition.OperationMeta;
-import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils;
-import org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils;
-import org.apache.servicecomb.foundation.vertx.http.AbstractHttpServletRequest;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
-import org.apache.servicecomb.registry.api.registry.Microservice;
-import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.mockito.MockedStatic;
-import org.mockito.Mockito;
-
-public class TestRestProducerInvocation {
-
- final Transport transport = Mockito.mock(Transport.class);
-
- HttpServletRequestEx requestEx = Mockito.mock(HttpServletRequestEx.class);
-
- final HttpServletResponseEx responseEx =
Mockito.mock(HttpServletResponseEx.class);
-
- RestProducerInvocation restProducerInvocation;
-
- Throwable throwableOfSendFailResponse;
-
- boolean scheduleInvocation;
-
- static final List<HttpServerFilter> httpServerFilters =
SPIServiceUtils.getSortedService(HttpServerFilter.class);
-
- static SCBEngine scbEngine;
-
- static OperationMeta operationMeta;
-
- static RestOperationMeta restOperationMeta;
-
- static MicroserviceMeta microserviceMeta;
-
- @BeforeAll
- public static void classSetup() {
- ConfigUtil.installDynamicConfig();
- scbEngine = SCBBootstrap.createSCBEngineForTest()
- .addProducerMeta("sid1", new TestPathSchema())
- .run();
- operationMeta =
scbEngine.getProducerMicroserviceMeta().operationMetas().get("test.sid1.dynamicId");
- restOperationMeta = RestMetaUtils.getRestOperationMeta(operationMeta);
- microserviceMeta = operationMeta.getMicroserviceMeta();
- }
-
- @AfterAll
- public static void classTeardown() {
- scbEngine.destroy();
- ArchaiusUtils.resetConfig();
- }
-
- private void initRestProducerInvocation() {
- restProducerInvocation.transport = transport;
- restProducerInvocation.requestEx = requestEx;
- restProducerInvocation.responseEx = responseEx;
- restProducerInvocation.restOperationMeta = restOperationMeta;
- restProducerInvocation.httpServerFilters = httpServerFilters;
- }
-
- @Test
- public void invokeSendFail() {
- InvocationException expected = new
InvocationException(javax.ws.rs.core.Response.Status.BAD_REQUEST, "test");
- restProducerInvocation = Mockito.spy(new RestProducerInvocation());
- Mockito.doThrow(expected).when(restProducerInvocation).findRestOperation();
- Mockito.doAnswer(invocationOnMock -> {
- throwableOfSendFailResponse = expected;
- return null;
- }).when(restProducerInvocation).sendFailResponse(Mockito.any());
- Mockito.doThrow(new IllegalStateException("must not invoke
scheduleInvocation")).when(restProducerInvocation).scheduleInvocation();
-
-
- restProducerInvocation.invoke(transport, requestEx, responseEx,
httpServerFilters);
-
- Assertions.assertSame(expected, throwableOfSendFailResponse);
- }
-
- @Test
- public void invokeNormal() {
- restProducerInvocation = Mockito.spy(new RestProducerInvocation());
- Mockito.doAnswer(invocationOnMock -> {
- restProducerInvocation.restOperationMeta = restOperationMeta;
- return null;
- }).when(restProducerInvocation).findRestOperation();
- Mockito.doAnswer(invocationOnMock -> {
- scheduleInvocation = true;
- return null;
- }).when(restProducerInvocation).scheduleInvocation();
-
- requestEx = new AbstractHttpServletRequest() {
- };
- restProducerInvocation.invoke(transport, requestEx, responseEx,
httpServerFilters);
-
- Assertions.assertTrue(scheduleInvocation);
- Assertions.assertSame(requestEx,
requestEx.getAttribute(RestConst.REST_REQUEST));
- }
-
- @Test
- public void findRestOperationNameFromRegistry() {
- Microservice microservice = new Microservice();
- microservice.setServiceName("ms");
-
- try (MockedStatic<ServicePathManager> managerMockedStatic =
Mockito.mockStatic(ServicePathManager.class)){
- managerMockedStatic.when(() ->
ServicePathManager.getServicePathManager(microserviceMeta)).thenReturn(null);
- restProducerInvocation = new RestProducerInvocation();
- initRestProducerInvocation();
-
- Exception exception = Assertions.assertThrows(Exception.class,
- () -> restProducerInvocation.findRestOperation());
- Assertions.assertTrue(exception.getMessage().contains("[message=Not
Found]"));
- }
- }
-
- @Test
- public void findRestOperationNormal() {
- requestEx = new AbstractHttpServletRequest() {
- @Override
- public String getRequestURI() {
- return "/path";
- }
-
- @Override
- public String getMethod() {
- return "GET";
- }
-
- @Override
- public String getHeader(String name) {
- return "ms";
- }
- };
- Map<String, String> pathVars = new HashMap<>();
- try (MockedStatic<ServicePathManager> managerMockedStatic =
Mockito.mockStatic(ServicePathManager.class)){
- ServicePathManager servicePathManager =
Mockito.mock(ServicePathManager.class);
- OperationLocator locator = Mockito.mock(OperationLocator.class);
- managerMockedStatic.when(() ->
ServicePathManager.getServicePathManager(microserviceMeta)).thenReturn(servicePathManager);
- Mockito.when(servicePathManager.producerLocateOperation(Mockito.any(),
Mockito.any())).thenReturn(locator);
- Mockito.when(locator.getPathVarMap()).thenReturn(pathVars);
- Mockito.when(locator.getOperation()).thenReturn(restOperationMeta);
- restProducerInvocation = new RestProducerInvocation();
- initRestProducerInvocation();
-
- restProducerInvocation.findRestOperation();
- Assertions.assertSame(restOperationMeta,
restProducerInvocation.restOperationMeta);
- Assertions.assertSame(pathVars,
requestEx.getAttribute(RestConst.PATH_PARAMETERS));
- }
- }
-}
diff --git
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/VertxRestInvocationTest.java
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/VertxRestInvocationTest.java
deleted file mode 100644
index a004e746a..000000000
---
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/VertxRestInvocationTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.common.rest;
-
-import org.apache.servicecomb.core.Invocation;
-import
org.apache.servicecomb.foundation.vertx.http.VertxServerRequestToHttpServletRequest;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-
-import io.vertx.ext.web.RoutingContext;
-
-public class VertxRestInvocationTest {
- @Test
- public void testCreateInvocation() {
- VertxRestInvocation vertxRestInvocation = Mockito.spy(new
VertxRestInvocation());
- Mockito.doNothing().when(vertxRestInvocation).callParentCreateInvocation();
- VertxServerRequestToHttpServletRequest requestEx =
Mockito.mock(VertxServerRequestToHttpServletRequest.class);
- RoutingContext routingContext = Mockito.mock(RoutingContext.class);
- Invocation invocation = Mockito.mock(Invocation.class);
-
- vertxRestInvocation.requestEx = requestEx;
- vertxRestInvocation.invocation = invocation;
- Mockito.when(requestEx.getContext()).thenReturn(routingContext);
-
- vertxRestInvocation.createInvocation();
-
- Mockito.verify(routingContext,
Mockito.times(1)).put(RestConst.REST_INVOCATION_CONTEXT, invocation);
- }
-}
diff --git
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/filter/inner/RestServerCodecFilterTest.java
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/filter/inner/RestServerCodecFilterTest.java
index 2d74c468d..b4093a1ca 100644
---
a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/filter/inner/RestServerCodecFilterTest.java
+++
b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/filter/inner/RestServerCodecFilterTest.java
@@ -22,11 +22,11 @@ import static
com.google.common.net.HttpHeaders.TRANSFER_ENCODING;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static org.assertj.core.api.Assertions.assertThat;
-import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
-import com.fasterxml.jackson.databind.JavaType;
+import javax.servlet.http.Part;
+
import org.apache.servicecomb.common.rest.HttpTransportContext;
import org.apache.servicecomb.common.rest.RestConst;
import org.apache.servicecomb.common.rest.codec.produce.ProduceJsonProcessor;
@@ -47,18 +47,17 @@ import
org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils;
import
org.apache.servicecomb.foundation.test.scaffolding.exception.RuntimeExceptionWithoutStackTrace;
import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
import org.apache.servicecomb.swagger.invocation.Response;
-
-import com.fasterxml.jackson.databind.type.TypeFactory;
-
-import io.vertx.core.MultiMap;
-import io.vertx.core.json.Json;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-import javax.servlet.http.Part;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+import io.vertx.core.MultiMap;
+import io.vertx.core.json.Json;
public class RestServerCodecFilterTest {
final RestServerCodecFilter codecFilter = new RestServerCodecFilter();
@@ -110,7 +109,6 @@ public class RestServerCodecFilterTest {
public void setUp() {
Mockito.when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
Mockito.when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
- Mockito.when(microserviceMeta.getHandlerChain()).thenReturn(new
ArrayList<>());
Mockito.when(operationMeta.buildBaseProviderRuntimeType()).thenReturn(invocationRuntimeType);
Mockito.when(transportContext.getProduceProcessor()).thenReturn(Mockito.mock(ProduceJsonProcessor.class));
invocation = Mockito.spy(InvocationFactory.forProvider(endpoint,
operationMeta, null));
diff --git a/core/src/main/java/org/apache/servicecomb/core/Handler.java
b/core/src/main/java/org/apache/servicecomb/core/Handler.java
deleted file mode 100644
index d2df96f51..000000000
--- a/core/src/main/java/org/apache/servicecomb/core/Handler.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.core;
-
-import org.apache.servicecomb.swagger.invocation.AsyncResponse;
-
-// 每个微服务 + invocationType,都对应一个handler实例
-public interface Handler {
- void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception;
-}
diff --git a/core/src/main/java/org/apache/servicecomb/core/Invocation.java
b/core/src/main/java/org/apache/servicecomb/core/Invocation.java
index 5c678c069..1dd42e726 100644
--- a/core/src/main/java/org/apache/servicecomb/core/Invocation.java
+++ b/core/src/main/java/org/apache/servicecomb/core/Invocation.java
@@ -21,7 +21,6 @@ import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@@ -52,14 +51,12 @@ import
org.apache.servicecomb.foundation.common.event.EventManager;
import org.apache.servicecomb.foundation.common.utils.AsyncUtils;
import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
-import org.apache.servicecomb.swagger.invocation.AsyncResponse;
import org.apache.servicecomb.swagger.invocation.InvocationType;
import org.apache.servicecomb.swagger.invocation.Response;
import org.apache.servicecomb.swagger.invocation.SwaggerInvocation;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import com.fasterxml.jackson.databind.JavaType;
-import com.google.common.annotations.VisibleForTesting;
public class Invocation extends SwaggerInvocation {
private static final Collection<TraceIdGenerator> TRACE_ID_GENERATORS =
loadTraceIdGenerators();
@@ -87,11 +84,6 @@ public class Invocation extends SwaggerInvocation {
// 只用于handler之间传递数据,是本地数据
private final Map<String, Object> handlerContext = localContext;
- // handler链,是arrayList,可以高效地通过index访问
- private List<Handler> handlerList;
-
- private int handlerIndex;
-
// 应答的处理器
// 同步模式:避免应答在网络线程中处理解码等等业务级逻辑
private Executor responseExecutor;
@@ -144,8 +136,6 @@ public class Invocation extends SwaggerInvocation {
this.schemaMeta = operationMeta.getSchemaMeta();
this.operationMeta = operationMeta;
this.setSwaggerArguments(swaggerArguments);
- this.handlerList = getHandlerChain();
- handlerIndex = 0;
traceIdLogger = new TraceIdLogger(this);
}
@@ -164,15 +154,6 @@ public class Invocation extends SwaggerInvocation {
return endpoint.getTransport();
}
- public List<Handler> getHandlerChain() {
- return schemaMeta.getMicroserviceMeta().getHandlerChain();
- }
-
- @VisibleForTesting
- public void setHandlerList(List<Handler> handlerList) {
- this.handlerList = handlerList;
- }
-
public Executor getResponseExecutor() {
return responseExecutor;
}
@@ -272,21 +253,6 @@ public class Invocation extends SwaggerInvocation {
return handlerContext;
}
- public int getHandlerIndex() {
- return handlerIndex;
- }
-
- public void setHandlerIndex(int handlerIndex) {
- this.handlerIndex = handlerIndex;
- }
-
- public void next(AsyncResponse asyncResp) throws Exception {
- // 不必判断有效性,因为整个流程都是内部控制的
- int runIndex = handlerIndex;
- handlerIndex++;
- handlerList.get(runIndex).handle(this, asyncResp);
- }
-
public String getSchemaId() {
return schemaMeta.getSchemaId();
}
@@ -436,7 +402,6 @@ public class Invocation extends SwaggerInvocation {
// for retry, reset invocation and try it again
public void reset() {
finished = false;
- handlerIndex = 0;
}
public boolean isFinished() {
diff --git
a/core/src/main/java/org/apache/servicecomb/core/NonSwaggerInvocation.java
b/core/src/main/java/org/apache/servicecomb/core/NonSwaggerInvocation.java
index 4c94865c5..90f602741 100644
--- a/core/src/main/java/org/apache/servicecomb/core/NonSwaggerInvocation.java
+++ b/core/src/main/java/org/apache/servicecomb/core/NonSwaggerInvocation.java
@@ -17,8 +17,6 @@
package org.apache.servicecomb.core;
-import org.apache.servicecomb.swagger.invocation.AsyncResponse;
-
public class NonSwaggerInvocation extends Invocation {
private final String appId;
@@ -26,13 +24,10 @@ public class NonSwaggerInvocation extends Invocation {
private final String versionRule;
- private final Handler nextHandler;
-
- public NonSwaggerInvocation(String appId, String microserviceName, String
versionRule, Handler nextHandler) {
+ public NonSwaggerInvocation(String appId, String microserviceName, String
versionRule) {
this.appId = appId;
this.microserviceName = microserviceName;
this.versionRule = versionRule;
- this.nextHandler = nextHandler;
}
@Override
@@ -69,9 +64,4 @@ public class NonSwaggerInvocation extends Invocation {
public String getMicroserviceVersionRule() {
return versionRule;
}
-
- @Override
- public void next(AsyncResponse asyncResp) throws Exception {
- nextHandler.handle(this, asyncResp);
- }
}
diff --git
a/core/src/main/java/org/apache/servicecomb/core/definition/MicroserviceMeta.java
b/core/src/main/java/org/apache/servicecomb/core/definition/MicroserviceMeta.java
index c5d21a60b..f953b7393 100644
---
a/core/src/main/java/org/apache/servicecomb/core/definition/MicroserviceMeta.java
+++
b/core/src/main/java/org/apache/servicecomb/core/definition/MicroserviceMeta.java
@@ -23,7 +23,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.servicecomb.core.Handler;
import org.apache.servicecomb.core.SCBEngine;
import org.apache.servicecomb.core.filter.FilterNode;
import org.apache.servicecomb.foundation.common.VendorExtensions;
@@ -65,16 +64,8 @@ public class MicroserviceMeta {
private final boolean consumer;
- private List<Handler> handlerChain = Collections.singletonList((invocation,
ar) -> ar.success(null));
-
private FilterNode filterChain = FilterNode.EMPTY;
- // providerQpsFlowControlHandler is a temporary field, only for internal
usage
- private Handler providerQpsFlowControlHandler;
-
- // providerQpsFlowControlHandlerSearched is a temporary field, only for
internal usage
- private boolean providerQpsFlowControlHandlerSearched;
-
private final VendorExtensions vendorExtensions = new VendorExtensions();
public MicroserviceMeta(SCBEngine scbEngine, String microserviceName,
boolean consumer) {
@@ -192,14 +183,6 @@ public class MicroserviceMeta {
return vendorExtensions.get(key);
}
- public List<Handler> getHandlerChain() {
- return handlerChain;
- }
-
- public void setHandlerChain(List<Handler> handlerChain) {
- this.handlerChain = handlerChain;
- }
-
public FilterNode getFilterChain() {
return filterChain;
}
@@ -207,24 +190,4 @@ public class MicroserviceMeta {
public void setFilterChain(FilterNode filterChain) {
this.filterChain = filterChain;
}
-
- /**
- * Only for JavaChassis internal usage.
- */
- @Deprecated
- public Handler getProviderQpsFlowControlHandler() {
- if (providerQpsFlowControlHandlerSearched) {
- return providerQpsFlowControlHandler;
- }
-
- for (Handler handler : handlerChain) {
- // matching by class name is more or less better than importing an extra
maven dependency
- if
("org.apache.servicecomb.qps.ProviderQpsFlowControlHandler".equals(handler.getClass().getName()))
{
- providerQpsFlowControlHandler = handler;
- break;
- }
- }
- providerQpsFlowControlHandlerSearched = true;
- return providerQpsFlowControlHandler;
- }
}
diff --git
a/core/src/main/java/org/apache/servicecomb/core/definition/OperationMeta.java
b/core/src/main/java/org/apache/servicecomb/core/definition/OperationMeta.java
index 4453597bc..7f0eb06a3 100644
---
a/core/src/main/java/org/apache/servicecomb/core/definition/OperationMeta.java
+++
b/core/src/main/java/org/apache/servicecomb/core/definition/OperationMeta.java
@@ -19,7 +19,6 @@ package org.apache.servicecomb.core.definition;
import java.util.concurrent.Executor;
import org.apache.servicecomb.core.Const;
-import org.apache.servicecomb.core.Handler;
import org.apache.servicecomb.foundation.common.VendorExtensions;
import org.apache.servicecomb.swagger.engine.SwaggerProducerOperation;
import org.apache.servicecomb.swagger.generator.core.model.SwaggerOperation;
@@ -155,14 +154,6 @@ public class OperationMeta {
this.executor = executor;
}
- /**
- * Only for JavaChassis internal usage.
- */
- @Deprecated
- public Handler getProviderQpsFlowControlHandler() {
- return getMicroserviceMeta().getProviderQpsFlowControlHandler();
- }
-
public InvocationRuntimeType buildBaseProviderRuntimeType() {
SwaggerProducerOperation swaggerProducerOperation =
this.getSwaggerProducerOperation();
return new
InvocationRuntimeType(swaggerProducerOperation.getProducerClass(),
diff --git
a/core/src/main/java/org/apache/servicecomb/core/handler/config/Config.java
b/core/src/main/java/org/apache/servicecomb/core/handler/config/Config.java
deleted file mode 100644
index 862d864ad..000000000
--- a/core/src/main/java/org/apache/servicecomb/core/handler/config/Config.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.core.handler.config;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.servicecomb.core.Handler;
-
-import
com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
-import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
-import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
-
-@JacksonXmlRootElement
-public class Config {
- // key为handler id
- private final Map<String, Class<Handler>> handlerClassMap = new HashMap<>();
-
- public void mergeFrom(Config otherConfig) {
- handlerClassMap.putAll(otherConfig.handlerClassMap);
- }
-
- public Map<String, Class<Handler>> getHandlerClassMap() {
- return this.handlerClassMap;
- }
-
- @JacksonXmlProperty(localName = "handler")
- @JacksonXmlElementWrapper(useWrapping = false)
- public void setHandlerConfigList(List<HandlerConfig> handlerConfigList) {
- for (HandlerConfig handlerConfig : handlerConfigList) {
- handlerClassMap.put(handlerConfig.getHandlerId(),
handlerConfig.getClazz());
- }
- }
-}
diff --git
a/core/src/main/java/org/apache/servicecomb/core/handler/config/HandlerConfig.java
b/core/src/main/java/org/apache/servicecomb/core/handler/config/HandlerConfig.java
deleted file mode 100644
index cf00c7f3a..000000000
---
a/core/src/main/java/org/apache/servicecomb/core/handler/config/HandlerConfig.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.core.handler.config;
-
-import org.apache.servicecomb.core.Handler;
-
-import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
-
-public class HandlerConfig {
- private String handlerId;
-
- private Class<Handler> clazz;
-
- @JacksonXmlProperty(localName = "id", isAttribute = true)
- public String getHandlerId() {
- return handlerId;
- }
-
- public void setHandlerId(String handlerId) {
- this.handlerId = handlerId;
- }
-
- @JacksonXmlProperty(localName = "class", isAttribute = true)
- public Class<Handler> getClazz() {
- return clazz;
- }
-
- public void setClazz(Class<Handler> clazz) {
- this.clazz = clazz;
- }
-
- @SuppressWarnings("unchecked")
- public void setClazz(String clazz) throws ClassNotFoundException {
- this.clazz = (Class<Handler>) Class.forName(clazz);
- }
-}
diff --git
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/AbstractEdgeDispatcher.java
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/AbstractEdgeDispatcher.java
index 7cdc43ea0..689da102b 100644
---
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/AbstractEdgeDispatcher.java
+++
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/AbstractEdgeDispatcher.java
@@ -34,10 +34,6 @@ import io.vertx.ext.web.RoutingContext;
public abstract class AbstractEdgeDispatcher extends
AbstractVertxHttpDispatcher {
private static final Logger LOGGER =
LoggerFactory.getLogger(AbstractEdgeDispatcher.class);
- protected EdgeInvocation createEdgeInvocation() {
- return new EdgeInvocation();
- }
-
protected void onFailure(RoutingContext context) {
LOGGER.error("edge server failed.", context.failure());
HttpServerResponse response = context.response();
diff --git
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java
deleted file mode 100644
index fa0aabee2..000000000
---
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.edge.core;
-
-import java.util.List;
-import java.util.concurrent.CompletableFuture;
-
-import org.apache.servicecomb.common.rest.AbstractRestInvocation;
-import org.apache.servicecomb.common.rest.RestConst;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import org.apache.servicecomb.common.rest.locator.OperationLocator;
-import org.apache.servicecomb.common.rest.locator.ServicePathManager;
-import org.apache.servicecomb.core.SCBEngine;
-import org.apache.servicecomb.core.invocation.InvocationFactory;
-import
org.apache.servicecomb.core.provider.consumer.MicroserviceReferenceConfig;
-import org.apache.servicecomb.core.provider.consumer.ReactiveResponseExecutor;
-import org.apache.servicecomb.core.provider.consumer.ReferenceConfig;
-import org.apache.servicecomb.foundation.vertx.executor.VertxContextExecutor;
-import
org.apache.servicecomb.foundation.vertx.http.VertxServerRequestToHttpServletRequest;
-import
org.apache.servicecomb.foundation.vertx.http.VertxServerResponseToHttpServletResponse;
-
-import io.vertx.core.Vertx;
-import io.vertx.ext.web.RoutingContext;
-
-public class EdgeInvocation extends AbstractRestInvocation {
- public static final String EDGE_INVOCATION_CONTEXT = "edgeInvocationContext";
-
- protected String microserviceName;
-
- protected MicroserviceReferenceConfig microserviceReferenceConfig;
-
- protected String versionRule = null;
-
- protected RoutingContext routingContext;
-
- public void init(String microserviceName, RoutingContext context, String
path,
- List<HttpServerFilter> httpServerFilters) {
- this.microserviceName = microserviceName;
- this.requestEx = new VertxServerRequestToHttpServletRequest(context, path);
- this.responseEx = new
VertxServerResponseToHttpServletResponse(context.response());
- this.routingContext = context;
- this.httpServerFilters = httpServerFilters;
- requestEx.setAttribute(RestConst.REST_REQUEST, requestEx);
- }
-
- public void edgeInvoke() {
- findMicroserviceVersionMeta().whenCompleteAsync((r, e) -> {
- if (e != null) {
- sendFailResponse(e);
- } else {
- try {
- microserviceReferenceConfig = r;
-
findRestOperation(microserviceReferenceConfig.getLatestMicroserviceMeta());
- scheduleInvocation();
- } catch (Throwable error) {
- sendFailResponse(error);
- }
- }
- }, VertxContextExecutor.create(Vertx.currentContext()));
- }
-
- protected CompletableFuture<MicroserviceReferenceConfig>
findMicroserviceVersionMeta() {
- return SCBEngine.getInstance()
- .createMicroserviceReferenceConfigAsync(microserviceName,
chooseVersionRule());
- }
-
- public void setVersionRule(String versionRule) {
- this.versionRule = versionRule;
- }
-
- // another possible rule:
- // path is: /msName/version/.....
- // version in path is v1 or v2 and so on
- // map version to VersionRule:
- // v1->1.0.0-2.0.0
- // v2->2.0.0-3.0.0
- // that means if a(1.x.x) bigger then b(1.y.y), then a compatible to b
- // but a(2.x.x) not compatible to b
- protected String chooseVersionRule() {
- // this will use all instance of the microservice
- // and this required all new version compatible to old version
- return versionRule;
- }
-
- @Override
- protected OperationLocator locateOperation(ServicePathManager
servicePathManager) {
- return
servicePathManager.consumerLocateOperation(requestEx.getRequestURI(),
requestEx.getMethod());
- }
-
- @Override
- protected void createInvocation() {
- ReferenceConfig referenceConfig = microserviceReferenceConfig
- .createReferenceConfig(restOperationMeta.getOperationMeta());
-
- this.invocation = InvocationFactory.forConsumer(referenceConfig,
- restOperationMeta.getOperationMeta(),
- restOperationMeta.getOperationMeta().buildBaseConsumerRuntimeType(),
- null);
- this.invocation.setSync(false);
- this.invocation.setEdge(true);
- this.invocation.getHandlerContext().put(EDGE_INVOCATION_CONTEXT,
Vertx.currentContext());
- this.invocation.setResponseExecutor(new ReactiveResponseExecutor());
- this.routingContext.put(RestConst.REST_INVOCATION_CONTEXT, invocation);
- }
-
- @Override
- public void setContext() throws Exception {
- // do not read InvocationContext from HTTP header, for security reason
-
- addParameterContext();
- }
-}
diff --git
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocationCreator.java
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocationCreator.java
index 17d67a647..167077e2e 100644
---
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocationCreator.java
+++
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocationCreator.java
@@ -16,8 +16,6 @@
*/
package org.apache.servicecomb.edge.core;
-import static
org.apache.servicecomb.edge.core.EdgeInvocation.EDGE_INVOCATION_CONTEXT;
-
import java.util.concurrent.CompletableFuture;
import org.apache.servicecomb.common.rest.RestVertxProducerInvocationCreator;
@@ -35,6 +33,8 @@ import io.vertx.core.Vertx;
import io.vertx.ext.web.RoutingContext;
public class EdgeInvocationCreator extends RestVertxProducerInvocationCreator {
+ public static final String EDGE_INVOCATION_CONTEXT = "edgeInvocationContext";
+
protected final String microserviceName;
protected final String versionRule;
diff --git
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeRestTransportClient.java
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeRestTransportClient.java
index f8229e085..4ccd21c0c 100644
---
a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeRestTransportClient.java
+++
b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeRestTransportClient.java
@@ -29,7 +29,8 @@ import io.vertx.core.Context;
public class EdgeRestTransportClient extends RestTransportClient {
@Override
protected HttpClientWithContext findHttpClientPool(Invocation invocation) {
- Context invocationContext = (Context)
invocation.getHandlerContext().get(EdgeInvocation.EDGE_INVOCATION_CONTEXT);
+ Context invocationContext = (Context) invocation.getHandlerContext()
+ .get(EdgeInvocationCreator.EDGE_INVOCATION_CONTEXT);
URIEndpointObject endpoint = (URIEndpointObject)
invocation.getEndpoint().getAddress();
String clientName = endpoint.isHttp2Enabled() ?
diff --git
a/edge/edge-core/src/test/java/org/apache/servicecomb/edge/core/TestURLMappedEdgeDispatcher.java
b/edge/edge-core/src/test/java/org/apache/servicecomb/edge/core/TestURLMappedEdgeDispatcher.java
index 59ba388d0..db0064c2a 100644
---
a/edge/edge-core/src/test/java/org/apache/servicecomb/edge/core/TestURLMappedEdgeDispatcher.java
+++
b/edge/edge-core/src/test/java/org/apache/servicecomb/edge/core/TestURLMappedEdgeDispatcher.java
@@ -27,7 +27,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
public class TestURLMappedEdgeDispatcher {
@@ -49,8 +48,6 @@ public class TestURLMappedEdgeDispatcher {
Assertions.assertEquals(items.size(), 0);
RoutingContext context = Mockito.mock(RoutingContext.class);
- HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
- EdgeInvocation invocation = Mockito.mock(EdgeInvocation.class);
Mockito.when(context.get(RestBodyHandler.BYPASS_BODY_HANDLER)).thenReturn(Boolean.TRUE);
dispatcher.onRequest(context);
diff --git
a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter2.java
b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter2.java
index 5e6efc885..d8bc679af 100644
---
a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter2.java
+++
b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter2.java
@@ -350,8 +350,7 @@ public class TestLoadBalanceFilter2 {
@Test
public void testZoneAwareFilterUsingMockedInvocationWorks() throws Exception
{
- Invocation invocation = new NonSwaggerInvocation("testApp",
"testMicroserviceName", "0.0.0+",
- (inv, aysnc) -> aysnc.success("OK"));
+ Invocation invocation = new NonSwaggerInvocation("testApp",
"testMicroserviceName", "0.0.0+");
InstanceCacheManager instanceCacheManager =
Mockito.mock(InstanceCacheManager.class);
TransportManager transportManager = Mockito.mock(TransportManager.class);
@@ -445,8 +444,7 @@ public class TestLoadBalanceFilter2 {
public void testStatusFilterUsingMockedInvocationWorks() throws Exception {
ArchaiusUtils.setProperty("servicecomb.loadbalance.filter.status.enabled",
"false");
- Invocation invocation = new NonSwaggerInvocation("testApp",
"testMicroserviceName", "0.0.0+",
- (inv, aysnc) -> aysnc.success("OK"));
+ Invocation invocation = new NonSwaggerInvocation("testApp",
"testMicroserviceName", "0.0.0+");
InstanceCacheManager instanceCacheManager =
Mockito.mock(InstanceCacheManager.class);
TransportManager transportManager = Mockito.mock(TransportManager.class);
diff --git
a/transports/transport-highway/src/main/java/org/apache/servicecomb/transport/highway/HighwayServerInvoke.java
b/transports/transport-highway/src/main/java/org/apache/servicecomb/transport/highway/HighwayServerInvoke.java
deleted file mode 100644
index 2efaf76c4..000000000
---
a/transports/transport-highway/src/main/java/org/apache/servicecomb/transport/highway/HighwayServerInvoke.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.transport.highway;
-
-import java.util.Map;
-import java.util.concurrent.RejectedExecutionException;
-
-import javax.ws.rs.core.Response.Status;
-
-import org.apache.servicecomb.codec.protobuf.definition.OperationProtobuf;
-import org.apache.servicecomb.codec.protobuf.definition.ProtobufManager;
-import org.apache.servicecomb.codec.protobuf.definition.ResponseRootSerializer;
-import org.apache.servicecomb.core.Const;
-import org.apache.servicecomb.core.Endpoint;
-import org.apache.servicecomb.core.Handler;
-import org.apache.servicecomb.core.Invocation;
-import org.apache.servicecomb.core.SCBEngine;
-import org.apache.servicecomb.core.definition.MicroserviceMeta;
-import org.apache.servicecomb.core.definition.OperationMeta;
-import org.apache.servicecomb.core.definition.SchemaMeta;
-import org.apache.servicecomb.core.invocation.InvocationFactory;
-import org.apache.servicecomb.foundation.common.Holder;
-import org.apache.servicecomb.foundation.vertx.tcp.TcpConnection;
-import org.apache.servicecomb.swagger.invocation.Response;
-import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
-import org.apache.servicecomb.transport.highway.message.RequestHeader;
-import org.apache.servicecomb.transport.highway.message.ResponseHeader;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import io.vertx.core.buffer.Buffer;
-
-public class HighwayServerInvoke {
- private static final Logger LOGGER =
LoggerFactory.getLogger(HighwayServerInvoke.class);
-
- private RequestHeader header;
-
- private OperationMeta operationMeta;
-
- private TcpConnection connection;
-
- private long msgId;
-
- private Buffer bodyBuffer;
-
- private final Endpoint endpoint;
-
- private Invocation invocation;
-
- private OperationProtobuf operationProtobuf;
-
- private final long start;
-
- public HighwayServerInvoke(Endpoint endpoint) {
- this.start = System.nanoTime();
- this.endpoint = endpoint;
- }
-
- public boolean init(TcpConnection connection, long msgId, RequestHeader
header, Buffer bodyBuffer) {
- try {
- doInit(connection, msgId, header, bodyBuffer);
- return true;
- } catch (Throwable e) {
- String microserviceQualifiedName = "unknown";
- if (operationMeta != null) {
- microserviceQualifiedName =
operationMeta.getMicroserviceQualifiedName();
- }
- String msg = String.format("decode request error,
microserviceQualifiedName=%s, msgId=%d",
- microserviceQualifiedName,
- msgId);
- LOGGER.error(msg, e);
-
- return false;
- }
- }
-
- private void doInit(TcpConnection connection, long msgId, RequestHeader
header, Buffer bodyBuffer) throws Exception {
- this.connection = connection;
- this.msgId = msgId;
- this.header = header;
-
- MicroserviceMeta microserviceMeta =
SCBEngine.getInstance().getProducerMicroserviceMeta();
- SchemaMeta schemaMeta =
microserviceMeta.ensureFindSchemaMeta(header.getSchemaId());
- this.operationMeta =
schemaMeta.ensureFindOperation(header.getOperationName());
- this.bodyBuffer = bodyBuffer;
- }
-
- private void runInExecutor() {
- try {
- if (isInQueueTimeout()) {
- throw new InvocationException(Status.INTERNAL_SERVER_ERROR, "Timeout
when processing the request.");
- }
- doRunInExecutor();
- } catch (Throwable e) {
- String msg = String.format("handle request error, %s, msgId=%d",
- operationMeta.getMicroserviceQualifiedName(),
- msgId);
- LOGGER.error(msg, e);
-
- sendResponse(header.getContext(), Response.providerFailResp(e));
- }
- }
-
- private boolean isInQueueTimeout() {
- return System.nanoTime() - invocation.getInvocationStageTrace().getStart()
>
- operationMeta.getConfig().getNanoHighwayRequestWaitInPoolTimeout();
- }
-
- private void doRunInExecutor() throws Exception {
- invocation.onExecuteStart();
-
- invocation.getInvocationStageTrace().startServerFiltersRequest();
- HighwayCodec.decodeRequest(invocation, header, operationProtobuf,
bodyBuffer);
- invocation.getHandlerContext().put(Const.REMOTE_ADDRESS,
this.connection.getNetSocket().remoteAddress());
-
- invocation.onStartHandlersRequest();
- invocation.next(response -> sendResponse(invocation.getContext(),
response));
- }
-
- private void sendResponse(Map<String, String> context, Response response) {
- invocation.getInvocationStageTrace().finishHandlersResponse();
-
- ResponseHeader header = new ResponseHeader();
- header.setStatusCode(response.getStatusCode());
- header.setReasonPhrase(response.getReasonPhrase());
- header.setContext(context);
- header.fromMultiMap(response.getHeaders());
-
- ResponseRootSerializer bodySchema =
operationProtobuf.findResponseRootSerializer(response.getStatusCode());
- Object body = response.getResult();
- if (response.isFailed()) {
- body = ((InvocationException) body).getErrorData();
- }
-
- try {
- Buffer respBuffer = HighwayCodec.encodeResponse(msgId, header,
bodySchema, body);
- invocation.getInvocationStageTrace().finishServerFiltersResponse();
- connection.write(respBuffer.getByteBuf());
- } catch (Exception e) {
- // keep highway performance and simple, this encoding/decoding error not
need handle by client
- String msg = String.format("encode response failed, %s, msgId=%d",
- invocation.getOperationMeta().getMicroserviceQualifiedName(),
- msgId);
- LOGGER.error(msg, e);
- } finally {
- if (invocation != null) {
- invocation.onFinish(response);
- }
- }
- }
-
- /**
- * start time in queue.
- */
- public void execute() {
- try {
- invocation = InvocationFactory.forProvider(endpoint,
- operationMeta,
- null);
- operationProtobuf = ProtobufManager.getOrCreateOperation(invocation);
- HighwayTransportContext transportContext = new HighwayTransportContext()
- .setConnection(connection)
- .setMsgId(msgId)
- .setHeader(header)
- .setBodyBuffer(bodyBuffer)
-
.setOperationProtobuf(ProtobufManager.getOrCreateOperation(invocation));
- invocation.setTransportContext(transportContext);
- invocation.mergeContext(header.getContext());
-
- invocation.onStart(null, start);
- invocation.getInvocationStageTrace().startSchedule();
-
- Holder<Boolean> qpsFlowControlReject =
checkQpsFlowControl(operationMeta);
- if (qpsFlowControlReject.value) {
- return;
- }
-
- operationMeta.getExecutor().execute(this::runInExecutor);
- } catch (Throwable e) {
- if (e instanceof RejectedExecutionException) {
- LOGGER.error("failed to schedule invocation, message={},
executor={}.", e.getMessage(), e.getClass().getName());
- }
- sendResponse(header.getContext(), Response.providerFailResp(e));
- }
- }
-
- private Holder<Boolean> checkQpsFlowControl(OperationMeta operationMeta) {
- Holder<Boolean> qpsFlowControlReject = new Holder<>(false);
- @SuppressWarnings("deprecation")
- Handler providerQpsFlowControlHandler =
operationMeta.getProviderQpsFlowControlHandler();
- if (null != providerQpsFlowControlHandler) {
- try {
- providerQpsFlowControlHandler.handle(invocation, response -> {
- qpsFlowControlReject.value = true;
- sendResponse(header.getContext(), response);
- });
- } catch (Exception e) {
- LOGGER.error("failed to execute ProviderQpsFlowControlHandler", e);
- qpsFlowControlReject.value = true;
- sendResponse(header.getContext(), Response.providerFailResp(e));
- }
- }
- return qpsFlowControlReject;
- }
-}
diff --git
a/transports/transport-rest/transport-rest-client/src/test/java/org/apache/servicecomb/transport/rest/client/http/TestRestClientInvocation.java
b/transports/transport-rest/transport-rest-client/src/test/java/org/apache/servicecomb/transport/rest/client/http/TestRestClientInvocation.java
index 48ed990be..34e372117 100644
---
a/transports/transport-rest/transport-rest-client/src/test/java/org/apache/servicecomb/transport/rest/client/http/TestRestClientInvocation.java
+++
b/transports/transport-rest/transport-rest-client/src/test/java/org/apache/servicecomb/transport/rest/client/http/TestRestClientInvocation.java
@@ -27,11 +27,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.Level;
import org.apache.servicecomb.common.rest.RestConst;
-import org.apache.servicecomb.common.rest.VertxRestInvocation;
import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
import org.apache.servicecomb.common.rest.definition.path.URLPathBuilder;
import org.apache.servicecomb.common.rest.filter.HttpClientFilter;
@@ -47,7 +44,6 @@ import
org.apache.servicecomb.foundation.common.utils.JsonUtils;
import
org.apache.servicecomb.foundation.test.scaffolding.exception.RuntimeExceptionWithoutStackTrace;
import org.apache.servicecomb.foundation.test.scaffolding.log.LogCollector;
import
org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.registry.definition.DefinitionConst;
import org.apache.servicecomb.swagger.invocation.AsyncResponse;
import org.apache.servicecomb.swagger.invocation.Response;
@@ -179,7 +175,8 @@ public class TestRestClientInvocation {
MatcherAssert.assertThat(headers.names(),
Matchers.containsInAnyOrder(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE,
org.apache.servicecomb.core.Const.CSE_CONTEXT));
- Assertions.assertEquals(TARGET_MICROSERVICE_NAME,
headers.get(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE));
+ Assertions.assertEquals(TARGET_MICROSERVICE_NAME,
+ headers.get(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE));
Assertions.assertEquals("{}",
headers.get(org.apache.servicecomb.core.Const.CSE_CONTEXT));
Assertions.assertEquals(nanoTime,
invocation.getInvocationStageTrace().getStartClientFiltersRequest());
}
@@ -216,7 +213,8 @@ public class TestRestClientInvocation {
MatcherAssert.assertThat(headers.names(),
Matchers.containsInAnyOrder(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE,
org.apache.servicecomb.core.Const.CSE_CONTEXT));
- Assertions.assertEquals(TARGET_MICROSERVICE_NAME,
headers.get(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE));
+ Assertions.assertEquals(TARGET_MICROSERVICE_NAME,
+ headers.get(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE));
Assertions.assertEquals("{}",
headers.get(org.apache.servicecomb.core.Const.CSE_CONTEXT));
Assertions.assertEquals(nanoTime,
invocation.getInvocationStageTrace().getStartClientFiltersRequest());
operationConfig.setClientRequestHeaderFilterEnabled(true);
@@ -278,74 +276,6 @@ public class TestRestClientInvocation {
logCollector.teardown();
}
- @Test
- public void testSetCseContext_enable_unicode() throws Exception {
- Map<String, String> contextMap = new HashMap<>();
- contextMap.put("key", "测试");
- contextMap.put("encodedKey", StringEscapeUtils.escapeJson("测试"));
- when(invocation.getContext()).thenReturn(contextMap);
- restClientInvocation.setCseContext();
-
- String context =
headers.get(org.apache.servicecomb.core.Const.CSE_CONTEXT);
- HttpServletRequestEx requestEx = new MockUp<HttpServletRequestEx>(){
- @Mock
- public String getHeader(String name){
- if (StringUtils.equals(name,
org.apache.servicecomb.core.Const.CSE_CONTEXT)){
- return context;
- } else {
- return null;
- }
- }
- }.getMockInstance();
-
- VertxRestInvocation vertxRestInvocation = new VertxRestInvocation();
- Deencapsulation.setField(vertxRestInvocation, "requestEx", requestEx);
- Deencapsulation.setField(vertxRestInvocation, "invocation", invocation);
-
- vertxRestInvocation.setContext();
-
- Assertions.assertEquals("测试", invocation.getContext().get("key"));
- Assertions.assertEquals(StringEscapeUtils.escapeJson("测试"),
invocation.getContext().get("encodedKey"));
- }
-
-
- @Test
- public void testSetCseContext_disable_unicode() throws Exception {
- Map<String, String> contextMap = new HashMap<>();
- contextMap.put("key", "测试");
- contextMap.put("encodedKey", StringEscapeUtils.escapeJson("测试"));
- when(invocation.getContext()).thenReturn(contextMap);
-
- new MockUp<JsonUtils>() {
- @Mock
- public String writeUnicodeValueAsString(Object value) throws
JsonProcessingException {
- return JsonUtils.writeValueAsString(value);
- }
- };
-
- restClientInvocation.setCseContext();
- String context =
headers.get(org.apache.servicecomb.core.Const.CSE_CONTEXT);
- HttpServletRequestEx requestEx = new MockUp<HttpServletRequestEx>(){
- @Mock
- public String getHeader(String name){
- if (StringUtils.equals(name,
org.apache.servicecomb.core.Const.CSE_CONTEXT)){
- return context;
- } else {
- return null;
- }
- }
- }.getMockInstance();
-
- VertxRestInvocation vertxRestInvocation = new VertxRestInvocation();
- Deencapsulation.setField(vertxRestInvocation, "requestEx", requestEx);
- Deencapsulation.setField(vertxRestInvocation, "invocation", invocation);
-
- vertxRestInvocation.setContext();
- Assertions.assertEquals("测试", invocation.getContext().get("key"));
- Assertions.assertEquals(StringEscapeUtils.escapeJson("测试"),
invocation.getContext().get("encodedKey"));
- }
-
-
@SuppressWarnings("unchecked")
@Test
public void handleResponse() {
diff --git
a/transports/transport-rest/transport-rest-servlet/src/main/java/org/apache/servicecomb/transport/rest/servlet/RestServletProducerInvocation.java
b/transports/transport-rest/transport-rest-servlet/src/main/java/org/apache/servicecomb/transport/rest/servlet/RestServletProducerInvocation.java
deleted file mode 100644
index 50909b307..000000000
---
a/transports/transport-rest/transport-rest-servlet/src/main/java/org/apache/servicecomb/transport/rest/servlet/RestServletProducerInvocation.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.transport.rest.servlet;
-
-import org.apache.servicecomb.common.rest.HttpTransportContext;
-import org.apache.servicecomb.common.rest.RestProducerInvocation;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import org.apache.servicecomb.core.definition.OperationMeta;
-import
org.apache.servicecomb.foundation.vertx.http.StandardHttpServletRequestEx;
-
-public class RestServletProducerInvocation extends RestProducerInvocation {
- @Override
- protected void findRestOperation() {
- super.findRestOperation();
-
- boolean cacheRequest =
collectCacheRequest(restOperationMeta.getOperationMeta());
- ((StandardHttpServletRequestEx) requestEx).setCacheRequest(cacheRequest);
- }
-
- protected boolean collectCacheRequest(OperationMeta operationMeta) {
- for (HttpServerFilter filter : httpServerFilters) {
- if (filter.needCacheRequest(operationMeta)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- protected void createInvocation() {
- super.createInvocation();
-
- invocation.setTransportContext(new HttpTransportContext(requestEx,
responseEx, produceProcessor));
- }
-}
diff --git
a/transports/transport-rest/transport-rest-servlet/src/test/java/org/apache/servicecomb/transport/rest/servlet/TestRestServletProducerInvocation.java
b/transports/transport-rest/transport-rest-servlet/src/test/java/org/apache/servicecomb/transport/rest/servlet/TestRestServletProducerInvocation.java
deleted file mode 100644
index 6090a891b..000000000
---
a/transports/transport-rest/transport-rest-servlet/src/test/java/org/apache/servicecomb/transport/rest/servlet/TestRestServletProducerInvocation.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.servicecomb.transport.rest.servlet;
-
-import java.util.Arrays;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.servicecomb.common.rest.RestProducerInvocation;
-import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
-import org.apache.servicecomb.core.definition.OperationMeta;
-import
org.apache.servicecomb.foundation.vertx.http.StandardHttpServletRequestEx;
-import org.junit.Test;
-
-import mockit.Deencapsulation;
-import mockit.Expectations;
-import mockit.Mock;
-import mockit.MockUp;
-import mockit.Mocked;
-import org.junit.jupiter.api.Assertions;
-
-public class TestRestServletProducerInvocation {
- @Mocked
- OperationMeta operationMeta;
-
- @Mocked
- RestOperationMeta restOperationMeta;
-
- RestServletProducerInvocation restInvocation = new
RestServletProducerInvocation();
-
- @Test
- public void findRestOperationCacheTrue(@Mocked HttpServletRequest request,
@Mocked HttpServerFilter f1) {
- StandardHttpServletRequestEx requestEx = new
StandardHttpServletRequestEx(request);
- Deencapsulation.setField(restInvocation, "requestEx", requestEx);
-
- new MockUp<RestProducerInvocation>() {
- @Mock
- void findRestOperation() {
- Deencapsulation.setField(getMockInstance(), "restOperationMeta",
restOperationMeta);
- }
- };
-
- List<HttpServerFilter> httpServerFilters = Arrays.asList(f1);
- new Expectations() {
- {
- f1.needCacheRequest(operationMeta);
- result = true;
- }
- };
-
- restInvocation.setHttpServerFilters(httpServerFilters);
-
- restInvocation.findRestOperation();
- Assertions.assertTrue(requestEx.isCacheRequest());
- }
-
- @Test
- public void collectCacheRequestCacheTrue(@Mocked HttpServerFilter f1) {
- List<HttpServerFilter> httpServerFilters = Arrays.asList(f1);
- new Expectations() {
- {
- f1.needCacheRequest(operationMeta);
- result = true;
- }
- };
-
- restInvocation.setHttpServerFilters(httpServerFilters);
- Assertions.assertTrue(restInvocation.collectCacheRequest(operationMeta));
- }
-
- @Test
- public void collectCacheRequestCacheFalse(@Mocked HttpServerFilter f1) {
- List<HttpServerFilter> httpServerFilters = Arrays.asList(f1);
- new Expectations() {
- {
- f1.needCacheRequest(operationMeta);
- result = false;
- }
- };
-
- restInvocation.setHttpServerFilters(httpServerFilters);
- Assertions.assertFalse(restInvocation.collectCacheRequest(operationMeta));
- }
-}
diff --git
a/transports/transport-rest/transport-rest-vertx/src/main/java/org/apache/servicecomb/transport/rest/vertx/VertxRestDispatcher.java
b/transports/transport-rest/transport-rest-vertx/src/main/java/org/apache/servicecomb/transport/rest/vertx/VertxRestDispatcher.java
index bb60ce6ed..1e22a127f 100644
---
a/transports/transport-rest/transport-rest-vertx/src/main/java/org/apache/servicecomb/transport/rest/vertx/VertxRestDispatcher.java
+++
b/transports/transport-rest/transport-rest-vertx/src/main/java/org/apache/servicecomb/transport/rest/vertx/VertxRestDispatcher.java
@@ -22,8 +22,6 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.Status.Family;
-import org.apache.servicecomb.common.rest.AbstractRestInvocation;
-import org.apache.servicecomb.common.rest.RestConst;
import org.apache.servicecomb.common.rest.RestProducerInvocationFlow;
import org.apache.servicecomb.common.rest.RestVertxProducerInvocationCreator;
import org.apache.servicecomb.core.Const;
@@ -85,7 +83,6 @@ public class VertxRestDispatcher extends
AbstractVertxHttpDispatcher {
protected void failureHandler(RoutingContext context) {
LOGGER.error("http server failed.", context.failure());
- AbstractRestInvocation restProducerInvocation =
context.get(RestConst.REST_PRODUCER_INVOCATION);
Throwable e = context.failure();
if (e instanceof ErrorDataDecoderException) {
Throwable cause = e.getCause();
@@ -96,20 +93,13 @@ public class VertxRestDispatcher extends
AbstractVertxHttpDispatcher {
// only when unexpected exception happens, it will run into here.
// the connection should be closed.
- handleFailureAndClose(context, restProducerInvocation, e);
+ handleFailureAndClose(context, e);
}
/**
* Try to find out the failure information and send it in response.
*/
- private void handleFailureAndClose(RoutingContext context,
AbstractRestInvocation restProducerInvocation,
- Throwable e) {
- if (null != restProducerInvocation) {
- // if there is restProducerInvocation, let it send exception in
response. The exception is allowed to be null.
- sendFailResponseByInvocation(context, restProducerInvocation, e);
- return;
- }
-
+ private void handleFailureAndClose(RoutingContext context, Throwable e) {
if (null != e) {
// if there exists exception, try to send this exception by
RoutingContext
sendExceptionByRoutingContext(context, e);
@@ -188,15 +178,6 @@ public class VertxRestDispatcher extends
AbstractVertxHttpDispatcher {
return true;
}
- /**
- * Use restProducerInvocation to send failure message. The throwable is
allowed to be null.
- */
- private void sendFailResponseByInvocation(RoutingContext context,
AbstractRestInvocation restProducerInvocation,
- Throwable e) {
- restProducerInvocation.sendFailResponse(e);
- context.response().close();
- }
-
protected void onRequest(RoutingContext context) {
if (transport == null) {
transport =
SCBEngine.getInstance().getTransportManager().findTransport(Const.RESTFUL);
diff --git
a/transports/transport-rest/transport-rest-vertx/src/test/java/org/apache/servicecomb/transport/rest/vertx/TestVertxRestDispatcher.java
b/transports/transport-rest/transport-rest-vertx/src/test/java/org/apache/servicecomb/transport/rest/vertx/TestVertxRestDispatcher.java
index 4b992caab..5f33c7227 100644
---
a/transports/transport-rest/transport-rest-vertx/src/test/java/org/apache/servicecomb/transport/rest/vertx/TestVertxRestDispatcher.java
+++
b/transports/transport-rest/transport-rest-vertx/src/test/java/org/apache/servicecomb/transport/rest/vertx/TestVertxRestDispatcher.java
@@ -17,23 +17,16 @@
package org.apache.servicecomb.transport.rest.vertx;
-import java.util.List;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.apache.http.HttpHeaders;
import org.apache.servicecomb.common.rest.RestConst;
-import org.apache.servicecomb.common.rest.RestProducerInvocation;
-import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
import org.apache.servicecomb.config.ConfigUtil;
import org.apache.servicecomb.core.SCBEngine;
-import org.apache.servicecomb.core.Transport;
import org.apache.servicecomb.core.bootstrap.SCBBootstrap;
import org.apache.servicecomb.core.transport.TransportManager;
import org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
-import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
@@ -47,8 +40,6 @@ import
io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDec
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
-import mockit.Mock;
-import mockit.MockUp;
import mockit.Mocked;
public class TestVertxRestDispatcher {
@@ -68,18 +59,6 @@ public class TestVertxRestDispatcher {
dispatcher = new VertxRestDispatcher();
dispatcher.init(mainRouter);
- new MockUp<RestProducerInvocation>() {
- @Mock
- void sendFailResponse(Throwable throwable) {
- TestVertxRestDispatcher.this.throwable = throwable;
- }
-
- @Mock
- void invoke(Transport transport, HttpServletRequestEx requestEx,
HttpServletResponseEx responseEx,
- List<HttpServerFilter> httpServerFilters) {
- }
- };
-
SCBBootstrap.createSCBEngineForTest().setTransportManager(transportManager);
}
@@ -94,56 +73,6 @@ public class TestVertxRestDispatcher {
Assertions.assertEquals(Integer.MAX_VALUE, dispatcher.getOrder());
}
- @Test
- public void failureHandlerNormal() {
- RoutingContext context = Mockito.mock(RoutingContext.class);
- RestProducerInvocation restProducerInvocation = new
RestProducerInvocation();
-
Mockito.when(context.get(RestConst.REST_PRODUCER_INVOCATION)).thenReturn(restProducerInvocation);
- Exception e = new Exception();
- Mockito.when(context.failure()).thenReturn(e);
- MockHttpServerResponse response = new MockHttpServerResponse();
- Mockito.when(context.response()).thenReturn(response);
-
- dispatcher.failureHandler(context);
-
- Assertions.assertSame(e, this.throwable);
- Assertions.assertTrue(response.responseClosed);
- }
-
- @Test
- public void failureHandlerErrorDataWithInvocation() {
- RestProducerInvocation restProducerInvocation = new
RestProducerInvocation();
- RoutingContext context = Mockito.mock(RoutingContext.class);
-
Mockito.when(context.get(RestConst.REST_PRODUCER_INVOCATION)).thenReturn(restProducerInvocation);
- InvocationException e = Mockito.mock(InvocationException.class);
- ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
- Mockito.when(context.failure()).thenReturn(edde);
- MockHttpServerResponse response = new MockHttpServerResponse();
- Mockito.when(context.response()).thenReturn(response);
-
- dispatcher.failureHandler(context);
-
- Assertions.assertSame(e, this.throwable);
- Assertions.assertTrue(response.responseClosed);
- }
-
- @Test
- public void failureHandlerErrorDataWithNormal() {
- RestProducerInvocation restProducerInvocation = new
RestProducerInvocation();
- RoutingContext context = Mockito.mock(RoutingContext.class);
-
Mockito.when(context.get(RestConst.REST_PRODUCER_INVOCATION)).thenReturn(restProducerInvocation);
- Exception e = new Exception();
- ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
- Mockito.when(context.failure()).thenReturn(edde);
- MockHttpServerResponse response = new MockHttpServerResponse();
- Mockito.when(context.response()).thenReturn(response);
-
- dispatcher.failureHandler(context);
-
- Assertions.assertSame(edde, this.throwable);
- Assertions.assertTrue(response.responseClosed);
- }
-
@Test
public void
failureHandlerWithNoRestProducerInvocationAndInvocationException() {
RoutingContext context = Mockito.mock(RoutingContext.class);