Java Code Examples for com.linecorp.armeria.client.ClientFactory#close()

The following examples show how to use com.linecorp.armeria.client.ClientFactory#close() . 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: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testSocks4BasicCase() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    final AggregatedHttpResponse response = responseFuture.join();

    assertThat(response.status()).isEqualTo(OK);
    assertThat(response.contentUtf8()).isEqualTo(SUCCESS_RESPONSE);
    assertThat(numSuccessfulProxyRequests).isEqualTo(1);
    clientFactory.close();
}
 
Example 2
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testSocks5BasicCase() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks5(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    final AggregatedHttpResponse response = responseFuture.join();
    assertThat(response.status()).isEqualTo(OK);
    assertThat(response.contentUtf8()).isEqualTo(SUCCESS_RESPONSE);
    assertThat(numSuccessfulProxyRequests).isEqualTo(1);
    clientFactory.close();
}
 
Example 3
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testH1CProxyBasicCase() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.connect(httpProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    final AggregatedHttpResponse response = responseFuture.join();
    assertThat(response.status()).isEqualTo(OK);
    assertThat(response.contentUtf8()).isEqualTo(SUCCESS_RESPONSE);
    assertThat(numSuccessfulProxyRequests).isEqualTo(1);
    clientFactory.close();
}
 
Example 4
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testHttpsProxyBasicCase() throws Exception {
    final ClientFactory clientFactory =
            ClientFactory.builder().tlsNoVerify().proxyConfig(
                    ProxyConfig.connect(httpsProxyServer.address(), true)).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    final AggregatedHttpResponse response = responseFuture.join();
    assertThat(response.status()).isEqualTo(OK);
    assertThat(response.contentUtf8()).isEqualTo(SUCCESS_RESPONSE);
    assertThat(numSuccessfulProxyRequests).isEqualTo(1);
    clientFactory.close();
}
 
Example 5
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxyWithH2C() throws Exception {
    final int numRequests = 5;
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(SessionProtocol.H2C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();

    final List<CompletableFuture<AggregatedHttpResponse>> responseFutures = new ArrayList<>();
    for (int i = 0; i < numRequests; i++) {
        responseFutures.add(webClient.get(PROXY_PATH).aggregate());
    }
    await().until(() -> responseFutures.stream().allMatch(CompletableFuture::isDone));
    assertThat(responseFutures.stream().map(CompletableFuture::join))
            .allMatch(response -> response.contentUtf8().equals(SUCCESS_RESPONSE));
    assertThat(numSuccessfulProxyRequests).isGreaterThanOrEqualTo(1);
    clientFactory.close();
}
 
Example 6
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxy_protocolUpgrade_notSharableExceptionNotThrown() throws Exception {
    DYNAMIC_HANDLER.setWriteCustomizer((ctx, msg, promise) -> {
        ctx.write(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED), promise);
    });
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(SessionProtocol.HTTP, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    assertThatThrownBy(responseFuture::join).isInstanceOf(CompletionException.class)
                                            .hasCauseInstanceOf(UnprocessedRequestException.class)
                                            .hasRootCauseInstanceOf(ProxyConnectException.class);
    clientFactory.close();
}
 
Example 7
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxy_connectionFailure_throwsException() throws Exception {
    final int unusedPort;
    try (ServerSocket ss = new ServerSocket(0)) {
        unusedPort = ss.getLocalPort();
    }

    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(new InetSocketAddress("127.0.0.1", unusedPort))).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();

    assertThatThrownBy(responseFuture::join).isInstanceOf(CompletionException.class)
                                            .hasMessageContaining("Connection refused")
                                            .hasCauseInstanceOf(UnprocessedRequestException.class)
                                            .hasRootCauseInstanceOf(ConnectException.class);
    clientFactory.close();
}
 
Example 8
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxy_connectionTimeoutFailure_throwsException() throws Exception {
    DYNAMIC_HANDLER.setChannelReadCustomizer((ctx, msg) -> {
        if (msg instanceof DefaultSocks4CommandRequest) {
            ctx.channel().eventLoop().schedule(
                    () -> ctx.fireChannelRead(msg), 50, TimeUnit.MILLISECONDS);
        } else {
            ctx.fireChannelRead(msg);
        }
    });

    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).connectTimeoutMillis(1).build();

    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    assertThatThrownBy(responseFuture::join).isInstanceOf(CompletionException.class)
                                            .hasCauseInstanceOf(UnprocessedRequestException.class)
                                            .hasRootCauseInstanceOf(ProxyConnectException.class);
    clientFactory.close();
}
 
Example 9
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxy_responseFailure_throwsException() throws Exception {
    DYNAMIC_HANDLER.setWriteCustomizer((ctx, msg, promise) -> {
        ctx.write(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED), promise);
    });
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();

    assertThatThrownBy(responseFuture::join).isInstanceOf(CompletionException.class)
                                            .hasCauseInstanceOf(UnprocessedRequestException.class)
                                            .hasRootCauseInstanceOf(ProxyConnectException.class);
    clientFactory.close();
}
 
Example 10
Source File: PrematureClientFactoryCloseTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static void test(Function<CentralDogma, CompletableFuture<?>> watchAction) throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder().build();
    final CentralDogma client = new ArmeriaCentralDogmaBuilder()
            .clientFactory(clientFactory)
            .host("127.0.0.1", dogma.serverAddress().getPort())
            .build();

    final CompletableFuture<?> future = watchAction.apply(client);

    // Wait until the server receives the watch request.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(dogma.dogma().meterRegistry().get()))
                .containsEntry("watches.active#value", 1.0);
    });

    // Close the `ClientFactory` to trigger disconnection.
    clientFactory.close();

    // The watch request should finish without an exception.
    assertThat(future.join()).isNull();

    // Wait until the server detects the watch cancellation.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(dogma.dogma().meterRegistry().get()))
                .containsEntry("watches.active#value", 0.0);
    });
}
 
