Java Code Examples for io.netty.util.concurrent.Future#getNow()

The following examples show how to use io.netty.util.concurrent.Future#getNow() . 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: FtdcTraderApiAdapter.java    From ftdc with Apache License 2.0 6 votes vote down vote up
@Override
public void operationComplete(Future<Channel> future) throws Exception {
	ApplicationRuntime.bindRequestIdentiity(requestIdentity);
	if (future.isSuccess()) {
		Channel channel = future.getNow();
		ByteBuf buffer = sendMessage(channel);
		spi.reqister(channel);
		channel.writeAndFlush(new FtdcProtocol(FtdType.FTDTypeCompressed, buffer, FtdcType.REQ.type(), requestIdentity.getReqId(),
				tid.id(), sequence));
		startTask(new RecieveMessageTimerTask(requestIdentity, spi));
	} else {
		logger.error(ExceptionUtils.getStackTrace(future.cause()));
		if(this.retry-- > 0) {
			FtdClientPool pool = FtdClientPool.getPool();
			pool.acquire(FtdcTraderApiAdapter.this.getSas()).addListener(this);
		}else {
			RspError connectError = RspError.buildConnectError();
			((BaseFtdcTraderSpiAdapter)spi).doRspError(requestIdentity, connectError);
		}
	}
}
 
Example 2
Source File: AsyncOlapNIOLayer.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void operationComplete(Future<Channel> channelFuture) throws Exception{
    if (LOG.isTraceEnabled())
        LOG.trace("Submit command ");
    if(!channelFuture.isSuccess()){
        olapFuture.fail(channelFuture.cause());
        return;
    }
    final Channel c=channelFuture.getNow();
    ChannelPipeline writePipeline=c.pipeline();
    writePipeline.addLast("handler",olapFuture.submitHandler);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Submitted job " + olapFuture.job.getUniqueName());
    }

    OlapMessage.Submit submit=OlapMessage.Submit.newBuilder().setCommandBytes(olapFuture.data).build();
    OlapMessage.Command cmd=OlapMessage.Command.newBuilder()
            .setUniqueName(olapFuture.job.getUniqueName())
            .setExtension(OlapMessage.Submit.command,submit)
            .setType(OlapMessage.Command.Type.SUBMIT)
            .build();
    ChannelFuture writeFuture=c.writeAndFlush(cmd);
    writeFuture.addListener(olapFuture.failListener);

}
 
Example 3
Source File: SearchDomainTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static List<String> assertResolveAll(DnsNameResolver resolver,
                                             String inetHost) throws InterruptedException {
    Future<List<InetAddress>> fut = resolver.resolveAll(inetHost);
    assertTrue(fut.await(10, TimeUnit.SECONDS));
    List<String> list = new ArrayList<String>();
    for (InetAddress addr : fut.getNow()) {
        list.add(addr.getHostAddress());
    }
    return list;
}
 
Example 4
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * 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 5
Source File: ConnectionPool.java    From drift with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Channel> getConnection(ConnectionParameters connectionParameters, HostAndPort address)
{
    ConnectionKey key = new ConnectionKey(connectionParameters, address);

    while (true) {
        synchronized (this) {
            if (closed) {
                return group.next().newFailedFuture(new TTransportException("Connection pool is closed"));
            }

            Future<Channel> future;
            try {
                future = cachedConnections.get(key, () -> createConnection(key));
            }
            catch (ExecutionException e) {
                throw new RuntimeException(e);
            }

            // connection is still opening
            if (!future.isDone()) {
                return future;
            }

            // check if connection is failed or closed
            Channel channel = future.getNow();
            // channel can be null if the future was canceled
            if (channel != null && channel.isOpen()) {
                return future;
            }

            // remove dead connection from cache
            cachedConnections.asMap().remove(key, future);
        }
    }
}
 
Example 6
Source File: FastdfsExecutor.java    From azeroth with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> cf) throws Exception {

    if (cf.isCancelled()) {
        promise.cancel(true);
        return;
    }

    if (!cf.isSuccess()) {
        promise.completeExceptionally(cf.cause());
        return;
    }

    Channel channel = cf.getNow();
    promise.whenComplete((result, error) -> pool.release(channel));

    try {

        FastdfsOperation<T> fastdfsOperation = new FastdfsOperation<>(channel, requestor,
            replier, promise);
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute {}", fastdfsOperation);
        }

        fastdfsOperation.execute();
    } catch (Exception e) {
        promise.completeExceptionally(e);
    }
}
 
