com.linecorp.armeria.client.Clients Java Examples

The following examples show how to use com.linecorp.armeria.client.Clients. 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: HelloServiceTest.java    From armeria with Apache License 2.0 9 votes vote down vote up
@Test
void getReplyWithDelay() {
    final HelloServiceFutureStub helloService = Clients.newClient(uri(), HelloServiceFutureStub.class);
    final ListenableFuture<HelloReply> future =
            helloService.lazyHello(HelloRequest.newBuilder().setName("Armeria").build());
    final AtomicBoolean completed = new AtomicBoolean();
    Futures.addCallback(future, new FutureCallback<HelloReply>() {
        @Override
        public void onSuccess(HelloReply result) {
            assertThat(result.getMessage()).isEqualTo("Hello, Armeria!");
            completed.set(true);
        }

        @Override
        public void onFailure(Throwable t) {
            // Should never reach here.
            throw new Error(t);
        }
    }, MoreExecutors.directExecutor());

    await().untilTrue(completed);
}
 
Example #2
Source File: GrpcClientRequestContextInitFailureTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void assertFailure(EndpointGroup group, Consumer<Throwable> requirements) {
    final AtomicReference<ClientRequestContext> capturedCtx = new AtomicReference<>();
    final TestServiceBlockingStub client =
            Clients.builder("gproto+http", group)
                   .decorator((delegate, ctx, req) -> {
                       capturedCtx.set(ctx);
                       return delegate.execute(ctx, req);
                   })
                   .build(TestServiceBlockingStub.class);

    final Throwable grpcCause = catchThrowable(() -> client.emptyCall(Empty.getDefaultInstance()));
    assertThat(grpcCause).isInstanceOfSatisfying(StatusRuntimeException.class, cause -> {
        assertThat(cause.getStatus().getCode()).isSameAs(Code.UNAVAILABLE);
    });

    final Throwable actualCause = grpcCause.getCause();
    assertThat(actualCause).isInstanceOf(UnprocessedRequestException.class);
    assertThat(actualCause.getCause()).satisfies((Consumer) requirements);

    assertThat(capturedCtx.get()).satisfies(ctx -> {
        final RequestLog log = ctx.log().ensureComplete();
        assertThat(log.requestCause()).isSameAs(actualCause);
        assertThat(log.responseCause()).isSameAs(actualCause);
    });
}
 
Example #3
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void contextCaptorAsync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final HelloService.AsyncIface client =
            Clients.builder(uri(Handlers.HELLO, format, protocol))
                   .options(clientOptions)
                   .build(Handlers.HELLO.asyncIface());

    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.hello("kukuman", new ThriftFuture<>());
        final ClientRequestContext ctx = ctxCaptor.get();
        final RpcRequest rpcReq = ctx.rpcRequest();
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.method()).isEqualTo("hello");
        assertThat(rpcReq.params()).containsExactly("kukuman");
    }
}
 
Example #4
Source File: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testThriftServiceRegistrationBean() throws Exception {
    final HelloService.Iface client = Clients.newClient(newUrl("tbinary+h1c") + "/thrift",
                                                        HelloService.Iface.class);
    assertThat(client.hello("world")).isEqualTo("hello world");

    final WebClient webClient = WebClient.of(newUrl("h1c"));
    final HttpResponse response = webClient.get("/internal/docs/specification.json");

    final AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).node("services[2].name").isStringEqualTo(
            "com.linecorp.armeria.spring.test.thrift.main.HelloService");
    assertThatJson(res.contentUtf8())
            .node("services[2].exampleHttpHeaders[0].x-additional-header").isStringEqualTo("headerVal");
    assertThatJson(res.contentUtf8())
            .node("services[0].methods[0].exampleHttpHeaders[0].x-additional-header")
            .isStringEqualTo("headerVal");
}
 
