io.netty.util.concurrent.Promise Java Examples

The following examples show how to use io.netty.util.concurrent.Promise. 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: AbstractExecutor.java    From bitchat with Apache License 2.0 6 votes vote down vote up
@Override
public Future<T> asyncExecute(Promise<T> promise, Object... request) {
    if (promise == null) {
        throw new IllegalArgumentException("promise should not be null");
    }
    // async execute
    eventExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                T response = doExecute(request);
                promise.setSuccess(response);
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }
    });
    // return the promise back
    return promise;
}
 
Example #2
Source File: ResponsePromise.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param retryPolicy     the policy for retries
 * @param connectionState which contains current connection details
 * @param retryHandler    handler for retries
 */
public ResponsePromise(RetryPolicy retryPolicy, ConnectionState connectionState, RetryHandler retryHandler) {
  this.connectionState = connectionState;
  this.retryHandler = retryHandler;
  this.retryPolicy = retryPolicy;

  promiseHandler = new GenericFutureListener<Promise<T>>() {
    @Override
    public void operationComplete(Promise<T> future) throws Exception {
      handlePromise(future);
    }
  };

  this.connectionFailHandler = new ConnectionFailHandler() {
    @Override
    public void catchException(IOException exception) {
      handleRetry(exception);
    }
  };
}
 
Example #3
Source File: SslHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Performs TLS renegotiation.
 */
public Future<Channel> renegotiate(final Promise<Channel> promise) {
    if (promise == null) {
        throw new NullPointerException("promise");
    }

    ChannelHandlerContext ctx = this.ctx;
    if (ctx == null) {
        throw new IllegalStateException();
    }

    EventExecutor executor = ctx.executor();
    if (!executor.inEventLoop()) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                handshake(promise);
            }
        });
        return promise;
    }

    handshake(promise);
    return promise;
}
 
Example #4
Source File: FixedChannelPool.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
    public Future<Channel> acquire(final Promise<Channel> promise) {
        try {
            if (executor.inEventLoop()) {
//                获取channel
                acquire0(promise);
            } else {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        acquire0(promise);
                    }
                });
            }
        } catch (Throwable cause) {
            promise.setFailure(cause);
        }
        return promise;
    }
 
Example #5
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 3000)
public void testHandlerAddedExceptionFromChildHandlerIsPropagated() {
    final EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    try {
        final Promise<Void> promise = group1.next().newPromise();
        final AtomicBoolean handlerAdded = new AtomicBoolean();
        final Exception exception = new RuntimeException();
        ChannelPipeline pipeline = new LocalChannel().pipeline();
        pipeline.addLast(group1, new CheckExceptionHandler(exception, promise));
        pipeline.addFirst(new ChannelHandlerAdapter() {
            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                handlerAdded.set(true);
                throw exception;
            }
        });
        assertFalse(handlerAdded.get());
        group.register(pipeline.channel());
        promise.syncUninterruptibly();
    } finally {
        group1.shutdownGracefully();
    }
}
 
Example #6
Source File: CancellableAcquireChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void promiseCancelledBeforeAcquireComplete_closesAndReleasesChannel() throws InterruptedException {
    Promise<Channel> acquireFuture = eventExecutor.newPromise();
    acquireFuture.setFailure(new RuntimeException("Changed my mind!"));

    when(mockDelegatePool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
        Promise p = invocationOnMock.getArgumentAt(0, Promise.class);
        p.setSuccess(channel);
        return p;
    });

    cancellableAcquireChannelPool.acquire(acquireFuture);

    Thread.sleep(500);
    verify(mockDelegatePool).release(eq(channel));
    assertThat(channel.closeFuture().isDone()).isTrue();
}
 
