org.apache.servicecomb.swagger.invocation.Response Java Examples
The following examples show how to use
org.apache.servicecomb.swagger.invocation.Response.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestBizkeeperCommand.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void testResumeWithFallbackProvider() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); Observable<Response> observe = bizkeeperCommand.resumeWithFallback(); Assert.assertNotNull(observe); }
Example #2
Source File: TestRestClientInvocation.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void invoke_3rdPartyServiceExposeServiceCombHeaders(@Mocked Response resp) throws Exception { doAnswer(a -> { asyncResp.complete(resp); return null; }).when(request).end(); when(invocation.isThirdPartyInvocation()).thenReturn(true); operationConfig.setClientRequestHeaderFilterEnabled(false); restClientInvocation.invoke(invocation, asyncResp); Assert.assertSame(resp, response); Assert.assertThat(headers.names(), Matchers.containsInAnyOrder(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE, org.apache.servicecomb.core.Const.CSE_CONTEXT)); Assert.assertEquals(TARGET_MICROSERVICE_NAME, headers.get(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE)); Assert.assertEquals("{}", headers.get(org.apache.servicecomb.core.Const.CSE_CONTEXT)); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartClientFiltersRequest()); Assert.assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartSend()); operationConfig.setClientRequestHeaderFilterEnabled(true); }
Example #3
Source File: TestInvocationFinishEvent.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void construct(@Mocked Invocation invocation, @Mocked Response response) { InvocationStageTrace stageTrace = new InvocationStageTrace(invocation); long time = 123; new MockUp<System>() { @Mock long nanoTime() { return time; } }; new Expectations() { { invocation.getInvocationStageTrace(); result = stageTrace; } }; stageTrace.finish(); event = new InvocationFinishEvent(invocation, response); Assert.assertEquals(time, event.getNanoCurrent()); Assert.assertSame(invocation, event.getInvocation()); Assert.assertSame(response, event.getResponse()); }
Example #4
Source File: HighwayServerCodecFilter.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
private CompletableFuture<Response> encodeResponse(Invocation invocation, Response response) { ResponseHeader header = new ResponseHeader(); header.setStatusCode(response.getStatusCode()); header.setReasonPhrase(response.getReasonPhrase()); header.setContext(invocation.getContext()); header.setHeaders(response.getHeaders()); HighwayTransportContext transportContext = invocation.getTransportContext(); long msgId = transportContext.getMsgId(); OperationProtobuf operationProtobuf = transportContext.getOperationProtobuf(); ResponseRootSerializer bodySchema = operationProtobuf.findResponseRootSerializer(response.getStatusCode()); try { Buffer respBuffer = HighwayCodec.encodeResponse( msgId, header, bodySchema, response.getResult()); transportContext.setResponseBuffer(respBuffer); return CompletableFuture.completedFuture(response); } catch (Exception e) { // keep highway performance and simple, this encoding/decoding error not need handle by client String msg = String.format("encode response failed, msgId=%d", msgId); return AsyncUtils.completeExceptionally(new IllegalStateException(msg, e)); } }
Example #5
Source File: RestServerCodecFilterTest.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void should_convert_exception_to_response_when_decode_request_failed() throws ExecutionException, InterruptedException { mockDecodeRequestFail(); new Expectations(invocation) { { invocation.findResponseType(anyInt); result = TypeFactory.defaultInstance().constructType(String.class); } }; Response response = codecFilter.onFilter(invocation, nextNode).get(); assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR); assertThat(Json.encode(response.getResult())) .isEqualTo("{\"code\":\"SCB.50000000\",\"message\":\"encode request failed\"}"); }
Example #6
Source File: CseAsyncClientHttpRequestTest.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void testNormal() { Holder<Invocation> holder = new Holder<>(); CseAsyncClientHttpRequest client = new CseAsyncClientHttpRequest(URI.create( "cse://defaultMicroservice/" + CseAsyncClientHttpRequestTest.CseAsyncClientHttpRequestTestSchema.class .getSimpleName() + "/testbytes"), HttpMethod.POST) { @Override protected CompletableFuture<ClientHttpResponse> doAsyncInvoke(Invocation invocation) { CompletableFuture<ClientHttpResponse> completableFuture = new CompletableFuture<>(); holder.value = invocation; completableFuture.complete(new CseClientHttpResponse(Response.ok("result"))); return completableFuture; } }; byte[] body = "abc".getBytes(); client.setRequestBody(body); client.executeAsync(); Assert.assertArrayEquals(body, (byte[]) holder.value.getInvocationArguments().get("input")); }
Example #7
Source File: TestAbstractRestInvocation.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void sendResponseQuietlyExceptionOnNullInvocation(@Mocked Response response) { 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 }
Example #8
Source File: EdgeSignatureRequestFilter.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Override public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) { EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext().get(EdgeConst.ENCRYPT_CONTEXT); if (encryptContext == null) { return null; } Hcr hcr = encryptContext.getHcr(); // signature for query and form List<String> names = Collections.list(requestEx.getParameterNames()); names.sort(Comparator.naturalOrder()); Hasher hasher = Hashing.sha256().newHasher(); hasher.putString(hcr.getSignatureKey(), StandardCharsets.UTF_8); for (String name : names) { hasher.putString(name, StandardCharsets.UTF_8); hasher.putString(requestEx.getParameter(name), StandardCharsets.UTF_8); } LOGGER.info("afterReceiveRequest signature: {}", hasher.hash().toString()); return null; }
Example #9
Source File: TestBizkeeperCommand.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void testConstructConsumer() { Invocation invocation = Mockito.mock(Invocation.class); Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class)); Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1"); HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter() .withRequestCacheEnabled(true) .withRequestLogEnabled(false); BizkeeperCommand bizkeeperCommand = new ConsumerBizkeeperCommand("groupname", invocation, HystrixObservableCommand.Setter .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation)) .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation)) .andCommandPropertiesDefaults(setter)); Observable<Response> response = bizkeeperCommand.construct(); Assert.assertNotNull(response); }
Example #10
Source File: JaxrsConsumerResponseMapper.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Override public Object mapResponse(Response response) { ResponseBuilder responseBuilder = javax.ws.rs.core.Response.status(response.getStatus()).entity(response.getResult()); Map<String, List<Object>> headers = response.getHeaders().getHeaderMap(); if (headers == null) { return responseBuilder.build(); } for (Entry<String, List<Object>> entry : headers.entrySet()) { if (entry.getValue() == null) { continue; } for (Object value : entry.getValue()) { if (value != null) { responseBuilder.header(entry.getKey(), value); } } } return responseBuilder.build(); }
Example #11
Source File: BizkeeperHandlerDelegate.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
protected HystrixObservable<Response> forceFallbackCommand(Invocation invocation) { return new HystrixObservable<Response>() { @Override public Observable<Response> observe() { ReplaySubject<Response> subject = ReplaySubject.create(); final Subscription sourceSubscription = toObservable().subscribe(subject); return subject.doOnUnsubscribe(sourceSubscription::unsubscribe); } @Override public Observable<Response> toObservable() { return Observable.create(f -> { try { f.onNext(FallbackPolicyManager.getFallbackResponse(handler.groupname, null, invocation)); } catch (Exception e) { f.onError(e); } }); } }; }
Example #12
Source File: TestClassPathStaticResourceHandler.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void readContentFailed() throws IOException { new Expectations(handler) { { handler.findResource(anyString); result = new RuntimeExceptionWithoutStackTrace("read content failed."); } }; try (LogCollector logCollector = new LogCollector()) { Response response = handler.handle("index.html"); Assert.assertEquals("failed to process static resource, path=web-root/index.html", logCollector.getLastEvents().getMessage()); InvocationException invocationException = response.getResult(); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR, invocationException.getStatus()); Assert.assertEquals("failed to process static resource.", ((CommonExceptionData) invocationException.getErrorData()).getMessage()); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode()); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), response.getReasonPhrase()); } }
Example #13
Source File: ProducerInvocationFlow.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
private void finishInvocation(Invocation invocation, Response response, Throwable throwable) { invocation.onFinish(response); if (throwable == null) { return; } throwable = Exceptions.unwrap(throwable); if (requestEx == null) { LOGGER.error("Failed to finish invocation, operation:{}", invocation.getMicroserviceQualifiedName(), throwable); return; } LOGGER.error("Failed to finish invocation, operation:{}, request uri:{}", invocation.getMicroserviceQualifiedName(), requestEx.getRequestURI(), throwable); }
Example #14
Source File: FallbackPolicyManager.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
public static Response getFallbackResponse(String type, Throwable error, Invocation invocation) { FallbackPolicy policy = getPolicy(type, invocation); if (policy != null) { return policy.getFallbackResponse(invocation, error); } else { return Response.failResp(invocation.getInvocationType(), BizkeeperExceptionUtils .createBizkeeperException(BizkeeperExceptionUtils.SERVICECOMB_BIZKEEPER_FALLBACK, error, invocation.getOperationMeta().getMicroserviceQualifiedName())); } }
Example #15
Source File: LoadbalanceHandler.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
protected boolean isFailedResponse(Response resp) { if (resp.isFailed()) { if (InvocationException.class.isInstance(resp.getResult())) { InvocationException e = (InvocationException) resp.getResult(); return e.getStatusCode() == ExceptionFactory.CONSUMER_INNER_STATUS_CODE || e.getStatusCode() == 503; } else { return true; } } else { return false; } }
Example #16
Source File: RestProducerInvocationFlow.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override protected Invocation sendCreateInvocationException(Throwable throwable) { try { Response response = Exceptions.exceptionToResponse(null, throwable, INTERNAL_SERVER_ERROR); RestServerCodecFilter.encodeResponse(response, false, DEFAULT_PRODUCE_PROCESSOR, responseEx); } catch (Throwable e) { LOGGER.error("Failed to send response when prepare invocation failed, request uri:{}", requestEx.getRequestURI(), e); } flushResponse("UNKNOWN_OPERATION"); return null; }
Example #17
Source File: TestClassPathStaticResourceHandler.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void attack() { Response response = handler.handle("../microservice.yaml"); InvocationException invocationException = response.getResult(); Assert.assertEquals(Status.NOT_FOUND, invocationException.getStatus()); Assert.assertEquals(Status.NOT_FOUND.getReasonPhrase(), ((CommonExceptionData) invocationException.getErrorData()).getMessage()); Assert.assertEquals(404, response.getStatusCode()); Assert.assertEquals("Not Found", response.getReasonPhrase()); }
Example #18
Source File: TestClassPathStaticResourceHandler.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void normal() throws IOException { Response response = handler.handle("index.html"); Part part = response.getResult(); try (InputStream is = part.getInputStream()) { Assert.assertTrue(IOUtils.toString(is, StandardCharsets.UTF_8).endsWith("<html></html>")); } Assert.assertEquals("text/html", part.getContentType()); Assert.assertEquals("text/html", response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE)); Assert.assertEquals("inline", response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION)); }
Example #19
Source File: TestInspectorImpl.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void getStaticResource() throws IOException { Response response = inspector.getStaticResource("index.html"); Part part = response.getResult(); Assert.assertEquals("inline", response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION)); Assert.assertEquals(MediaType.TEXT_HTML, response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE)); try (InputStream is = part.getInputStream()) { Assert.assertTrue(IOUtils.toString(is, StandardCharsets.UTF_8).endsWith("</html>")); } }
Example #20
Source File: HighwayServerCodecFilter.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); }
Example #21
Source File: TestExceptionToProducerResponseConverters.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void convertExceptionToResponse( @Mocked ExceptionToProducerResponseConverter<Throwable> c1, @Mocked Response r1, @Mocked ExceptionToProducerResponseConverter<Throwable> c2, @Mocked Response r2, @Mocked ExceptionToProducerResponseConverter<Throwable> cDef) { new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(ExceptionToProducerResponseConverter.class); result = Arrays.asList(c1, c2, cDef); c1.getExceptionClass(); result = Throwable.class; c1.convert((SwaggerInvocation) any, (Throwable) any); result = r1; c2.getExceptionClass(); result = Exception.class; c2.convert((SwaggerInvocation) any, (Throwable) any); result = r2; cDef.getExceptionClass(); result = null; } }; ExceptionToProducerResponseConverters exceptionToProducerResponseConverters = new ExceptionToProducerResponseConverters(); Assert.assertSame(r1, exceptionToProducerResponseConverters.convertExceptionToResponse(null, new Throwable())); Assert.assertSame(r2, exceptionToProducerResponseConverters.convertExceptionToResponse(null, new Exception())); Assert.assertSame(r2, exceptionToProducerResponseConverters.convertExceptionToResponse(null, new IllegalStateException())); }
Example #22
Source File: FilterNode.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
private Response rethrowExceptionInResponse(Response response) { if (response.isFailed() && response.getResult() instanceof Throwable) { AsyncUtils.rethrow(response.getResult()); } return response; }
Example #23
Source File: InspectorImpl.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) public Response downloadSchemas(@QueryParam("format") SchemaFormat format) { if (format == null) { format = SchemaFormat.SWAGGER; } // normally, schema will not be too big, just save them in memory temporarily ByteArrayOutputStream os = new ByteArrayOutputStream(); try (ZipOutputStream zos = new ZipOutputStream(os)) { for (Entry<String, String> entry : schemas.entrySet()) { // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(entry.getKey() + format.getSuffix())); String content = entry.getValue(); if (SchemaFormat.HTML.equals(format)) { content = swaggerToHtml(content); } zos.write(content.getBytes(StandardCharsets.UTF_8)); zos.closeEntry(); } } catch (Throwable e) { String msg = "failed to create schemas zip file, format=" + format + "."; LOGGER.error(msg, e); return Response.failResp(new InvocationException(Status.INTERNAL_SERVER_ERROR, msg)); } Part part = new InputStreamPart(null, new ByteArrayInputStream(os.toByteArray())) .setSubmittedFileName( RegistrationManager.INSTANCE.getMicroservice().getServiceName() + format.getSuffix() + ".zip"); return Response.ok(part); }
Example #24
Source File: TestConsumerResponseMapperFactorys.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void should_mapper_to_scbResponse_string() { SwaggerConsumerOperation operation = swaggerConsumer.findOperation("scbResponse"); assertThat(operation.getResponseMapper().getClass().getName()) .startsWith(CseResponseConsumerResponseMapperFactory.class.getName()); Response scbResponse = (Response) operation.getResponseMapper().mapResponse(response); Assert.assertEquals(result, scbResponse.getResult()); }
Example #25
Source File: TestSpringmvcProducerResponseMapper.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void mapResponse_withoutHeader_fail() { ResponseEntity<String[]> responseEntity = new ResponseEntity<>(arrResult, org.springframework.http.HttpStatus.BAD_REQUEST); Response response = mapper.mapResponse(null, responseEntity); Assert.assertSame(arrResult, response.getResult()); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus().getStatusCode()); }
Example #26
Source File: TestSpringmvcProducerResponseMapper.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void mapResponse_withHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("h", "v"); ResponseEntity<String[]> responseEntity = new ResponseEntity<>(arrResult, headers, org.springframework.http.HttpStatus.OK); Response response = mapper.mapResponse(null, responseEntity); List<Object> hv = response.getHeaders().getHeader("h"); Assert.assertThat(hv, Matchers.contains("v")); }
Example #27
Source File: TestDefaultHttpClientFilter.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void testAfterReceiveResponseNormal(@Mocked Invocation invocation, @Mocked HttpServletResponseEx responseEx, @Mocked Buffer bodyBuffer, @Mocked OperationMeta operationMeta, @Mocked RestOperationMeta swaggerRestOperation, @Mocked ProduceProcessor produceProcessor) throws Exception { MultiMap responseHeader = new CaseInsensitiveHeaders(); responseHeader.add("b", "bValue"); Object decodedResult = new Object(); new Expectations() { { responseEx.getHeader(HttpHeaders.CONTENT_TYPE); result = "json"; responseEx.getHeaderNames(); result = Arrays.asList("a", "b"); responseEx.getHeaders("b"); result = responseHeader.getAll("b"); swaggerRestOperation.findProduceProcessor("json"); result = produceProcessor; produceProcessor.decodeResponse(bodyBuffer, (JavaType) any); result = decodedResult; invocation.getOperationMeta(); result = operationMeta; operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION); result = swaggerRestOperation; responseEx.getStatusType(); result = Status.OK; } }; Response response = filter.afterReceiveResponse(invocation, responseEx); Assert.assertSame(decodedResult, response.getResult()); Assert.assertEquals(1, response.getHeaders().getHeaderMap().size()); Assert.assertEquals(response.getHeaders().getHeader("b"), Arrays.asList("bValue")); }
Example #28
Source File: TestSpringmvcProducerResponseMapperFactory.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void createResponseMapper() { Method responseEntityMethod = ReflectUtils.findMethod(this.getClass(), "responseEntity"); ProducerResponseMapper mapper = factory .createResponseMapper(factorys, responseEntityMethod.getGenericReturnType()); Assert.assertThat(mapper, Matchers.instanceOf(SpringmvcProducerResponseMapper.class)); ResponseEntity<String[]> responseEntity = new ResponseEntity<>(new String[] {"a", "b"}, HttpStatus.OK); Response response = mapper.mapResponse(null, responseEntity); Assert.assertThat(response.getResult(), Matchers.arrayContaining("a", "b")); }
Example #29
Source File: JaxrsProducerResponseMapper.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override public Response mapResponse(StatusType status, Object response) { javax.ws.rs.core.Response jaxrsResponse = (javax.ws.rs.core.Response) response; Response cseResponse = Response.status(jaxrsResponse.getStatusInfo()).entity(jaxrsResponse.getEntity()); MultivaluedMap<String, Object> headers = jaxrsResponse.getHeaders(); for (Entry<String, List<Object>> entry : headers.entrySet()) { if (entry.getValue() == null || entry.getValue().isEmpty()) { continue; } cseResponse.getHeaders().addHeader(entry.getKey(), entry.getValue()); } return cseResponse; }
Example #30
Source File: TestExceptionFactory.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void convertExceptionToResponse() { Error error = new Error("test"); Response response = ExceptionFactory.convertExceptionToResponse(null, error); Assert.assertSame(Status.OK, response.getStatus()); Assert.assertEquals("response from error: test", response.getResult()); }