Example #5
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testBinaryServiceSync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final BinaryService.Iface client = Clients.builder(uri(Handlers.BINARY, format, protocol))
                                              .options(clientOptions)
                                              .build(Handlers.BINARY.iface());

    final ByteBuffer result = client.process(ByteBuffer.wrap(new byte[] { 1, 2 }));
    final List<Byte> out = new ArrayList<>();
    for (int i = result.position(); i < result.limit(); i++) {
        out.add(result.get(i));
    }
    assertThat(out).containsExactly((byte) 2, (byte) 3);
}
 
Example #6
Source File: GrpcApiClientBuilder.java    From curiostack with MIT License 6 votes vote down vote up
public ClientBuilder newBuilder(String url) {
  return Clients.builder("gproto+" + url)
      .decorator(
          client ->
              new SimpleDecoratingHttpClient(client) {
                @Override
                public HttpResponse execute(ClientRequestContext ctx, HttpRequest req)
                    throws Exception {
                  // Many Google services do not support the standard application/grpc+proto
                  // header...
                  req =
                      req.withHeaders(
                          req.headers().toBuilder()
                              .set(HttpHeaderNames.CONTENT_TYPE, "application/grpc")
                              .build());
                  return delegate().execute(ctx, req);
                }
              })
      .decorator(credentialsDecorator.newAccessTokenDecorator())
      .decorator(BraveClient.newDecorator(tracing))
      .decorator(MetricCollectingClient.newDecorator(MetricLabels.grpcRequestLabeler()))
      .decorator(LoggingClient.builder().newDecorator());
}
 
Example #7
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testTimeServiceAsync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final TimeService.AsyncIface client =
            Clients.builder(uri(Handlers.TIME, format, protocol))
                   .options(clientOptions)
                   .build(Handlers.TIME.asyncIface());

    final BlockingQueue<Object> resQueue = new LinkedBlockingQueue<>();
    client.getServerTime(new RequestQueuingCallback(resQueue));

    final Object result = resQueue.take();
    assertThat(result).isInstanceOf(Long.class);
    assertThat((Long) result).isLessThanOrEqualTo(System.currentTimeMillis());
}
 
Example #8
Source File: ContentPreviewingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void decodedContentPreview() {
    final WebClient client = WebClient.builder(server.httpUri())
                                      .decorator(DecodingClient.newDecorator())
                                      .decorator(ContentPreviewingClient.newDecorator(100))
                                      .build();
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, "/",
                                                     HttpHeaderNames.CONTENT_TYPE, "text/plain");

    final ClientRequestContext context;
    try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) {
        final AggregatedHttpResponse res = client.execute(headers, "Armeria").aggregate().join();
        assertThat(res.contentUtf8()).isEqualTo("Hello Armeria!");
        assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("gzip");
        context = captor.get();
    }

    final RequestLog requestLog = context.log().whenComplete().join();
    assertThat(requestLog.requestContentPreview()).isEqualTo("Armeria");
    assertThat(requestLog.responseContentPreview()).isEqualTo("Hello Armeria!");
}
 
Example #9
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void contextCaptorSync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final HelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                             .options(clientOptions)
                                             .build(Handlers.HELLO.iface());
    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.hello("kukuman");
        final ClientRequestContext ctx = ctxCaptor.get();
        final RpcRequest rpcReq = ctx.rpcRequest();
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.method()).isEqualTo("hello");
        assertThat(rpcReq.params()).containsExactly("kukuman");
    }
}
 
Example #10
Source File: ArmeriaClientInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
protected void beforeMethod(final URI uri, final HttpMethod httpMethod, final String path) {
    final ContextCarrier contextCarrier = new ContextCarrier();
    final String remotePeer = uri.getHost() + ":" + uri.getPort();

    final AbstractSpan exitSpan = ContextManager.createExitSpan(path, contextCarrier, remotePeer);

    exitSpan.setComponent(ComponentsDefine.ARMERIA);
    exitSpan.setLayer(SpanLayer.HTTP);
    Tags.HTTP.METHOD.set(exitSpan, httpMethod.name());

    ContextManager.getRuntimeContext().put(KEY_SAFE_CLOSEABLE, Clients.withHttpHeaders(headers -> {
        HttpHeadersBuilder builder = headers.toBuilder();
        for (CarrierItem item = contextCarrier.items(); item.hasNext(); ) {
            item = item.next();
            builder.add(AsciiString.of(item.getHeadKey()), item.getHeadValue());
        }
        return builder.build();
    }));
}
 