Example #7
Source File: NettyUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link BiConsumer} that notifies the promise of any failures either via the throwable passed into the BiConsumer
 * or as a result of running the successConsumer. This assumes that the successConsumer will notify the promise when it
 * completes successfully.
 *
 * @param successConsumer BiConsumer to call if the result is successful. Promise is also passed and must be notified on
 * success.
 * @param promise Promise to notify.
 * @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> asyncPromiseNotifyingBiConsumer(
    BiConsumer<SuccessT, Promise<PromiseT>> successConsumer, Promise<PromiseT> promise) {
    return (success, fail) -> {
        if (fail != null) {
            promise.setFailure(fail);
        } else {
            try {
                successConsumer.accept(success, promise);
            } catch (Throwable e) {
                // If the successConsumer fails synchronously then we can notify the promise. If it fails asynchronously
                // it's up to the successConsumer to notify.
                promise.setFailure(e);
            }
        }
    };
}
 
Example #8
Source File: NettyHandlerTestBase.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
FakeClockScheduledNettyFuture(
    EventLoop eventLoop, final Runnable command, long delay, TimeUnit timeUnit) {
  super(eventLoop);
  Runnable wrap = new Runnable() {
    @Override
    public void run() {
      try {
        command.run();
      } catch (Throwable t) {
        setFailure(t);
        return;
      }
      if (!isDone()) {
        Promise<Void> unused = setSuccess(null);
      }
      // else: The command itself, such as a shutdown task, might have cancelled all the
      // scheduled tasks already.
    }
  };
  future = fakeClock.getScheduledExecutorService().schedule(wrap, delay, timeUnit);
}
 
Example #9
Source File: DefaultHttp2ConnectionTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void removeAllStreamsWhileIteratingActiveStreams() throws InterruptedException, Http2Exception {
    final Endpoint<Http2RemoteFlowController> remote = client.remote();
    final Endpoint<Http2LocalFlowController> local = client.local();
    for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
        local.createStream(c, false);
        remote.createStream(s, false);
    }
    final Promise<Void> promise = group.next().newPromise();
    final CountDownLatch latch = new CountDownLatch(client.numActiveStreams());
    client.forEachActiveStream(new Http2StreamVisitor() {
        @Override
        public boolean visit(Http2Stream stream) {
            client.close(promise).addListener(new FutureListener<Void>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    assertTrue(promise.isDone());
                    latch.countDown();
                }
            });
            return true;
        }
    });
    assertTrue(latch.await(5, TimeUnit.SECONDS));
}
 
Example #10
Source File: Http2StreamChannelBootstrap.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public Future<Http2StreamChannel> open(final Promise<Http2StreamChannel> promise) {
    final ChannelHandlerContext ctx = channel.pipeline().context(Http2MultiplexCodec.class);
    if (ctx == null) {
        if (channel.isActive()) {
            promise.setFailure(new IllegalStateException(StringUtil.simpleClassName(Http2MultiplexCodec.class) +
                    " must be in the ChannelPipeline of Channel " + channel));
        } else {
            promise.setFailure(new ClosedChannelException());
        }
    } else {
        EventExecutor executor = ctx.executor();
        if (executor.inEventLoop()) {
            open0(ctx, promise);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    open0(ctx, promise);
                }
            });
        }
    }
    return promise;
}
 
Example #11
Source File: Http2MultiplexedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void acquireStreamOnNewConnection(Promise<Channel> promise) {
    Future<Channel> newConnectionAcquire = connectionPool.acquire();

    newConnectionAcquire.addListener(f -> {
        if (!newConnectionAcquire.isSuccess()) {
            promise.setFailure(newConnectionAcquire.cause());
            return;
        }

        Channel parentChannel = newConnectionAcquire.getNow();
        try {
            parentChannel.attr(ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL).set(this);

            // When the protocol future is completed on the new connection, we're ready for new streams to be added to it.
            parentChannel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).get()
                         .thenAccept(protocol -> acquireStreamOnFreshConnection(promise, parentChannel, protocol))
                         .exceptionally(throwable -> failAndCloseParent(promise, parentChannel, throwable));
        } catch (Throwable e) {
            failAndCloseParent(promise, parentChannel, e);
        }
    });
}
 
