Java Code Examples for com.linecorp.armeria.client.Clients#newClient()

The following examples show how to use com.linecorp.armeria.client.Clients#newClient() . 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: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testGrpcServiceRegistrationBean() throws Exception {
    final HelloServiceBlockingStub client = Clients.newClient(newUrl("gproto+h2c") + '/',
                                                              HelloServiceBlockingStub.class);
    final HelloRequest request = HelloRequest.newBuilder()
                                             .setName("world")
                                             .build();
    assertThat(client.hello(request).getMessage()).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[1].name").isStringEqualTo(
            "com.linecorp.armeria.spring.test.grpc.main.HelloService");
    assertThatJson(res.contentUtf8())
            .node("services[1].exampleHttpHeaders[0].x-additional-header").isStringEqualTo("headerVal");
    assertThatJson(res.contentUtf8())
            .node("services[1].methods[0].exampleHttpHeaders[0].x-additional-header")
            .isStringEqualTo("headerVal");
}
 
Example 3
Source File: ClientRequestContextPushedOnCallbackTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushedContextOnAsyncMethodCallback() throws Exception {
    final AtomicReference<ClientRequestContext> ctxHolder = new AtomicReference<>();
    final AsyncIface client = Clients.newClient(server.httpUri(BINARY) + "/hello", AsyncIface.class);

    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) {
                assertThat(response).isEqualTo("Hello, foo!");
                ctxHolder.set(RequestContext.currentOrNull());
                latch.countDown();
            }

            @Override
            public void onError(Exception exception) {}
        });
        ctx = captor.get();
    }

    latch.await();
    assertThat(ctx).isSameAs(ctxHolder.get());
}
 
Example 4
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 5
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 6
Source File: ThrottlingRpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void serve() throws Exception {
    final HelloService.Iface client =
            Clients.newClient(server.httpUri(BINARY) + "/thrift-always", HelloService.Iface.class);
    when(serviceHandler.hello("foo")).thenReturn("bar");

    assertThat(client.hello("foo")).isEqualTo("bar");
}
 
Example 7
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 8
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 9
Source File: ThriftHttpErrorResponseTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@EnumSource(TestParam.class)
void test(TestParam param) throws Exception {
    final Iface client = Clients.newClient(server.httpUri(BINARY).resolve(param.path), Iface.class);
    assertThatThrownBy(() -> client.hello("foo"))
            .isInstanceOfSatisfying(InvalidResponseHeadersException.class, cause -> {
                assertThat(cause.headers().status()).isEqualTo(HttpStatus.CONFLICT);
            });
}
 
Example 10
Source File: AbstractUnaryGrpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void normal_downstream() {
    final TestServiceBlockingStub stub =
            Clients.newClient(server.httpUri(GrpcSerializationFormats.PROTO),
                              TestServiceBlockingStub.class);
    assertThat(stub.unaryCall(SimpleRequest.newBuilder()
                                           .setPayload(Payload.newBuilder()
                                                              .setBody(
                                                                      ByteString.copyFromUtf8("hello"))
                                                              .build())
                                           .build()).getPayload().getBody().toStringUtf8())
            .isEqualTo("hello");
}
 
Example 11
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void emptyUnary_grpcWeb() throws Exception {
    final TestServiceBlockingStub stub =
            Clients.newClient(server.httpUri(GrpcSerializationFormats.PROTO_WEB),
                              TestServiceBlockingStub.class);
    assertThat(stub.emptyCall(EMPTY)).isEqualTo(EMPTY);
}
 
Example 12
Source File: ThriftSerializationFormatsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void notAllowed() throws Exception {
    final HelloService.Iface client =
            Clients.newClient(server.httpUri(TEXT) + "/hellobinaryonly", HelloService.Iface.class);
    assertThatThrownBy(() -> client.hello("Trustin")).isInstanceOf(InvalidResponseHeadersException.class)
                                                     .hasMessageContaining(":status=415");
}
 