Example #11
Source File: PooledResponseBufferBenchmark.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Setup
public void startServer() throws Exception {
    final ServerBuilder sb =
            Server.builder()
                  .service("/a", THttpService.of((AsyncIface) (name, cb) -> cb.onComplete(RESPONSE))
                                             .decorate(PooledDecoratingService::new))
                  .service("/b", THttpService.of((AsyncIface) (name, cb) -> cb.onComplete(RESPONSE))
                                             .decorate(UnpooledDecoratingService::new));
    server = sb.build();
    server.start().join();

    final int httpPort = server.activeLocalPort(SessionProtocol.HTTP);
    pooledClient = Clients.newClient("tbinary+http://127.0.0.1:" + httpPort + "/a",
                                     HelloService.Iface.class);
    unpooledClient = Clients.newClient("tbinary+http://127.0.0.1:" + httpPort + "/b",
                                       HelloService.Iface.class);
}
 
Example #12
Source File: ThriftDynamicTimeoutTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientDecoratorProvider.class)
void testDisabledTimeout(Function<? super RpcClient, ? extends RpcClient> clientDecorator)
        throws Exception {
    final SleepService.Iface client =
            Clients.builder(server.httpUri(BINARY) + "/fakeSleep")
                   .rpcDecorator(clientDecorator)
                   .responseTimeout(Duration.ofSeconds(1))
                   .build(SleepService.Iface.class);

    final long delay = 30000;
    final Stopwatch sw = Stopwatch.createStarted();
    // This call should take very short amount of time because the fakeSleep service does not sleep.
    client.sleep(delay);
    assertThat(sw.elapsed(TimeUnit.MILLISECONDS)).isLessThan(delay);
}
 
Example #13
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    requestLogQueue.clear();
    final DecoratingHttpClientFunction requestLogRecorder = (delegate, ctx, req) -> {
        ctx.log().whenComplete().thenAccept(requestLogQueue::add);
        return delegate.execute(ctx, req);
    };

    final URI uri = server.httpUri(GrpcSerializationFormats.PROTO);
    blockingStub = Clients.builder(uri)
                          .maxResponseLength(MAX_MESSAGE_SIZE)
                          .decorator(LoggingClient.builder().newDecorator())
                          .decorator(requestLogRecorder)
                          .build(TestServiceBlockingStub.class);
    asyncStub = Clients.builder(uri.getScheme(), server.httpEndpoint())
                       .decorator(LoggingClient.builder().newDecorator())
                       .decorator(requestLogRecorder)
                       .build(TestServiceStub.class);
}
 
Example #14
Source File: ClientRequestContextPushedOnCallbackTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void checkContextOnAsyncMethodCallbackOnError(AsyncIface client) throws Exception {
    final AtomicReference<ClientRequestContext> ctxHolder = new AtomicReference<>();
    final ClientRequestContext ctx;
    final CountDownLatch latch = new CountDownLatch(1);
    try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) {
        client.hello("foo", new AsyncMethodCallback<String>() {
            @Override
            public void onComplete(String response) {}

            @Override
            public void onError(Exception exception) {
                ctxHolder.set(RequestContext.currentOrNull());
                latch.countDown();
            }
        });
        ctx = captor.get();
    }

    latch.await();
    assertThat(ctx).isSameAs(ctxHolder.get());
}
 