Example #12
Source File: MultiplexedChannelRecordTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void recordsWithoutReservedStreamsAreClosedAfterTimeout() throws InterruptedException {
    int idleTimeoutMillis = 1000;
    EmbeddedChannel channel = newHttp2Channel();
    MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, Duration.ofMillis(idleTimeoutMillis));

    Promise<Channel> streamPromise = channel.eventLoop().newPromise();
    record.acquireStream(streamPromise);

    channel.runPendingTasks();

    assertThat(streamPromise.isSuccess()).isTrue();
    assertThat(channel.isOpen()).isTrue();

    record.closeAndReleaseChild(streamPromise.getNow());

    assertThat(channel.isOpen()).isTrue();

    Thread.sleep(idleTimeoutMillis * 2);
    channel.runPendingTasks();

    assertThat(channel.isOpen()).isFalse();
}
 
Example #13
Source File: PerServerConnectionPool.java    From zuul with Apache License 2.0 6 votes vote down vote up
protected void handleConnectCompletion(
        ChannelFuture cf, Promise<PooledConnection> callerPromise, CurrentPassport passport) {
    connCreationsInProgress.decrementAndGet();
    
    if (cf.isSuccess()) {
        
        passport.add(PassportState.ORIGIN_CH_CONNECTED);
        
        stats.incrementOpenConnectionsCount();
        createConnSucceededCounter.increment();
        connsInUse.incrementAndGet();

        createConnection(cf, callerPromise, passport);
    }
    else {
        stats.incrementSuccessiveConnectionFailureCount();
        stats.addToFailureCount();
        stats.decrementActiveRequestsCount();
        createConnFailedCounter.increment();
        callerPromise.setFailure(new OriginConnectException(cf.cause().getMessage(), OutboundErrorType.CONNECT_ERROR));
    }
}
 
Example #14
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 6 votes vote down vote up
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
  http2ClientMetrics.http2NewStreamCount.inc();
  if (closed.get()) {
    return promise.setFailure(new IOException("Channel pool is closed!"));
  }

  // Only when number of connections reach http2MinConnectionPerPort, we reuse connections.
  if (parentConnections.size() >= http2ClientConfig.http2MinConnectionPerPort) {
    List<MultiplexedChannelRecord> multiplexedChannelRecords = new ArrayList<>(parentConnections);
    Collections.shuffle(multiplexedChannelRecords);
    // Attempt at most multiplexedChannelRecords.size(). No slip acquire expected.
    for (MultiplexedChannelRecord multiplexedChannelRecord : multiplexedChannelRecords) {
      if (acquireStreamOnInitializedConnection(multiplexedChannelRecord, promise)) {
        return promise;
      }
      log.warn("Stream slip acquire on {}", inetSocketAddress);
      http2ClientMetrics.http2StreamSlipAcquireCount.inc();
    }
  }

  // No connection or No available streams on existing connections, establish new connection and add it to set.
  acquireStreamOnNewConnection(promise);
  return promise;
}
 
Example #15
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void doReleaseChannel(Channel channel, Promise<Void> promise) {
        assert channel.eventLoop().inEventLoop();
        // Remove the POOL_KEY attribute from the Channel and check if it was acquired from this pool, if not fail.从通道中删除POOL_KEY属性,如果没有失败,则检查它是否从这个池中获得。
        if (channel.attr(POOL_KEY).getAndSet(null) != this) {
            closeAndFail(channel,
                         // Better include a stacktrace here as this is an user error.最好在这里包含一个stacktrace,因为这是一个用户错误。
                         new IllegalArgumentException(
                                 "Channel " + channel + " was not acquired from this ChannelPool"),
                         promise);
        } else {
            try {
//                健康检查并释放
                if (releaseHealthCheck) {
                    doHealthCheckOnRelease(channel, promise);
                } else {
//                    直接释放
                    releaseAndOffer(channel, promise);
                }
            } catch (Throwable cause) {
                closeAndFail(channel, cause, promise);
            }
        }
    }
 