Example 11
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void clientSocketClosedBeforeHalfClose(String protocol) throws Exception {
    final ClientFactory factory = ClientFactory.builder().build();
    final UnitTestServiceStub stub =
            Clients.builder("gproto+" + protocol + "://127.0.0.1:" + server.httpPort() + '/')
                   .factory(factory)
                   .build(UnitTestServiceStub.class);
    final AtomicReference<SimpleResponse> response = new AtomicReference<>();
    final StreamObserver<SimpleRequest> stream = stub.streamClientCancels(
            new StreamObserver<SimpleResponse>() {
                @Override
                public void onNext(SimpleResponse value) {
                    response.set(value);
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onCompleted() {
                }
            });
    stream.onNext(SimpleRequest.getDefaultInstance());
    await().untilAsserted(() -> assertThat(response).hasValue(SimpleResponse.getDefaultInstance()));
    factory.close();
    await().untilAsserted(() -> assertThat(COMPLETED).hasValue(true));

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StreamClientCancels");
        assertThat(rpcReq.params()).containsExactly(SimpleRequest.getDefaultInstance());
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(protocol.startsWith("h2") ? Code.CANCELLED
                                                                             : Code.UNKNOWN);
    });
}
 
Example 12
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static RequestLog clientSocketClosedAfterHalfCloseBeforeCloseCancels(SessionProtocol protocol)
        throws Exception {

    final ClientFactory factory = ClientFactory.builder().build();
    final UnitTestServiceStub stub =
            Clients.builder(server.uri(protocol, GrpcSerializationFormats.PROTO))
                   .factory(factory)
                   .build(UnitTestServiceStub.class);
    final AtomicReference<SimpleResponse> response = new AtomicReference<>();
    stub.streamClientCancelsBeforeResponseClosedCancels(
            SimpleRequest.getDefaultInstance(),
            new StreamObserver<SimpleResponse>() {
                @Override
                public void onNext(SimpleResponse value) {
                    response.set(value);
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onCompleted() {
                }
            });
    await().untilAsserted(() -> assertThat(response).hasValue(SimpleResponse.getDefaultInstance()));
    factory.close();
    CLIENT_CLOSED.set(true);
    await().untilAsserted(() -> assertThat(COMPLETED).hasValue(true));

    final RequestLog log = requestLogQueue.take();
    assertThat(log.isComplete()).isTrue();
    assertThat(log.requestContent()).isNotNull();
    assertThat(log.responseContent()).isNull();
    final RpcRequest rpcReq = (RpcRequest) log.requestContent();
    assertThat(rpcReq.method()).isEqualTo(
            "armeria.grpc.testing.UnitTestService/StreamClientCancelsBeforeResponseClosedCancels");
    assertThat(rpcReq.params()).containsExactly(SimpleRequest.getDefaultInstance());
    return log;
}
 
Example 13
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testDisabledProxyBasicCase() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(ProxyConfig.direct()).build();
    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    final AggregatedHttpResponse response = responseFuture.join();

    assertThat(response.status()).isEqualTo(OK);
    assertThat(response.contentUtf8()).isEqualTo(SUCCESS_RESPONSE);
    clientFactory.close();
}
 
Example 14
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testProxyWithUserName() throws Exception {
    final String username = "username";
    DYNAMIC_HANDLER.setChannelReadCustomizer((ctx, msg) -> {
        if (msg instanceof DefaultSocks4CommandRequest) {
            assertThat(username).isEqualTo(((DefaultSocks4CommandRequest) msg).userId());
        }
        ctx.fireChannelRead(msg);
    });

    final ClientFactory clientFactory =
            ClientFactory.builder()
                         .proxyConfig(ProxyConfig.socks4(socksProxyServer.address(), username))
                         .build();

    final WebClient webClient = WebClient.builder(H1C, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    final AggregatedHttpResponse response = responseFuture.join();
    assertThat(response.status()).isEqualTo(OK);
    assertThat(response.contentUtf8()).isEqualTo(SUCCESS_RESPONSE);
    assertThat(numSuccessfulProxyRequests).isEqualTo(1);
    clientFactory.close();
}
 
Example 15
Source File: HealthCheckedEndpointGroupTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void closesWhenClientFactoryCloses() {
    final ClientFactory factory = ClientFactory.builder().build();
    final EndpointGroup delegate = Endpoint.of("foo");
    final AsyncCloseableSupport checkerCloseable = AsyncCloseableSupport.of();
    final AtomicInteger newCheckerCount = new AtomicInteger();
    final HealthCheckedEndpointGroup group = new AbstractHealthCheckedEndpointGroupBuilder(delegate) {
        @Override
        protected Function<? super HealthCheckerContext, ? extends AsyncCloseable> newCheckerFactory() {
            return ctx -> {
                ctx.updateHealth(1);
                newCheckerCount.incrementAndGet();
                return checkerCloseable;
            };
        }
    }.clientFactory(factory).build();

    // When the ClientFactory is closed, the health checkers must be closed as well.
    factory.close();
    await().untilAsserted(() -> {
        assertThat(group.isClosed()).isTrue();
        assertThat(group.isClosing()).isTrue();
        assertThat(checkerCloseable.isClosing()).isTrue();
        assertThat(checkerCloseable.isClosed()).isTrue();
    });

    // No more than one checker must be created.
    assertThat(newCheckerCount).hasValue(1);
}