Example #15
Source File: ThriftHttpHeaderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleManipulationAsync() throws Exception {
    final HelloService.AsyncIface client = Clients.newClient(
            server.httpUri(BINARY) + "/hello", HelloService.AsyncIface.class);

    final BlockingQueue<Object> result = new ArrayBlockingQueue<>(1);
    final Callback callback = new Callback(result);

    try (SafeCloseable ignored = Clients.withHttpHeader(AUTHORIZATION, SECRET)) {
        client.hello("armeria", callback);
    }

    assertThat(result.poll(10, TimeUnit.SECONDS)).isEqualTo("Hello, armeria!");

    // Ensure that the header manipulator set in the thread-local variable has been cleared.
    client.hello("bar", callback);
    assertThat(result.poll(10, TimeUnit.SECONDS))
            .isInstanceOf(TException.class)
            .matches(o -> ((Throwable) o).getMessage().contains("not authorized"),
                     "must fail with authorization failure");
}
 
Example #16
Source File: ThriftClientRequestContextInitFailureTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void assertFailure(EndpointGroup endpointGroup, Consumer<Throwable> requirements) {
    final AtomicBoolean rpcDecoratorRan = new AtomicBoolean();
    final AtomicReference<ClientRequestContext> capturedCtx = new AtomicReference<>();
    final HelloService.Iface client =
            Clients.builder("tbinary+http", endpointGroup)
                   .decorator((delegate, ctx, req) -> {
                       capturedCtx.set(ctx);
                       return delegate.execute(ctx, req);
                   })
                   .rpcDecorator((delegate, ctx, req) -> {
                       rpcDecoratorRan.set(true);
                       return delegate.execute(ctx, req);
                   })
                   .build(HelloService.Iface.class);

    final Throwable actualCause = catchThrowable(() -> client.hello(""));
    assertThat(actualCause).isInstanceOf(UnprocessedRequestException.class);
    assertThat(actualCause.getCause()).satisfies((Consumer) requirements);

    assertThat(rpcDecoratorRan).isTrue();
    assertThat(capturedCtx.get()).satisfies(ctx -> {
        final RequestLog log = ctx.log().ensureComplete();
        assertThat(log.requestCause()).isSameAs(actualCause);
        assertThat(log.responseCause()).isSameAs(actualCause);
    });
}
 
Example #17
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void deadlineNotExceeded() {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(
                            TimeUnit.SECONDS.toMillis(10)));
    stub
            .streamingOutputCall(
                    StreamingOutputCallRequest.newBuilder()
                                              .addResponseParameters(
                                                      ResponseParameters.newBuilder()
                                                                        .setIntervalUs(0))
                                              .build())
            .next();
}
 
Example #18
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maxInboundSize_tooBig() throws Exception {
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final int size = blockingStub.streamingOutputCall(request).next().getSerializedSize();
    requestLogQueue.take();

    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES.newValue(size - 1));
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
    assertThat(Exceptions.traceText(t)).contains("exceeds maximum");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
    });
}
 
Example #19
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maxOutboundSize_tooBig() throws Exception {
    // set at least one field to ensure the size is non-zero.
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES.newValue(
                            request.getSerializedSize() - 1));
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.CANCELLED);
    assertThat(Exceptions.traceText(t)).contains("message too large");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.CANCELLED);
    });
}
 
Example #20
Source File: BraveIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupClients() {
    fooClient = Clients.builder(server.httpUri(BINARY) + "/foo")
                       .decorator(BraveClient.newDecorator(newTracing("client/foo")))
                       .build(HelloService.Iface.class);
    zipClient = Clients.builder(server.httpUri(BINARY) + "/zip")
                       .decorator(BraveClient.newDecorator(newTracing("client/zip")))
                       .build(HelloService.Iface.class);
    fooClientWithoutTracing = Clients.newClient(server.httpUri(BINARY) + "/foo", HelloService.Iface.class);
    barClient = newClient("/bar");
    quxClient = newClient("/qux");
    poolWebClient = WebClient.of(server.httpUri());
    timeoutClient = Clients.builder(server.httpUri(BINARY) + "/timeout")
                           .decorator(BraveClient.newDecorator(newTracing("client/timeout")))
                           .build(HelloService.Iface.class);
    timeoutClientClientTimesOut =
            Clients.builder(server.httpUri(BINARY) + "/timeout")
                   .decorator(BraveClient.newDecorator(newTracing("client/timeout")))
                   .responseTimeout(Duration.ofMillis(3))
                   .build(HelloService.Iface.class);
    http1TimeoutClientClientTimesOut =
            Clients.builder(server.uri(H1C, BINARY) + "/timeout")
                   .decorator(BraveClient.newDecorator(newTracing("client/timeout")))
                   .responseTimeout(Duration.ofMillis(3))
                   .build(HelloService.Iface.class);
}
 
