com.linecorp.armeria.common.CommonPools Java Examples
The following examples show how to use
com.linecorp.armeria.common.CommonPools.
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: AbstractAccessTokenProvider.java From curiostack with MIT License | 6 votes |
AbstractAccessTokenProvider(WebClient googleApisClient, Clock clock) { this.googleApisClient = googleApisClient; this.clock = clock; cachedAccessToken = new AsyncRefreshingValue<>( () -> this.refresh(Type.ACCESS_TOKEN), AbstractAccessTokenProvider::extractExpirationTime, CommonPools.workerGroup().next(), clock); cachedIdToken = new AsyncRefreshingValue<>( () -> this.refresh(Type.ID_TOKEN), AbstractAccessTokenProvider::extractExpirationTime, CommonPools.workerGroup().next(), clock); }
Example #2
Source File: HttpResponseWrapperTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void headersAndData() throws Exception { final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next()); final HttpResponseWrapper wrapper = httpResponseWrapper(res); assertThat(wrapper.tryWrite( ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_LENGTH, "foo".length()))).isTrue(); assertThat(wrapper.tryWrite(HttpData.ofUtf8("foo"))).isTrue(); wrapper.close(); StepVerifier.create(res) .expectNext(ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_LENGTH, 3)) .expectNext(HttpData.ofUtf8("foo")) .expectComplete() .verify(); }
Example #3
Source File: DefaultTimeoutControllerTest.java From armeria with Apache License 2.0 | 6 votes |
@BeforeEach void setUp() { isTimeout = false; final TimeoutTask timeoutTask = new TimeoutTask() { @Override public boolean canSchedule() { return true; } @Override public void run() { isTimeout = true; } }; timeoutController = new StatusCheckedTaskTimeoutController( new DefaultTimeoutController(timeoutTask, CommonPools.workerGroup().next())); }
Example #4
Source File: DefaultTimeoutControllerTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void disabledTimeoutTask() { final DefaultTimeoutController timeoutController = new DefaultTimeoutController( new TimeoutTask() { @Override public boolean canSchedule() { return false; } @Override public void run() { throw new Error("Should not reach here"); } }, CommonPools.workerGroup().next()); assertThat(timeoutController.scheduleTimeout(1000)).isFalse(); assertThat(timeoutController.extendTimeout(2000)).isFalse(); assertThat(timeoutController.resetTimeout(3000)).isFalse(); assertThat(timeoutController.timeoutNow()).isFalse(); assertThat(timeoutController.cancelTimeout()).isFalse(); }
Example #5
Source File: DefaultHttpResponseTest.java From armeria with Apache License 2.0 | 6 votes |
/** * The aggregation future must be completed even if the response being aggregated has been aborted. */ @ParameterizedTest @ValueSource(booleans = { true, false }) void abortedAggregation(boolean executorSpecified) { final Thread mainThread = Thread.currentThread(); final HttpResponseWriter res = HttpResponse.streaming(); final CompletableFuture<AggregatedHttpResponse> future; // Practically same execution, but we need to test the both case due to code duplication. if (executorSpecified) { future = res.aggregate(CommonPools.workerGroup().next()); } else { future = res.aggregate(); } final AtomicReference<Thread> callbackThread = new AtomicReference<>(); assertThatThrownBy(() -> { final CompletableFuture<AggregatedHttpResponse> f = future.whenComplete((unused, cause) -> callbackThread.set(Thread.currentThread())); res.abort(); f.join(); }).hasCauseInstanceOf(AbortedStreamException.class); assertThat(callbackThread.get()).isNotSameAs(mainThread); }
Example #6
Source File: HttpResponseWrapperTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void dataIsIgnoreAfterSecondHeaders() throws Exception { final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next()); final HttpResponseWrapper wrapper = httpResponseWrapper(res); assertThat(wrapper.tryWrite(ResponseHeaders.of(200))).isTrue(); assertThat(wrapper.tryWrite( HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))).isTrue(); // Second header is trailers. assertThat(wrapper.tryWrite(HttpData.ofUtf8("foo"))).isFalse(); wrapper.close(); StepVerifier.create(res) .expectNext(ResponseHeaders.of(200)) .expectNext(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz")) .expectComplete() .verify(); }
Example #7
Source File: PublicKeysManager.java From curiostack with MIT License | 6 votes |
@SuppressWarnings("ConstructorLeaksThis") public PublicKeysManager(@Provided Clock clock, String publicKeysUrl) { this.clock = clock; URI uri = URI.create(publicKeysUrl); path = uri.getPath(); httpClient = WebClient.builder(uri.getScheme() + "://" + uri.getAuthority()) .decorator(LoggingClient.builder().newDecorator()) .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) .build(); keysCache = new AsyncRefreshingValue<>( this::refresh, CachedPublicKeys::expirationTime, CommonPools.workerGroup().next(), clock); }
Example #8
Source File: PooledHttpStreamMessageTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void subscribeWithPooledObjects_executorOptions() { final DrainingSubscriber<HttpObject> objects = new DrainingSubscriber<>(); PooledHttpResponse.of(response()).subscribeWithPooledObjects(objects, CommonPools.workerGroup().next(), SubscriptionOption.NOTIFY_CANCELLATION); assertThat(objects.result().join()) .filteredOn(HttpData.class::isInstance) .allSatisfy(data -> { assertThat(data).isInstanceOfSatisfying( PooledHttpData.class, pooled -> { assertThat(pooled.content().isDirect()).isTrue(); pooled.close(); }); }); }
Example #9
Source File: RedisModule.java From curiostack with MIT License | 6 votes |
@Provides @Singleton static RedisClusterClient redisClusterClient( RedisConfig config, MeterRegistry registry, Tracing tracing) { RedisClusterClient client = RedisClusterClient.create( DefaultClientResources.builder() .eventExecutorGroup(CommonPools.workerGroup()) .eventLoopGroupProvider(ArmeriaEventLoopGroupProvider.INSTANCE) .commandLatencyCollector( new MicrometerCommandLatencyCollector(DEFAULT_METER_ID_PREFIX, registry)) .tracing(BraveTracing.create(tracing)) .build(), config.getUrl()); client.setOptions(ClusterClientOptions.builder().validateClusterNodeMembership(false).build()); return client; }
Example #10
Source File: HttpResponseWrapperTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void splitTrailersIsIgnored() throws Exception { final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next()); final HttpResponseWrapper wrapper = httpResponseWrapper(res); assertThat(wrapper.tryWrite(ResponseHeaders.of(200))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("qux"), "quux"))).isFalse(); wrapper.close(); StepVerifier.create(res) .expectNext(ResponseHeaders.of(200)) .expectNext(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz")) .expectComplete() .verify(); }
Example #11
Source File: PooledHttpStreamMessageTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void subscribe_executorOptions() { final DrainingSubscriber<HttpObject> objects = new DrainingSubscriber<>(); PooledHttpResponse.of(response()).subscribe(objects, CommonPools.workerGroup().next(), SubscriptionOption.NOTIFY_CANCELLATION); assertThat(objects.result().join()) .filteredOn(HttpData.class::isInstance) .allSatisfy(data -> { assertThat(data).isInstanceOfSatisfying( PooledHttpData.class, pooled -> { assertThat(pooled.content().isDirect()).isFalse(); pooled.close(); }); }); }
Example #12
Source File: HttpResponseWrapperTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void splitTrailersAfterDataIsIgnored() throws Exception { final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next()); final HttpResponseWrapper wrapper = httpResponseWrapper(res); assertThat(wrapper.tryWrite( ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_LENGTH, "foo".length()))).isTrue(); assertThat(wrapper.tryWrite(HttpData.ofUtf8("foo"))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("qux"), "quux"))).isFalse(); wrapper.close(); StepVerifier.create(res) .expectNext(ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_LENGTH, 3)) .expectNext(HttpData.ofUtf8("foo")) .expectNext(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz")) .expectComplete() .verify(); }
Example #13
Source File: HttpResponseWrapperTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void informationalHeadersHeadersDataAndTrailers() throws Exception { final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next()); final HttpResponseWrapper wrapper = httpResponseWrapper(res); assertThat(wrapper.tryWrite(ResponseHeaders.of(100))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("a"), "b"))).isTrue(); assertThat(wrapper.tryWrite( ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_LENGTH, "foo".length()))).isTrue(); assertThat(wrapper.tryWrite(HttpData.ofUtf8("foo"))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))).isTrue(); wrapper.close(); StepVerifier.create(res) .expectNext(ResponseHeaders.of(100)) .expectNext(HttpHeaders.of(HttpHeaderNames.of("a"), "b")) .expectNext(ResponseHeaders.of(HttpStatus.OK, HttpHeaderNames.CONTENT_LENGTH, 3)) .expectNext(HttpData.ofUtf8("foo")) .expectNext(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz")) .expectComplete() .verify(); }
Example #14
Source File: TestDnsServer.java From armeria with Apache License 2.0 | 6 votes |
public TestDnsServer(Map<DnsQuestion, DnsResponse> responses, @Nullable ChannelInboundHandlerAdapter beforeDnsServerHandler) { this.responses = ImmutableMap.copyOf(responses); final Bootstrap b = new Bootstrap(); b.channel(TransportType.datagramChannelType(CommonPools.workerGroup())); b.group(CommonPools.workerGroup()); b.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); p.addLast(new DatagramDnsQueryDecoder()); p.addLast(new DatagramDnsResponseEncoder()); if (beforeDnsServerHandler != null) { p.addLast(beforeDnsServerHandler); } p.addLast(new DnsServerHandler()); } }); channel = b.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel(); }
Example #15
Source File: HttpFileTest.java From armeria with Apache License 2.0 | 6 votes |
@Test public void additionalHeaders() throws Exception { final HttpFile f = HttpFile.builder(ClassLoader.getSystemClassLoader(), "java/lang/Object.class") .addHeader("foo", "1") .addHeader("foo", "2") .setHeader("bar", "3") .contentType(MediaType.PLAIN_TEXT_UTF_8) .cacheControl(ServerCacheControl.REVALIDATED) .build(); // Make sure content-type auto-detection is disabled. assertThat(((AbstractHttpFile) f).contentType()).isNull(); // Make sure all additional headers are set as expected. final HttpHeaders headers = f.readHeaders(CommonPools.blockingTaskExecutor()).join(); assertThat(headers).isNotNull(); assertThat(headers.getAll(HttpHeaderNames.of("foo"))).containsExactly("1", "2"); assertThat(headers.getAll(HttpHeaderNames.of("bar"))).containsExactly("3"); assertThat(headers.getAll(HttpHeaderNames.CONTENT_TYPE)) .containsExactly(MediaType.PLAIN_TEXT_UTF_8.toString()); assertThat(headers.getAll(HttpHeaderNames.CACHE_CONTROL)) .containsExactly(ServerCacheControl.REVALIDATED.asHeaderValue()); }
Example #16
Source File: PooledHttpStreamMessageTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void subscribeWithPooledObjects_executor() { final DrainingSubscriber<HttpObject> objects = new DrainingSubscriber<>(); PooledHttpResponse.of(response()).subscribeWithPooledObjects(objects, CommonPools.workerGroup().next()); assertThat(objects.result().join()) .filteredOn(HttpData.class::isInstance) .allSatisfy(data -> { assertThat(data).isInstanceOfSatisfying( PooledHttpData.class, pooled -> { assertThat(pooled.content().isDirect()).isTrue(); pooled.close(); }); }); }
Example #17
Source File: HttpFileTest.java From armeria with Apache License 2.0 | 5 votes |
@Test public void leadingSlashInResourcePath() throws Exception { final HttpFile f = HttpFile.of(ClassLoader.getSystemClassLoader(), "/java/lang/Object.class"); final HttpFileAttributes attrs = f.readAttributes(CommonPools.blockingTaskExecutor()).join(); assertThat(attrs).isNotNull(); assertThat(attrs.length()).isPositive(); }
Example #18
Source File: DefaultTimeoutControllerTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void shouldHaveTimeoutTask() { final TimeoutController emptyTaskTimeoutController = new DefaultTimeoutController(CommonPools.workerGroup().next()); assertThatThrownBy(() -> emptyTaskTimeoutController.extendTimeout(100)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("setTimeoutTask(timeoutTask) is not called yet"); }
Example #19
Source File: EventLoopCheckingFutureTest.java From armeria with Apache License 2.0 | 5 votes |
private void testBlockingOperationOffEventLoop(EventLoopCheckingFutureTask task) throws Exception { final EventLoopCheckingFuture<String> future = new EventLoopCheckingFuture<>(); final Future<?> submitFuture = CommonPools.blockingTaskExecutor() .submit(() -> task.run(future)); // Give time to make sure the task is invoked before future.complete() below. Thread.sleep(500); // Complete the future and ensure the logger was invoked. future.complete("complete"); submitFuture.get(); verify(appender, atLeast(0)).doAppend(eventCaptor.capture()); assertThat(eventCaptor.getAllValues()).noneSatisfy(this::assertWarned); }
Example #20
Source File: PooledHttpStreamMessageTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void subscribe_executor() { final DrainingSubscriber<HttpObject> objects = new DrainingSubscriber<>(); PooledHttpResponse.of(response()).subscribe(objects, CommonPools.workerGroup().next()); assertThat(objects.result().join()) .filteredOn(HttpData.class::isInstance) .allSatisfy(data -> { assertThat(data).isInstanceOfSatisfying( PooledHttpData.class, pooled -> { assertThat(pooled.content().isDirect()).isFalse(); pooled.close(); }); }); }
Example #21
Source File: PooledHttpResponseTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void aggregateWithPooledObjects_executor() { try (PooledAggregatedHttpResponse agg = PooledHttpResponse.of(response()) .aggregateWithPooledObjects(CommonPools.workerGroup().next()) .join()) { assertThat(agg.content().content().isDirect()).isTrue(); } }
Example #22
Source File: PooledHttpResponseTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void aggregateWithPooledObjects_executorAlloc() { try (PooledAggregatedHttpResponse agg = PooledHttpResponse.of(response()) .aggregateWithPooledObjects(CommonPools.workerGroup().next(), ByteBufAllocator.DEFAULT).join()) { assertThat(agg.content().content().isDirect()).isTrue(); } }
Example #23
Source File: PooledHttpResponseTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void aggregate_executor() { final AggregatedHttpResponse agg = PooledHttpResponse.of(response()) .aggregate(CommonPools.workerGroup().next()).join(); assertThat(agg.content()).isNotInstanceOf(PooledHttpData.class); }
Example #24
Source File: PooledHttpRequestTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void aggregateWithPooledObjects_executor() { try (PooledAggregatedHttpRequest agg = PooledHttpRequest.of(request()) .aggregateWithPooledObjects(CommonPools.workerGroup().next()) .join()) { assertThat(agg.content().content().isDirect()).isTrue(); } }
Example #25
Source File: PooledHttpRequestTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void aggregateWithPooledObjects_executorAlloc() { try (PooledAggregatedHttpRequest agg = PooledHttpRequest.of(request()) .aggregateWithPooledObjects(CommonPools.workerGroup().next(), ByteBufAllocator.DEFAULT).join()) { assertThat(agg.content().content().isDirect()).isTrue(); } }
Example #26
Source File: HealthCheckedEndpointGroupTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void delegateUpdateCandidatesWhileCreatingHealthCheckedEndpointGroup() { final MockEndpointGroup delegate = new MockEndpointGroup(); final CompletableFuture<List<Endpoint>> future = delegate.whenReady(); future.complete(ImmutableList.of(Endpoint.of("127.0.0.1", 8080), Endpoint.of("127.0.0.1", 8081))); final CountDownLatch latch = new CountDownLatch(1); // Schedule the task which updates the endpoint one second later to ensure that the change is happening // while creating the HealthCheckedEndpointGroup. final EventLoopGroup executors = CommonPools.workerGroup(); executors.schedule( () -> { delegate.set(Endpoint.of("127.0.0.1", 8082)); latch.countDown(); }, 1, TimeUnit.SECONDS); new AbstractHealthCheckedEndpointGroupBuilder(delegate) { @Override protected Function<? super HealthCheckerContext, ? extends AsyncCloseable> newCheckerFactory() { return (Function<HealthCheckerContext, AsyncCloseable>) ctx -> { // Call updateHealth *after* the endpoint is changed so that // snapshot.forEach(ctx -> ctx.initialCheckFuture.join()); performs the next action. new Thread(() -> { try { Thread.sleep(2000); latch.await(); } catch (InterruptedException e) { // Ignore } ctx.updateHealth(1); }).start(); return AsyncCloseableSupport.of(); }; } }.build(); }
Example #27
Source File: HttpResponseWrapperTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void headersAndTrailers() throws Exception { final DecodedHttpResponse res = new DecodedHttpResponse(CommonPools.workerGroup().next()); final HttpResponseWrapper wrapper = httpResponseWrapper(res); assertThat(wrapper.tryWrite(ResponseHeaders.of(200))).isTrue(); assertThat(wrapper.tryWrite(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz"))).isTrue(); wrapper.close(); StepVerifier.create(res) .expectNext(ResponseHeaders.of(200)) .expectNext(HttpHeaders.of(HttpHeaderNames.of("bar"), "baz")) .expectComplete() .verify(); }
Example #28
Source File: DnsEndpointGroupBuilder.java From armeria with Apache License 2.0 | 5 votes |
final EventLoop eventLoop() { if (eventLoop != null) { return eventLoop; } else { return CommonPools.workerGroup().next(); } }
Example #29
Source File: GrpcClientTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void credentialsUnaryCall() { final TestServiceBlockingStub stub = // Explicitly construct URL to better test authority. Clients.builder("gproto+http://localhost:" + server.httpPort()) .decorator(LoggingClient.builder().newDecorator()) .build(TestServiceBlockingStub.class) .withCallCredentials( new CallCredentials() { @Override public void applyRequestMetadata(RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { assertThat(requestInfo.getMethodDescriptor()) .isEqualTo(TestServiceGrpc.getEmptyCallMethod()); assertThat(requestInfo.getAuthority()) .isEqualTo("localhost:" + server.httpPort()); assertThat(requestInfo.getSecurityLevel()) .isEqualTo(SecurityLevel.NONE); assertThat(appExecutor).isEqualTo(CommonPools.blockingTaskExecutor()); CommonPools.blockingTaskExecutor().schedule(() -> { final Metadata metadata = new Metadata(); metadata.put(TestServiceImpl.EXTRA_HEADER_KEY, "token"); applier.apply(metadata); }, 100, TimeUnit.MILLISECONDS); } @Override public void thisUsesUnstableApi() { } }); assertThat(stub.emptyCall(EMPTY)).isNotNull(); final HttpHeaders clientHeaders = CLIENT_HEADERS_CAPTURE.get(); assertThat(clientHeaders.get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("token"); }
Example #30
Source File: BraveServiceIntegrationTest.java From armeria with Apache License 2.0 | 5 votes |
HttpResponse asyncResponse(Consumer<CompletableFuture<HttpResponse>> completeResponse) { final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>(); final HttpResponse res = HttpResponse.from(responseFuture); CommonPools.workerGroup().next().submit( () -> completeResponse.accept(responseFuture)); return res; }