Java Code Examples for io.netty.util.concurrent.Promise#setSuccess()
The following examples show how to use
io.netty.util.concurrent.Promise#setSuccess() .
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: Http2MultiplexedChannelPoolTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void acquire_shouldAcquireAgainIfExistingNotReusable() throws Exception { Channel channel = new EmbeddedChannel(); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); Mockito.when(connectionPool.acquire()).thenReturn(channelPromise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.emptySet(), null); h2Pool.acquire().awaitUninterruptibly(); h2Pool.acquire().awaitUninterruptibly(); Mockito.verify(connectionPool, Mockito.times(2)).acquire(); } finally { channel.close(); } }
Example 2
Source File: Http2MultiplexedChannelPool.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private void cacheConnectionForFutureStreams(Channel stream, MultiplexedChannelRecord multiplexedChannel, Promise<Channel> promise) { Channel parentChannel = stream.parent(); // Before we cache the connection, make sure that exceptions on the connection will remove it from the cache. parentChannel.pipeline().addLast(ReleaseOnExceptionHandler.INSTANCE); connections.add(multiplexedChannel); if (closed.get()) { // Whoops, we were closed while we were setting up. Make sure everything here is cleaned up properly. failAndCloseParent(promise, parentChannel, new IOException("Connection pool was closed while creating a new stream.")); return; } promise.setSuccess(stream); }
Example 3
Source File: MqttClientImpl.java From smartacus-mqtt-broker with Apache License 2.0 | 6 votes |
private void checkSubscribtions(String topic, Promise<Void> promise) { if (!(this.subscriptions.containsKey(topic) && this.subscriptions.get(topic).size() != 0) && this.serverSubscriptions.contains(topic)) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE, false, 0); MqttMessageIdVariableHeader variableHeader = getNewMessageId(); MqttUnsubscribePayload payload = new MqttUnsubscribePayload(Collections.singletonList(topic)); MqttUnsubscribeMessage message = new MqttUnsubscribeMessage(fixedHeader, variableHeader, payload); MqttPendingUnsubscription pendingUnsubscription = new MqttPendingUnsubscription(promise, topic, message); this.pendingServerUnsubscribes.put(variableHeader.messageId(), pendingUnsubscription); pendingUnsubscription.startRetransmissionTimer(this.eventLoop.next(), this::sendAndFlushPacket); this.sendAndFlushPacket(message); } else { promise.setSuccess(null); } }
Example 4
Source File: DefaultNameResolver.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override protected void doResolve(String inetHost, Promise<InetAddress> promise) throws Exception { try { promise.setSuccess(SocketUtils.addressByName(inetHost)); } catch (UnknownHostException e) { promise.setFailure(e); } }
Example 5
Source File: ReleaseOnceChannelPool.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public Future<Void> release(Channel channel, Promise<Void> promise) { if (shouldRelease(channel)) { return delegate.release(channel, promise); } else { return promise.setSuccess(null); } }
Example 6
Source File: ChicagoNode.java From xio with Apache License 2.0 | 5 votes |
private SimpleChannelInboundHandler<ChicagoMessage> newReader() { return new SimpleChannelInboundHandler<ChicagoMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ChicagoMessage msg) throws Exception { Promise<WriteResult> result = resultMap.get(msg.id); if (result != null) { System.out.println("Got result for id " + msg.id); result.setSuccess(new WriteResult()); } else { System.out.println("Couldn't find result for id " + msg.id); } } }; }
Example 7
Source File: Http2MultiplexedChannelPoolTest.java From ambry with Apache License 2.0 | 5 votes |
/** * Channel acquire and release test. */ @Test public void streamChannelAcquireReleaseTest() throws Exception { Channel channel = newHttp2Channel(); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); Mockito.when(connectionPool.acquire()).thenReturn(channelPromise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, new HashSet<>(), null, http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer); Channel streamChannel1 = h2Pool.acquire().awaitUninterruptibly().getNow(); assertTrue(streamChannel1 instanceof Http2StreamChannel); Mockito.verify(connectionPool, Mockito.times(1)).acquire(); Channel streamChannel2 = h2Pool.acquire().awaitUninterruptibly().getNow(); assertTrue(streamChannel2 instanceof Http2StreamChannel); Mockito.verify(connectionPool, Mockito.times(1)).acquire(); // Verify number of numOfAvailableStreams MultiplexedChannelRecord multiplexedChannelRecord = streamChannel2.parent().attr(Http2MultiplexedChannelPool.MULTIPLEXED_CHANNEL).get(); assertEquals(maxConcurrentStreamsPerConnection - 2, multiplexedChannelRecord.getNumOfAvailableStreams().get()); h2Pool.release(streamChannel1).getNow(); h2Pool.release(streamChannel2).getNow(); assertEquals(maxConcurrentStreamsPerConnection, multiplexedChannelRecord.getNumOfAvailableStreams().get()); } finally { channel.close(); } }
Example 8
Source File: Http2MultiplexedChannelPool.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause, Promise<Void> resultPromise) { if (parentChannel.parent() != null) { // This isn't a parent channel. Notify it that something is wrong. Exception exception = new IOException("Channel (" + parentChannel + ") is not a parent channel. It will be closed, " + "but cannot be released within this pool."); log.error(exception::getMessage); parentChannel.close(); return resultPromise.setFailure(exception); } MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get(); // We may not have a multiplexed channel if the parent channel hasn't been fully initialized. if (multiplexedChannel != null) { if (cause == null) { multiplexedChannel.closeChildChannels(); } else { multiplexedChannel.closeChildChannels(cause); } connections.remove(multiplexedChannel); } parentChannel.close(); if (parentChannel.attr(RELEASED).getAndSet(Boolean.TRUE) == null) { return connectionPool.release(parentChannel, resultPromise); } return resultPromise.setSuccess(null); }
Example 9
Source File: Http2MultiplexedChannelPool.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public Future<Void> release(Channel childChannel, Promise<Void> promise) { if (childChannel.parent() == null) { // This isn't a child channel. Oddly enough, this is "expected" and is handled properly by the // BetterFixedChannelPool AS LONG AS we return an IllegalArgumentException via the promise. closeAndReleaseParent(childChannel); return promise.setFailure(new IllegalArgumentException("Channel (" + childChannel + ") is not a child channel.")); } Channel parentChannel = childChannel.parent(); MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get(); if (multiplexedChannel == null) { // This is a child channel, but there is no attached multiplexed channel, which there should be if it was from // this pool. Close it and log an error. Exception exception = new IOException("Channel (" + childChannel + ") is not associated with any channel records. " + "It will be closed, but cannot be released within this pool."); log.error(exception::getMessage); childChannel.close(); return promise.setFailure(exception); } multiplexedChannel.closeAndReleaseChild(childChannel); if (multiplexedChannel.canBeClosedAndReleased()) { // We just closed the last stream in a connection that has reached the end of its life. return closeAndReleaseParent(parentChannel, null, promise); } return promise.setSuccess(null); }
Example 10
Source File: TunnelSocketFrameHandler.java From arthas with Apache License 2.0 | 5 votes |
private void openTunnel(ChannelHandlerContext ctx, String clientConnectionId) { Optional<ClientConnectionInfo> infoOptional = this.tunnelServer.findClientConnection(clientConnectionId); if (infoOptional.isPresent()) { ClientConnectionInfo info = infoOptional.get(); logger.info("openTunnel clientConnectionId:" + clientConnectionId); Promise<Channel> promise = info.getPromise(); promise.setSuccess(ctx.channel()); } else { logger.error("Can not find client connection by id: {}", clientConnectionId); } }
Example 11
Source File: HttpOrHttp2ChannelPoolTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test(timeout = 5_000) public void protocolConfigInProgress_poolClosed_closesChannelAndDelegatePoolOnAcquireSuccess() throws InterruptedException { Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); // initiate the configuration httpOrHttp2ChannelPool.acquire(); // close the pool before the config can complete (we haven't completed acquirePromise yet) httpOrHttp2ChannelPool.close(); Thread.sleep(500); Channel channel = new NioSocketChannel(); eventLoopGroup.register(channel); try { channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1)); acquirePromise.setSuccess(channel); assertThat(channel.closeFuture().await().isDone()).isTrue(); Thread.sleep(500); verify(mockDelegatePool).release(eq(channel)); verify(mockDelegatePool).close(); } finally { channel.close(); } }
Example 12
Source File: NettyUtils.java From ambry with Apache License 2.0 | 5 votes |
/** * Creates a {@link BiConsumer} that notifies the promise of any failures either via the {@link Throwable} passed into the * BiConsumer of as a result of running the successFunction. * * @param successFunction Function called to process the successful result and map it into the result to notify the promise * with. * @param promise Promise to notify of success or failure. * @param <SuccessT> Success type. * @param <PromiseT> Type being fulfilled by the promise. * @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method. */ public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> promiseNotifyingBiConsumer( Function<SuccessT, PromiseT> successFunction, Promise<PromiseT> promise) { return (success, fail) -> { if (fail != null) { promise.setFailure(fail); } else { try { promise.setSuccess(successFunction.apply(success)); } catch (Throwable e) { promise.setFailure(e); } } }; }
Example 13
Source File: SimpleChannelPool.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private void releaseAndOffer(Channel channel, Promise<Void> promise) throws Exception { // 把channel添加到deque中 if (offerChannel(channel)) { // 执行channelPoolHandler的释放逻辑 handler.channelReleased(channel); promise.setSuccess(null); } else { // 如果把channel添加到deque中失败就关闭channel并发布promise失败事件 closeAndFail(channel, FULL_EXCEPTION, promise); } }
Example 14
Source File: SimpleChannelPool.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
/** * Adds the channel back to the pool only if the channel is healthy.仅当通道是健康的时,才将通道添加回池。 * @param channel the channel to put back to the pool * @param promise offer operation promise. * @param future the future that contains information fif channel is healthy or not. * @throws Exception in case when failed to notify handler about release operation. */ private void releaseAndOfferIfHealthy(Channel channel, Promise<Void> promise, Future<Boolean> future) throws Exception { if (future.getNow()) { //channel turns out to be healthy, offering and releasing it.频道被证明是健康的,提供和释放它。 releaseAndOffer(channel, promise); } else { //channel not healthy, just releasing it.通道不健康,只是释放它。 handler.channelReleased(channel); promise.setSuccess(null); } }
Example 15
Source File: Http2MultiplexedChannelPool.java From ambry with Apache License 2.0 | 5 votes |
private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause, Promise<Void> resultPromise) { if (parentChannel.parent() != null) { // This isn't a parent channel. Notify it that something is wrong. Exception exception = new IOException( "Channel (" + parentChannel + ") is not a parent channel. It will be closed, " + "but cannot be released within this pool."); log.error(exception.getMessage()); parentChannel.close(); return resultPromise.setFailure(exception); } MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get(); // We may not have a multiplexed channel if the parent channel hasn't been fully initialized. if (multiplexedChannel != null) { if (cause == null) { multiplexedChannel.closeChildChannels(); } else { multiplexedChannel.closeChildChannels(cause); } parentConnections.remove(multiplexedChannel); } parentChannel.close(); if (parentChannel.attr(PARENT_CHANNEL_RELEASED).getAndSet(Boolean.TRUE) == null) { return parentConnectionPool.release(parentChannel, resultPromise); } return resultPromise.setSuccess(null); }
Example 16
Source File: SniHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public Future<SslContext> map(String input, Promise<SslContext> promise) { final SslContext context; try { context = mapping.map(input); } catch (Throwable cause) { return promise.setFailure(cause); } return promise.setSuccess(context); }
Example 17
Source File: DnsNameResolver.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
/** * Hook designed for extensibility so one can pass a different cache on each resolution attempt * instead of using the global one. */ protected void doResolveAll(String inetHost, DnsRecord[] additionals, Promise<List<InetAddress>> promise, DnsCache resolveCache) throws Exception { if (inetHost == null || inetHost.isEmpty()) { // If an empty hostname is used we should use "localhost", just like InetAddress.getAllByName(...) does. promise.setSuccess(Collections.singletonList(loopbackAddress())); return; } final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost); if (bytes != null) { // The unresolvedAddress was created via a String that contains an ipaddress. promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes))); return; } final String hostname = hostname(inetHost); InetAddress hostsFileEntry = resolveHostsFileEntry(hostname); if (hostsFileEntry != null) { promise.setSuccess(Collections.singletonList(hostsFileEntry)); return; } if (!doResolveAllCached(hostname, additionals, promise, resolveCache)) { doResolveAllUncached(hostname, additionals, promise, resolveCache); } }
Example 18
Source File: NoopAddressResolver.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
@Override protected void doResolveAll( SocketAddress unresolvedAddress, Promise<List<SocketAddress>> promise) throws Exception { promise.setSuccess(Collections.singletonList(unresolvedAddress)); }
Example 19
Source File: NoopAddressResolver.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
@Override protected void doResolve(SocketAddress unresolvedAddress, Promise<SocketAddress> promise) throws Exception { promise.setSuccess(unresolvedAddress); }
Example 20
Source File: RequestContextTest.java From armeria with Apache License 2.0 | 4 votes |
@Test public void contextAwareEventExecutor() throws Exception { when(channel.eventLoop()).thenReturn(eventLoop.get()); final RequestContext context = createContext(); final Set<Integer> callbacksCalled = Collections.newSetFromMap(new ConcurrentHashMap<>()); final EventExecutor executor = context.contextAwareEventLoop(); final CountDownLatch latch = new CountDownLatch(18); executor.execute(() -> checkCallback(1, context, callbacksCalled, latch)); executor.schedule(() -> checkCallback(2, context, callbacksCalled, latch), 0, TimeUnit.SECONDS); executor.schedule(() -> { checkCallback(2, context, callbacksCalled, latch); return "success"; }, 0, TimeUnit.SECONDS); executor.scheduleAtFixedRate(() -> checkCallback(3, context, callbacksCalled, latch), 0, 1000, TimeUnit.SECONDS); executor.scheduleWithFixedDelay(() -> checkCallback(4, context, callbacksCalled, latch), 0, 1000, TimeUnit.SECONDS); executor.submit(() -> checkCallback(5, context, callbacksCalled, latch)); executor.submit(() -> checkCallback(6, context, callbacksCalled, latch), "success"); executor.submit(() -> { checkCallback(7, context, callbacksCalled, latch); return "success"; }); executor.invokeAll(makeTaskList(8, 10, context, callbacksCalled, latch)); executor.invokeAll(makeTaskList(11, 12, context, callbacksCalled, latch), 10000, TimeUnit.SECONDS); executor.invokeAny(makeTaskList(13, 13, context, callbacksCalled, latch)); executor.invokeAny(makeTaskList(14, 14, context, callbacksCalled, latch), 10000, TimeUnit.SECONDS); final Promise<String> promise = executor.newPromise(); promise.addListener(f -> checkCallback(15, context, callbacksCalled, latch)); promise.setSuccess("success"); executor.newSucceededFuture("success") .addListener(f -> checkCallback(16, context, callbacksCalled, latch)); executor.newFailedFuture(new IllegalArgumentException()) .addListener(f -> checkCallback(17, context, callbacksCalled, latch)); final ProgressivePromise<String> progressivePromise = executor.newProgressivePromise(); progressivePromise.addListener(f -> checkCallback(18, context, callbacksCalled, latch)); progressivePromise.setSuccess("success"); latch.await(); eventLoop.get().shutdownGracefully(); await().untilAsserted(() -> { assertThat(callbacksCalled).containsExactlyElementsOf(IntStream.rangeClosed(1, 18) .boxed()::iterator); }); }