Example #21
Source File: BraveClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void get(WebClient client, String path, BiConsumer<Integer, Throwable> callback) {
    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        final HttpResponse res = client.get(path);
        final ClientRequestContext ctx = ctxCaptor.get();
        res.aggregate().handle((response, cause) -> {
            try (SafeCloseable ignored = ctx.push()) {
                if (cause == null) {
                    callback.accept(response.status().code(), null);
                } else {
                    callback.accept(null, cause);
                }
            }
            return null;
        });
    }
}
 
Example #22
Source File: GrpcServiceLogNameTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void logNameInAccessLog() {
    final TestServiceBlockingStub client = Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO))
                                                  .build(TestServiceBlockingStub.class);
    client.emptyCall(Empty.newBuilder().build());

    await().untilAsserted(() -> {
        verify(appender, atLeast(0)).doAppend(eventCaptor.capture());
        assertThat(eventCaptor.getAllValues()).anyMatch(evt -> {
            return evt.getMessage().contains("POST /armeria.grpc.testing.TestService/EmptyCall h2c");
        });
    });
}
 
Example #23
Source File: ThriftClientBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void uri() throws Exception {
    final HelloService.Iface client = Clients.builder("tbinary+https://google.com/")
                                             .build(HelloService.Iface.class);
    final ClientBuilderParams params = Clients.unwrap(client, ClientBuilderParams.class);
    assertThat(params).isNotNull();
    assertThat(params.uri().toString()).isEqualTo("tbinary+https://google.com/");
}
 
Example #24
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testDerivedClient(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final String AUTHORIZATION = "authorization";
    final String NO_TOKEN = "";
    final String TOKEN_A = "token 1234";
    final String TOKEN_B = "token 5678";

    final HeaderService.Iface client = Clients.builder(uri(Handlers.HEADER, format, protocol))
                                              .options(clientOptions)
                                              .build(Handlers.HEADER.iface());

    assertThat(client.header(AUTHORIZATION)).isEqualTo(NO_TOKEN);

    final HeaderService.Iface clientA =
            Clients.newDerivedClient(client,
                                     newHttpHeaderOption(HttpHeaderNames.of(AUTHORIZATION), TOKEN_A));

    final HeaderService.Iface clientB =
            Clients.newDerivedClient(client,
                                     newHttpHeaderOption(HttpHeaderNames.of(AUTHORIZATION), TOKEN_B));

    assertThat(clientA.header(AUTHORIZATION)).isEqualTo(TOKEN_A);
    assertThat(clientB.header(AUTHORIZATION)).isEqualTo(TOKEN_B);

    // Ensure that the parent client's HTTP_HEADERS option did not change:
    assertThat(client.header(AUTHORIZATION)).isEqualTo(NO_TOKEN);
}
 
Example #25
Source File: ThriftTreeStructureTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testRecursiveUnionCodec() throws TException {
    for (SerializationFormat format : ThriftSerializationFormats.values()) {
        final TreeService.Iface client = Clients.newClient(server.uri(HTTP, format).resolve("/tree"),
                                                           TreeService.Iface.class);
        assertThat(client.createTree(treeRequest)).isEqualTo("OK");
    }
}
 