Example #16
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 3000)
public void testHandlerRemovedExceptionFromChildHandlerIsPropagated() {
    final EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    try {
        final Promise<Void> promise = group1.next().newPromise();
        String handlerName = "foo";
        final Exception exception = new RuntimeException();
        ChannelPipeline pipeline = new LocalChannel().pipeline();
        pipeline.addLast(handlerName, new ChannelHandlerAdapter() {
            @Override
            public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                throw exception;
            }
        });
        pipeline.addLast(group1, new CheckExceptionHandler(exception, promise));
        group.register(pipeline.channel()).syncUninterruptibly();
        pipeline.remove(handlerName);
        promise.syncUninterruptibly();
    } finally {
        group1.shutdownGracefully();
    }
}
 
Example #17
Source File: InetSocketAddressResolver.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doResolveAll(final InetSocketAddress unresolvedAddress,
                            final Promise<List<InetSocketAddress>> promise) throws Exception {
    // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here,
    // because an unresolved address always has a host name.
    nameResolver.resolveAll(unresolvedAddress.getHostName())
            .addListener(new FutureListener<List<InetAddress>>() {
                @Override
                public void operationComplete(Future<List<InetAddress>> future) throws Exception {
                    if (future.isSuccess()) {
                        List<InetAddress> inetAddresses = future.getNow();
                        List<InetSocketAddress> socketAddresses =
                                new ArrayList<InetSocketAddress>(inetAddresses.size());
                        for (InetAddress inetAddress : inetAddresses) {
                            socketAddresses.add(new InetSocketAddress(inetAddress, unresolvedAddress.getPort()));
                        }
                        promise.setSuccess(socketAddresses);
                    } else {
                        promise.setFailure(future.cause());
                    }
                }
            });
}
 
Example #18
Source File: NettyRequestExecutorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void cancelExecuteFuture_channelAcquired_submitsRunnable() {
    EventLoop mockEventLoop = mock(EventLoop.class);
    Channel mockChannel = mock(Channel.class);
    when(mockChannel.eventLoop()).thenReturn(mockEventLoop);

    when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
        Promise p = invocationOnMock.getArgumentAt(0, Promise.class);
        p.setSuccess(mockChannel);
        return p;
    });

    CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute();

    executeFuture.cancel(true);

    verify(mockEventLoop).submit(any(Runnable.class));
}
 
Example #19
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
    public Future<Void> release(final Channel channel, final Promise<Void> promise) {
        checkNotNull(channel, "channel");
        checkNotNull(promise, "promise");
        try {
            EventLoop loop = channel.eventLoop();
            if (loop.inEventLoop()) {
                doReleaseChannel(channel, promise);
            } else {
                loop.execute(new Runnable() {
                    @Override
                    public void run() {
//                        释放channel
                        doReleaseChannel(channel, promise);
                    }
                });
            }
        } catch (Throwable cause) {
//            关闭channel,发布promise失败事件
            closeAndFail(channel, cause, promise);
        }
        return promise;
    }
 
Example #20
Source File: InetSocketAddressResolver.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doResolve(final InetSocketAddress unresolvedAddress, final Promise<InetSocketAddress> promise)
        throws Exception {
    // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here,
    // because an unresolved address always has a host name.
    nameResolver.resolve(unresolvedAddress.getHostName())
            .addListener(new FutureListener<InetAddress>() {
                @Override
                public void operationComplete(Future<InetAddress> future) throws Exception {
                    if (future.isSuccess()) {
                        promise.setSuccess(new InetSocketAddress(future.getNow(), unresolvedAddress.getPort()));
                    } else {
                        promise.setFailure(future.cause());
                    }
                }
            });
}
 