Example 7
Source File: NettyRequestExecutor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void makeRequestListener(Future<Channel> channelFuture) {
    if (channelFuture.isSuccess()) {
        channel = channelFuture.getNow();
        configureChannel();
        if (tryConfigurePipeline()) {
            makeRequest();
        }
    } else {
        handleFailure(() -> "Failed to create connection to " + endpoint(), channelFuture.cause());
    }
}
 
Example 8
Source File: FastdfsExecutor.java    From fastdfs-client with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> cf) throws Exception {

    if (cf.isCancelled()) {
        promise.cancel(true);
        return;
    }

    if (!cf.isSuccess()) {
        promise.completeExceptionally(cf.cause());
        return;
    }

    Channel channel = cf.getNow();
    promise.whenComplete((result, error) -> {
        if (null != error) {
            channel.close().addListener(ignore -> pool.release(channel));
            return;
        }

        pool.release(channel);
    });

    try {

        FastdfsOperation<T> fastdfsOperation = new FastdfsOperation<>(channel, requestor, replier, promise);
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute {}", fastdfsOperation);
        }

        fastdfsOperation.execute();
    } catch (Exception e) {
        promise.completeExceptionally(e);
    }
}
 
Example 9
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(Future<Http2StreamChannel> future) {
	Channel channel = pooledRef.poolable().channel();
	Http2FrameCodec frameCodec = channel.pipeline().get(Http2FrameCodec.class);
	if (future.isSuccess()) {
		Http2StreamChannel ch = future.getNow();

		if (!frameCodec.connection().local().canOpenStream()) {
			if (!retried) {
				if (log.isDebugEnabled()) {
					log.debug(format(ch, "Immediately aborted pooled channel max active streams is reached, " +
						"re-acquiring a new channel"));
				}
				pool.acquire(Duration.ofMillis(pendingAcquireTimeout))
				    .subscribe(new DisposableAcquire(this));
			}
			else {
				sink.error(new IOException("Error while acquiring from " + pool + ". Max active streams is reached."));
			}
		}
		else {
			ChannelOperations<?, ?> ops = ChannelOperations.get(ch);
			if (ops != null) {
				obs.onStateChange(ops, STREAM_CONFIGURED);
				sink.success(ops);
			}

			if (log.isDebugEnabled()) {
				log.debug(format(ch, "Stream opened, now {} active streams, {} max active streams."),
						frameCodec.connection().local().numActiveStreams(),
						frameCodec.connection().local().maxActiveStreams());
			}
		}
	}
	else {
		sink.error(future.cause());
	}

	release(this, channel);
}
 
Example 10
Source File: DnsEndpointGroup.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void onDnsRecords(Future<? super List<DnsRecord>> future) {
    if (isClosing()) {
        if (future.isSuccess()) {
            @SuppressWarnings("unchecked")
            final List<DnsRecord> result = (List<DnsRecord>) future.getNow();
            result.forEach(ReferenceCountUtil::safeRelease);
        }
        return;
    }

    if (!future.isSuccess()) {
        // Failed. Try again with the delay given by Backoff.
        final long delayMillis = backoff.nextDelayMillis(attemptsSoFar);
        logger.warn("{} DNS query failed; retrying in {} ms (attempts so far: {}):",
                    logPrefix, delayMillis, attemptsSoFar, future.cause());
        scheduledFuture = eventLoop.schedule(() -> sendQueries(questions),
                                             delayMillis, TimeUnit.MILLISECONDS);
        return;
    }

    // Reset the counter so that Backoff is reset.
    attemptsSoFar = 0;

    @SuppressWarnings("unchecked")
    final List<DnsRecord> records = (List<DnsRecord>) future.getNow();
    final long serverTtl = records.stream().mapToLong(DnsRecord::timeToLive).min().orElse(minTtl);
    final int effectiveTtl = (int) Math.max(Math.min(serverTtl, maxTtl), minTtl);

    try {
        setEndpoints(onDnsRecords(records, effectiveTtl));
    } catch (Throwable t) {
        logger.warn("{} Failed to process the DNS query result: {}", logPrefix, records, t);
    } finally {
        records.forEach(ReferenceCountUtil::safeRelease);
        scheduledFuture = eventLoop.schedule(() -> sendQueries(questions), effectiveTtl, TimeUnit.SECONDS);
    }
}
 