Example #26
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testMessageLogsForOneWay(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final OnewayHelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                                   .options(clientOptions)
                                                   .build(Handlers.ONEWAYHELLO.iface());
    recordMessageLogs = true;
    client.hello("trustin");

    final RequestLog log = requestLogs.take();

    assertThat(log.requestHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.requestContent()).isInstanceOf(RpcRequest.class);
    assertThat(log.rawRequestContent()).isInstanceOf(ThriftCall.class);

    final RpcRequest request = (RpcRequest) log.requestContent();
    assertThat(request.serviceType()).isEqualTo(OnewayHelloService.Iface.class);
    assertThat(request.method()).isEqualTo("hello");
    assertThat(request.params()).containsExactly("trustin");

    final ThriftCall rawRequest = (ThriftCall) log.rawRequestContent();
    assertThat(rawRequest.header().type).isEqualTo(TMessageType.ONEWAY);
    assertThat(rawRequest.header().name).isEqualTo("hello");
    assertThat(rawRequest.args()).isInstanceOf(OnewayHelloService.hello_args.class);
    assertThat(((OnewayHelloService.hello_args) rawRequest.args()).getName()).isEqualTo("trustin");

    assertThat(log.responseHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.responseContent()).isInstanceOf(RpcResponse.class);
    assertThat(log.rawResponseContent()).isNull();

    final RpcResponse response = (RpcResponse) log.responseContent();
    assertThat(response.get()).isNull();
}
 
Example #27
Source File: TMultiplexedProtocolIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static Iface client(String serviceName) {
    final URI uri;
    if (serviceName.isEmpty()) {
        uri = server.httpUri(BINARY);
    } else {
        uri = server.httpUri(BINARY).resolve('#' + serviceName);
    }
    return Clients.newClient(uri, Iface.class);
}
 
Example #28
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void json() throws Exception {
    final AtomicReference<HttpHeaders> requestHeaders = new AtomicReference<>();
    final AtomicReference<byte[]> payload = new AtomicReference<>();
    final UnitTestServiceBlockingStub jsonStub =
            Clients.builder(server.httpUri(GrpcSerializationFormats.JSON))
                   .decorator(client -> new SimpleDecoratingHttpClient(client) {
                       @Override
                       public HttpResponse execute(ClientRequestContext ctx, HttpRequest req)
                               throws Exception {
                           requestHeaders.set(req.headers());
                           return new FilteredHttpResponse(unwrap().execute(ctx, req)) {
                               @Override
                               protected HttpObject filter(HttpObject obj) {
                                   if (obj instanceof HttpData) {
                                       payload.set(((HttpData) obj).array());
                                   }
                                   return obj;
                               }
                           };
                       }
                   })
                   .build(UnitTestServiceBlockingStub.class);
    final SimpleResponse response = jsonStub.staticUnaryCall(REQUEST_MESSAGE);
    assertThat(response).isEqualTo(RESPONSE_MESSAGE);
    assertThat(requestHeaders.get().get(HttpHeaderNames.CONTENT_TYPE)).isEqualTo(
            "application/grpc+json");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StaticUnaryCall");
        assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
        assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE);
    });

    final byte[] deframed = Arrays.copyOfRange(payload.get(), 5, payload.get().length);
    assertThat(new String(deframed, StandardCharsets.UTF_8)).contains("oauthScope");
}
 
Example #29
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testFileServiceSync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final FileService.Iface client =
            Clients.builder(uri(Handlers.FILE, format, protocol))
                   .options(clientOptions)
                   .build(Handlers.FILE.iface());

    assertThatThrownBy(() -> client.create("test")).isInstanceOf(FileServiceException.class);
}
 
Example #30
Source File: ThriftSerializationFormatsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void acceptNotSameAsContentType() throws Exception {
    final HelloService.Iface client =
            Clients.builder(server.httpUri(TEXT) + "/hello")
                   .setHttpHeader(HttpHeaderNames.ACCEPT, "application/x-thrift; protocol=TBINARY")
                   .build(HelloService.Iface.class);
    assertThatThrownBy(() -> client.hello("Trustin")).isInstanceOf(InvalidResponseHeadersException.class)
                                                     .hasMessageContaining(":status=406");
}