Java Code Examples for com.linecorp.armeria.client.WebClient#get()

The following examples show how to use com.linecorp.armeria.client.WebClient#get() . 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: 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 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: 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 4
Source File: JsonTextSequencesTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void fromPublisherOrStream() {
    final WebClient client = WebClient.of(rule.httpUri() + "/seq");
    for (final String path : ImmutableList.of("/publisher", "/stream", "/custom-mapper")) {
        final HttpResponse response = client.get(path);
        StepVerifier.create(response)
                    .expectNext(ResponseHeaders.of(HttpStatus.OK,
                                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_SEQ))
                    .assertNext(o -> ensureExpectedHttpData(o, "foo"))
                    .assertNext(o -> ensureExpectedHttpData(o, "bar"))
                    .assertNext(o -> ensureExpectedHttpData(o, "baz"))
                    .assertNext(o -> ensureExpectedHttpData(o, "qux"))
                    .assertNext(JsonTextSequencesTest::assertThatLastContent)
                    .expectComplete()
                    .verify();
    }
}
 
Example 5
Source File: ArmeriaSpringActuatorAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void assertStatus(int port, String url, int statusCode) {
    final WebClient client = WebClient.of(newUrl("http", port));
    final HttpResponse response = client.get(url);

    final AggregatedHttpResponse httpResponse = response.aggregate().join();
    assertThat(httpResponse.status().code()).isEqualTo(statusCode);
}
 
Example 6
Source File: LocalArmeriaPortsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpServiceRegistrationBean() throws Exception {
    for (Integer port : ports) {
        final WebClient client = WebClient.of(newUrl("h1c", port));
        final HttpResponse response = client.get("/ok");
        final AggregatedHttpResponse res = response.aggregate().get();
        assertThat(res.status()).isEqualTo(HttpStatus.OK);
        assertThat(res.contentUtf8()).isEqualTo("ok");
    }
}
 
Example 7
Source File: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpServiceRegistrationBean() throws Exception {
    final WebClient client = WebClient.of(newUrl("h1c"));

    final HttpResponse response = client.get("/ok");

    final AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("ok");
}
 
Example 8
Source File: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedServiceRegistrationBean() throws Exception {
    final WebClient client = WebClient.of(newUrl("h1c"));

    HttpResponse response = client.get("/annotated/get");

    AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("annotated");

    response = client.get("/annotated/get/2");
    res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("exception");

    final RequestHeaders postJson = RequestHeaders.of(HttpMethod.POST, "/annotated/post",
                                                      HttpHeaderNames.CONTENT_TYPE, "application/json");
    response = client.execute(postJson, "{\"foo\":\"bar\"}");
    res = response.aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).node("foo").isEqualTo("bar");

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

    res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).node("services[0].name").isStringEqualTo(
            "com.linecorp.armeria.spring.ArmeriaAutoConfigurationTest$AnnotatedService");
    assertThatJson(res.contentUtf8())
            .node("services[0].methods[2].exampleRequests[0]").isStringEqualTo("{\"foo\":\"bar\"}");
    assertThatJson(res.contentUtf8())
            .node("services[0].exampleHttpHeaders[0].x-additional-header").isStringEqualTo("headerVal");
    assertThatJson(res.contentUtf8())
            .node("services[0].methods[0].exampleHttpHeaders[0].x-additional-header")
            .isStringEqualTo("headerVal");
}
 
Example 9
Source File: ArmeriaAutoConfigurationWithoutMeterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpServiceRegistrationBean() throws Exception {
    final WebClient client = WebClient.of(newUrl("h1c"));

    final HttpResponse response = client.get("/ok");

    final AggregatedHttpResponse msg = response.aggregate().get();
    assertThat(msg.status()).isEqualTo(HttpStatus.OK);
    assertThat(msg.contentUtf8()).isEqualTo("ok");
}
 
Example 10
Source File: LocalArmeriaPortTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpServiceRegistrationBean() throws Exception {
    final WebClient client = WebClient.of(newUrl("h1c"));
    final HttpResponse response = client.get("/ok");
    final AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("ok");
}
 
Example 11
Source File: ArmeriaAutoConfigurationWithConsumerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void normal() throws Exception {
    final WebClient client = WebClient.of(newUrl("h1c"));

    final HttpResponse response = client.get("/customizer");

    final AggregatedHttpResponse msg = response.aggregate().get();
    assertThat(msg.status()).isEqualTo(HttpStatus.OK);
}
 