Example #21
Source File: ProxyTunnelInitHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulProxyResponse_removesSelfAndCodec() {
    Promise<Channel> promise = GROUP.next().newPromise();
    ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
    successResponse(handler);

    verify(mockPipeline).remove(eq(handler));
    verify(mockPipeline).remove(any(HttpClientCodec.class));
}
 
Example #22
Source File: Http2StreamChannelBootstrap.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public void open0(ChannelHandlerContext ctx, final Promise<Http2StreamChannel> promise) {
    assert ctx.executor().inEventLoop();
    final Http2StreamChannel streamChannel = ((Http2MultiplexCodec) ctx.handler()).newOutboundStream();
    try {
        init(streamChannel);
    } catch (Exception e) {
        streamChannel.unsafe().closeForcibly();
        promise.setFailure(e);
        return;
    }

    ChannelFuture future = ctx.channel().eventLoop().register(streamChannel);
    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                promise.setSuccess(streamChannel);
            } else if (future.isCancelled()) {
                promise.cancel(false);
            } else {
                if (streamChannel.isRegistered()) {
                    streamChannel.close();
                } else {
                    streamChannel.unsafe().closeForcibly();
                }

                promise.setFailure(future.cause());
            }
        }
    });
}
 
Example #23
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 5 votes vote down vote up
private void acquireStreamOnFreshConnection(Promise<Channel> promise, Channel parentChannel) {
  long startTime = System.currentTimeMillis();
  try {
    MultiplexedChannelRecord multiplexedChannel =
        new MultiplexedChannelRecord(parentChannel, http2ClientConfig.http2MaxConcurrentStreamsPerConnection,
            http2ClientConfig.idleConnectionTimeoutMs, streamChannelInitializer);
    parentChannel.attr(MULTIPLEXED_CHANNEL).set(multiplexedChannel);

    Promise<Channel> streamPromise = parentChannel.eventLoop().newPromise();

    if (!acquireStreamOnInitializedConnection(multiplexedChannel, streamPromise)) {
      failAndCloseParent(promise, parentChannel,
          new IOException("Connection was closed while creating a new stream."));
      return;
    }

    streamPromise.addListener(f -> {
      if (!streamPromise.isSuccess()) {
        promise.setFailure(streamPromise.cause());
        return;
      }

      Channel stream = streamPromise.getNow();
      cacheConnectionForFutureStreams(stream, multiplexedChannel, promise);
      http2ClientMetrics.http2FirstStreamAcquireTime.update(System.currentTimeMillis() - startTime);
    });
  } catch (Throwable e) {
    failAndCloseParent(promise, parentChannel, e);
  }
}
 
Example #24
Source File: CancellableAcquireChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Channel> acquire(Promise<Channel> acquirePromise) {
    Future<Channel> channelFuture = delegatePool.acquire(executor.newPromise());
    channelFuture.addListener((Future<Channel> f) -> {
        if (f.isSuccess()) {
            Channel ch = f.getNow();
            if (!acquirePromise.trySuccess(ch)) {
                ch.close().addListener(closeFuture -> delegatePool.release(ch));
            }
        } else {
            acquirePromise.tryFailure(f.cause());
        }
    });
    return acquirePromise;
}
 
Example #25
Source File: HonorCloseOnReleaseChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
    doInEventLoop(channel.eventLoop(), () -> {
        boolean shouldCloseOnRelease = Boolean.TRUE.equals(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get());

        if (shouldCloseOnRelease && channel.isOpen() && !channel.eventLoop().isShuttingDown()) {
            log.debug(() -> "Closing connection (" + channel.id() + "), instead of releasing it.");
            channel.close();
        }

        delegatePool.release(channel, promise);
    });
    return promise;
}
 
Example #26
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private boolean query(String hostname, DnsRecordType type, DnsServerAddressStream dnsServerAddressStream,
                      Promise<T> promise, Throwable cause) {
    final DnsQuestion question = newQuestion(hostname, type);
    if (question == null) {
        return false;
    }
    query(dnsServerAddressStream, 0, question, promise, cause);
    return true;
}
 