Example 11
Source File: AbstractAddPathTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static BGPSessionImpl connectPeer(final Ipv4Address localAddress, final BGPDispatcherImpl dispatcherImpl)
        throws InterruptedException {
    final Future<BGPSessionImpl> future = dispatcherImpl
            .createClient(new InetSocketAddress(localAddress.getValue(), PORT.toJava()),
                    new InetSocketAddress(RIB_ID, PORT.toJava()), RETRY_TIMER, true);
    Thread.sleep(200);
    waitFutureSuccess(future);
    Thread.sleep(100);
    return future.getNow();
}
 
Example 12
Source File: AsyncOlapNIOLayer.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> channelFuture) throws Exception{
    if(!channelFuture.isSuccess()){
        olapFuture.fail(channelFuture.cause());
        return;
    }

    final Channel c=channelFuture.getNow();
    ChannelPipeline writePipeline=c.pipeline();
    writePipeline.addLast("handler",olapFuture.resultHandler);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Status check job " + olapFuture.job.getUniqueName());
    }

    OlapMessage.Status.Builder status=OlapMessage.Status.newBuilder();
    if (olapFuture.waitTimeMillis > 0) {
        status.setWaitTimeMillis(olapFuture.waitTimeMillis);
        olapFuture.waitTimeMillis = 0;
    }
    OlapMessage.Command cmd=OlapMessage.Command.newBuilder()
            .setUniqueName(olapFuture.job.getUniqueName())
            .setType(OlapMessage.Command.Type.STATUS)
            .setExtension(OlapMessage.Status.command,status.build()).build();
    ChannelFuture writeFuture=c.writeAndFlush(cmd);
    writeFuture.addListener(new GenericFutureListener<Future<Void>>(){
        @Override
        public void operationComplete(Future<Void> future) throws Exception{
            //TODO -sf- possible failover/retry mechanism in place here?
            if(!future.isSuccess()){
                olapFuture.fail(future.cause());
                olapFuture.signal();
            }
        }
    });
}
 
Example 13
Source File: AsyncOlapNIOLayer.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> channelFuture) throws Exception{
    if(!channelFuture.isSuccess()){
         /*
          * Unfortunately, no one is listening to this, so there's really no
          * way to communicate this back to the client (the client has moved on).
          * So just note the error and move on.
          */
        LOG.error("Unable to cancel job "+uniqueName+": Unable to obtain channel",channelFuture.cause());
        return;
    }

    final Channel c=channelFuture.getNow();

    OlapMessage.Cancel cancel=OlapMessage.Cancel.newBuilder().build();
    OlapMessage.Command cmd=OlapMessage.Command.newBuilder()
            .setUniqueName(uniqueName)
            .setType(OlapMessage.Command.Type.CANCEL)
            .setExtension(OlapMessage.Cancel.command,cancel).build();
    ChannelFuture writeFuture=c.writeAndFlush(cmd);
    writeFuture.addListener(new GenericFutureListener<Future<Void>>(){
        @Override
        public void operationComplete(Future<Void> future) throws Exception{
            if(future.isSuccess()){
                if(LOG.isTraceEnabled()){
                    LOG.trace("job "+uniqueName+" cancelled successfully");
                }
            }else{
                LOG.error("Unable to cancel job "+uniqueName+": Unable to write cancel command",future.cause());
            }
            //once the write is complete, release the channel from the pool
            channelPool.release(c);
        }
    });
}
 