Example 12
Source File: RetryingClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void doNotRetryWhenResponseIsAborted() throws Exception {
    final List<Throwable> abortCauses =
            Arrays.asList(null, new IllegalStateException("abort stream with a specified cause"));
    for (Throwable abortCause : abortCauses) {
        final AtomicReference<ClientRequestContext> context = new AtomicReference<>();
        final WebClient client =
                WebClient.builder(server.httpUri())
                         .decorator(RetryingClient.newDecorator(retryAlways))
                         .decorator((delegate, ctx, req) -> {
                             context.set(ctx);
                             return delegate.execute(ctx, req);
                         })
                         .build();
        final HttpResponse httpResponse = client.get("/response-abort");
        if (abortCause == null) {
            httpResponse.abort();
        } else {
            httpResponse.abort(abortCause);
        }

        final RequestLog log = context.get().log().whenComplete().join();
        assertThat(responseAbortServiceCallCounter.get()).isOne();
        assertThat(log.requestCause()).isNull();
        if (abortCause == null) {
            assertThat(log.responseCause()).isExactlyInstanceOf(AbortedStreamException.class);
        } else {
            assertThat(log.responseCause()).isSameAs(abortCause);
        }

        // Sleep 3 more seconds to check if there was another retry.
        TimeUnit.SECONDS.sleep(3);
        assertThat(responseAbortServiceCallCounter.get()).isOne();
        responseAbortServiceCallCounter.decrementAndGet();
    }
}
 
Example 13
Source File: ServiceBindingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void accessLogWriter() throws InterruptedException {
    final WebClient client = WebClient.of(server.httpUri());
    client.execute(RequestHeaders.of(HttpMethod.POST, "/hello"), "armeria")
          .aggregate().join();

    assertThat(accessLogWriterCheckLatch.getCount()).isOne();

    client.get("/greet/armeria");
    accessLogWriterCheckLatch.await();
}
 
Example 14
Source File: HttpServerStreamingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void runStreamingResponseTest(WebClient client, boolean slowClient)
        throws InterruptedException, ExecutionException {
    final HttpResponse res = client.get("/zeroes/" + STREAMING_CONTENT_LENGTH);
    final AtomicReference<HttpStatus> status = new AtomicReference<>();

    final StreamConsumer consumer = new StreamConsumer(GlobalEventExecutor.INSTANCE, slowClient) {

        @Override
        public void onNext(HttpObject obj) {
            if (obj instanceof ResponseHeaders) {
                status.compareAndSet(null, ((ResponseHeaders) obj).status());
            }
            super.onNext(obj);
        }

        @Override
        public void onError(Throwable cause) {
            // Will be notified via the 'awaitClose().get()' below.
        }

        @Override
        public void onComplete() {}
    };

    res.subscribe(consumer);

    res.whenComplete().get();
    assertThat(status.get()).isEqualTo(HttpStatus.OK);
    assertThat(consumer.numReceivedBytes()).isEqualTo(STREAMING_CONTENT_LENGTH);
}
 
Example 15
Source File: ServerMaxConnectionAgeTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@CsvSource({ "H2C", "H2" })
@ParameterizedTest
void http2MaxConnectionAge(SessionProtocol protocol) throws InterruptedException {
    final int concurrency = 200;
    final WebClient client = newWebClient(server.uri(protocol));

    // Make sure that a connection is opened.
    assertThat(client.get("/").aggregate().join().status()).isEqualTo(OK);
    assertThat(opened).hasValue(1);

    final Supplier<HttpResponse> execute = () -> client.get("/");

    await().untilAsserted(() -> {
        final List<HttpResponse> responses = IntStream.range(0, concurrency)
                                                      .mapToObj(unused -> execute.get())
                                                      .collect(toImmutableList());
        Throwable cause = null;
        for (HttpResponse response : responses) {
            try {
                response.aggregate().join();
            } catch (Exception e) {
                cause = e;
                break;
            }
        }

        assertThat(cause)
                .isInstanceOf(CompletionException.class)
                .hasCauseInstanceOf(UnprocessedRequestException.class)
                .hasRootCauseInstanceOf(GoAwayReceivedException.class);
    });

    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(meterRegistry))
                .hasEntrySatisfying(
                        "armeria.server.connections.lifespan.percentile#value{phi=0,protocol=" +
                        protocol.uriText() + '}',
                        value -> {
                            assertThat(value * 1000)
                                    .isBetween(MAX_CONNECTION_AGE - 200.0, MAX_CONNECTION_AGE + 3000.0);
                        })
                .hasEntrySatisfying(
                        "armeria.server.connections.lifespan.percentile#value{phi=1,protocol=" +
                        protocol.uriText() + '}',
                        value -> {
                            assertThat(value * 1000)
                                    .isBetween(MAX_CONNECTION_AGE - 200.0, MAX_CONNECTION_AGE + 3000.0);
                        }
                )
                .hasEntrySatisfying(
                        "armeria.server.connections.lifespan#count{protocol=" + protocol.uriText() + '}',
                        value -> assertThat(value).isEqualTo(closed.get()));
    });
}