Example 13
Source File: ThrottlingRpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void throttle() throws Exception {
    final HelloService.Iface client =
            Clients.newClient(server.httpUri(BINARY) + "/thrift-never", HelloService.Iface.class);

    assertThatThrownBy(() -> client.hello("foo"))
            .isInstanceOfSatisfying(InvalidResponseHeadersException.class, cause -> {
                assertThat(cause.headers().status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
            });
    verifyNoMoreInteractions(serviceHandler);
}
 
Example 14
Source File: HelloServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void getReplyFromServerSideBlockingCall() {
    final HelloServiceBlockingStub helloService = Clients.newClient(uri(), HelloServiceBlockingStub.class);
    final Stopwatch watch = Stopwatch.createStarted();
    assertThat(helloService.blockingHello(HelloRequest.newBuilder().setName("Armeria").build())
                           .getMessage()).isEqualTo("Hello, Armeria!");
    assertThat(watch.elapsed(TimeUnit.SECONDS)).isGreaterThanOrEqualTo(3);
}
 
Example 15
Source File: StaticEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
public void testRoundRobinServerGroup() throws Exception {
    serverOne.start();
    serverTwo.start();
    serverThree.start();

    final EndpointGroup endpointGroup = EndpointGroup.of(
            Endpoint.of("127.0.0.1", serverOne.httpPort()).withWeight(1),
            Endpoint.of("127.0.0.1", serverTwo.httpPort()).withWeight(2),
            Endpoint.of("127.0.0.1", serverThree.httpPort()).withWeight(3));

    HelloService.Iface ipService = Clients.newClient("ttext+http", endpointGroup, "/serverIp",
                                                     HelloService.Iface.class);
    assertThat(ipService.hello("ip")).isEqualTo(
            "host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo(
            "host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());

    final EndpointGroup serverGroup2 = EndpointGroup.of(
            Endpoint.of("127.0.0.1", serverOne.httpPort()).withWeight(2),
            Endpoint.of("127.0.0.1", serverTwo.httpPort()).withWeight(4),
            Endpoint.of("127.0.0.1", serverThree.httpPort()).withWeight(3));

    ipService = Clients.newClient("tbinary+http", serverGroup2, "/serverIp",
                                  HelloService.Iface.class);

    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());

    //new round
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());

    //direct connect to ip host
    ipService = Clients.newClient("tbinary+http://127.0.0.1:" + serverOne.httpPort() + "/serverIp",
                                  HelloService.Iface.class);
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
}
 
Example 16
Source File: HelloServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void getReply() {
    final HelloServiceBlockingStub helloService = Clients.newClient(uri(), HelloServiceBlockingStub.class);
    assertThat(helloService.hello(HelloRequest.newBuilder().setName("Armeria").build()).getMessage())
            .isEqualTo("Hello, Armeria!");
}
 
Example 17
Source File: HelloServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void beforeClass() throws Exception {
    server = Main.newServer(0, 0);
    server.start().join();
    helloService = Clients.newClient(uri(), HelloServiceStub.class);
}
 
Example 18
Source File: THttpClientBadSeqIdTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 30000L)
public void badSeqId() throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        ss.setSoTimeout(5000);

        final THttpClient client = Clients.newClient(
                "ttext+h1c://127.0.0.1:" + ss.getLocalPort(), THttpClient.class);

        final RpcResponse res = client.execute("/", HelloService.Iface.class, "hello", "trustin");
        assertThat(res.isDone()).isFalse();

        try (Socket s = ss.accept()) {
            final InputStream sin = s.getInputStream();
            final OutputStream sout = s.getOutputStream();

            // Ensure the request is received before sending its response.
            assertThat(sin.read()).isGreaterThanOrEqualTo(0);

            // Send the TTEXT over HTTP/1 response with mismatching seqid.
            final byte[] thriftTextResponse = ('{' +
                                               "  \"method\": \"hello\"," +
                                               "  \"type\": \"CALL\"," +
                                               "  \"seqid\": " + Integer.MIN_VALUE + ',' +
                                               "  \"args\": { \"success\": \"Hello, trustin!\" }" +
                                               '}').getBytes(StandardCharsets.US_ASCII);
            sout.write(("HTTP/1.1 200 OK\r\n" +
                        "Connection: close\r\n" +
                        "Content-Length: " + thriftTextResponse.length + "\r\n" +
                        "\r\n").getBytes(StandardCharsets.US_ASCII));
            sout.write(thriftTextResponse);

            // Wait until the client closes the connection thanks to 'connection: close'.
            while (sin.read() >= 0) {
                continue;
            }
        } catch (SocketTimeoutException expected) {
            // A connection was not accepted; Wait for the response to raise the cause.
            res.join();
            // Should not reach here because .join() will fail, but for completeness:
            throw expected;
        }

        assertThatThrownBy(res::get)
                .isInstanceOf(ExecutionException.class)
                .hasCauseInstanceOf(TApplicationException.class)
                .satisfies(cause -> assertThat(((TApplicationException) Exceptions.peel(cause)).getType())
                        .isEqualTo(TApplicationException.BAD_SEQUENCE_ID));
    }
}
 
Example 19
Source File: HelloServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void beforeClass() throws Exception {
    server = Main.newServer(0, 0);
    server.start().join();
    helloService = Clients.newClient(uri(), ReactorHelloServiceGrpc.ReactorHelloServiceStub.class);
}
 
Example 20
Source File: ThriftSerializationFormatsTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
public void notDefault() throws Exception {
    final HelloService.Iface client = Clients.newClient(server.httpUri(TEXT) + "/hello",
                                                        HelloService.Iface.class);
    assertThat(client.hello("Trustin")).isEqualTo("Hello, Trustin!");
}