Example #27
Source File: Socks4ProxyHandler.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Socks4Message socksRequest) {
    Socks4CommandRequest command = (Socks4CommandRequest) socksRequest;
    if (command.type() != Socks4CommandType.CONNECT) {
        NettyUtils.closeOnFlush(ctx.channel());
        logger.error("unsupported socks4 command: {}", command.type());
        return;
    }
    Promise<Channel> promise = ctx.executor().newPromise();
    Bootstrap bootstrap = initBootStrap(promise, ctx.channel().eventLoop());

    bootstrap.connect(command.dstAddr(), command.dstPort()).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(REJECTED_OR_FAILED));
            NettyUtils.closeOnFlush(ctx.channel());
        }
    });

    promise.addListener((FutureListener<Channel>) future -> {
        Channel outboundChannel = future.getNow();
        if (!future.isSuccess()) {
            ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(REJECTED_OR_FAILED));
            NettyUtils.closeOnFlush(ctx.channel());
            return;
        }
        ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(SUCCESS));

        responseFuture.addListener((ChannelFutureListener) channelFuture -> {
            ctx.pipeline().remove(Socks4ProxyHandler.this);
            ctx.pipeline().remove(Socks4ServerEncoder.class);
            ctx.pipeline().remove(Socks4ServerDecoder.class);
            var address = HostPort.of(command.dstAddr(), command.dstPort());
            initTcpProxyHandlers(ctx, address, outboundChannel);
        });
    });
}
 
Example #28
Source File: BetterFixedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> release(final Channel channel, final Promise<Void> promise) {
    ObjectUtil.checkNotNull(promise, "promise");
    Promise<Void> p = executor.newPromise();
    delegateChannelPool.release(channel, p.addListener(new FutureListener<Void>() {

        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            assert executor.inEventLoop();

            if (closed) {
                // Since the pool is closed, we have no choice but to close the channel
                channel.close();
                promise.setFailure(POOL_CLOSED_ON_RELEASE_EXCEPTION);
                return;
            }

            if (future.isSuccess()) {
                decrementAndRunTaskQueue();
                promise.setSuccess(null);
            } else {
                Throwable cause = future.cause();
                // Check if the exception was not because of we passed the Channel to the wrong pool.
                if (!(cause instanceof IllegalArgumentException)) {
                    decrementAndRunTaskQueue();
                }
                promise.setFailure(future.cause());
            }
        }
    }));
    return promise;
}
 
Example #29
Source File: DefaultHttp2ConnectionTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void removeAllStreamsWhileIteratingActiveStreamsAndExceptionOccurs()
        throws InterruptedException, Http2Exception {
    final Endpoint<Http2RemoteFlowController> remote = client.remote();
    final Endpoint<Http2LocalFlowController> local = client.local();
    for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
        local.createStream(c, false);
        remote.createStream(s, false);
    }
    final Promise<Void> promise = group.next().newPromise();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        client.forEachActiveStream(new Http2StreamVisitor() {
            @Override
            public boolean visit(Http2Stream stream) throws Http2Exception {
                // This close call is basically a noop, because the following statement will throw an exception.
                client.close(promise);
                // Do an invalid operation while iterating.
                remote.createStream(3, false);
                return true;
            }
        });
    } catch (Http2Exception ignored) {
        client.close(promise).addListener(new FutureListener<Void>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                assertTrue(promise.isDone());
                latch.countDown();
            }
        });
    }
    assertTrue(latch.await(5, TimeUnit.SECONDS));
}
 
Example #30
Source File: BetterFixedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Channel> acquire(final Promise<Channel> promise) {
    try {
        if (executor.inEventLoop()) {
            acquire0(promise);
        } else {
            executor.execute(() -> acquire0(promise));
        }
    } catch (Throwable cause) {
        promise.setFailure(cause);
    }
    return promise;
}