Example 14
Source File: RntbdClientChannelPool.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Override
public void operationComplete(Future<Channel> future) {

    checkState(this.pool.executor.inEventLoop());

    if (this.pool.isClosed()) {
        if (future.isSuccess()) {
            // Since the pool is closed, we have no choice but to close the channel
            future.getNow().close();
        }
        this.originalPromise.setFailure(POOL_CLOSED_ON_ACQUIRE);
        return;
    }

    if (future.isSuccess()) {

        // Ensure that the channel is active and ready to receive requests
        // A Direct TCP channel is ready to receive requests when it:
        // * is active and
        // * has an RntbdContext
        // We send a health check request on a channel without an RntbdContext to force:
        // 1. SSL negotiation
        // 2. RntbdContextRequest -> RntbdContext
        // 3. RntbdHealthCheckRequest -> receive acknowledgement

        final Channel channel = future.getNow();

        channel.eventLoop().execute(() -> {

            if (!channel.isActive()) {
                this.fail(CHANNEL_CLOSED_ON_ACQUIRE);
                return;
            }

            final ChannelPipeline pipeline = channel.pipeline();
            checkState(pipeline != null);

            final RntbdRequestManager requestManager = pipeline.get(RntbdRequestManager.class);
            checkState(requestManager != null);

            if (requestManager.hasRequestedRntbdContext()) {

                this.originalPromise.setSuccess(channel);

            } else {

                channel.writeAndFlush(RntbdHealthCheckRequest.MESSAGE).addListener(completed -> {

                    if (completed.isSuccess()) {

                        reportIssueUnless(logger, this.acquired && requestManager.hasRntbdContext(),
                            channel,"acquired: {}, rntbdContext: {}", this.acquired,
                            requestManager.rntbdContext());

                        this.originalPromise.setSuccess(channel);

                    } else {

                        logger.warn("Channel({}) health check request failed due to:", channel, completed.cause());
                        this.fail(completed.cause());
                    }
                });
            }
        });

    } else {
        logger.warn("channel acquisition failed due to:", future.cause());
        this.fail(future.cause());
    }
}
 
Example 15
Source File: TestConnectionPool.java    From drift with Apache License 2.0 4 votes vote down vote up
private static <T> T futureGet(Future<T> future)
{
    assertTrue(future.isSuccess());
    return future.getNow();
}
 
Example 16
Source File: RefreshingAddressResolverTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void resolve() throws Exception {
    try (TestDnsServer server = new TestDnsServer(ImmutableMap.of(
            new DefaultDnsQuestion("foo.com.", A),
            new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("foo.com.", "1.1.1.1")),
            new DefaultDnsQuestion("bar.com.", A),
            new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("bar.com.", "1.2.3.4"))))
    ) {
        final EventLoop eventLoop = eventLoopExtension.get();
        try (RefreshingAddressResolverGroup group = builder(server).build(eventLoop)) {
            final AddressResolver<InetSocketAddress> resolver = group.getResolver(eventLoop);
            final Future<InetSocketAddress> foo = resolver.resolve(
                    InetSocketAddress.createUnresolved("foo.com", 36462));
            await().untilAsserted(() -> assertThat(foo.isSuccess()).isTrue());
            InetSocketAddress addr = foo.getNow();
            assertThat(addr.getAddress().getHostAddress()).isEqualTo("1.1.1.1");
            assertThat(addr.getPort()).isEqualTo(36462);

            final ConcurrentMap<String, CompletableFuture<CacheEntry>> cache = group.cache();
            assertThat(cache.size()).isOne();

            final Future<InetSocketAddress> bar = resolver.resolve(
                    InetSocketAddress.createUnresolved("bar.com", 36462));
            await().untilAsserted(() -> assertThat(bar.isSuccess()).isTrue());
            addr = bar.getNow();
            assertThat(addr.getAddress().getHostAddress()).isEqualTo("1.2.3.4");
            assertThat(addr.getPort()).isEqualTo(36462);
            assertThat(cache.size()).isEqualTo(2);

            final Future<InetSocketAddress> foo1 = resolver.resolve(
                    InetSocketAddress.createUnresolved("foo.com", 80));
            addr = foo1.getNow();
            assertThat(addr.getAddress().getHostAddress()).isEqualTo("1.1.1.1");
            assertThat(addr.getPort()).isEqualTo(80);
            assertThat(cache.size()).isEqualTo(2);

            final List<InetAddress> addresses =
                    cache.values()
                         .stream()
                         .map(future -> future.join().address())
                         .collect(toImmutableList());
            assertThat(addresses).containsExactlyInAnyOrder(
                    InetAddress.getByAddress("foo.com", new byte[] { 1, 1, 1, 1 }),
                    InetAddress.getByAddress("bar.com", new byte[] { 1, 2, 3, 4 }));
        }
    }
}