List of usage examples for io.netty.util.concurrent Future getNow
V getNow();
From source file:com.linecorp.armeria.client.endpoint.dns.DnsEndpointGroup.java
License:Apache License
private void sendQueries() { if (stopped) { return;//from w w w .ja v a2 s.co m } final Future<List<DnsRecord>> future; final int numQuestions = questions.size(); if (numQuestions == 1) { // Simple case of single query final DnsQuestion question = questions.get(0); logger.debug("{} Sending a DNS query", logPrefix); future = resolver.resolveAll(question); } else { // Multiple queries logger.debug("{} Sending DNS queries", logPrefix); @SuppressWarnings("unchecked") final Promise<List<DnsRecord>> aggregatedPromise = eventLoop.newPromise(); final FutureListener<List<DnsRecord>> listener = new FutureListener<List<DnsRecord>>() { private final List<DnsRecord> records = new ArrayList<>(); private int remaining = numQuestions; @Nullable private List<Throwable> causes; @Override public void operationComplete(Future<List<DnsRecord>> future) throws Exception { if (future.isSuccess()) { final List<DnsRecord> records = future.getNow(); this.records.addAll(records); } else { if (causes == null) { causes = new ArrayList<>(numQuestions); } causes.add(future.cause()); } if (--remaining == 0) { if (!records.isEmpty()) { aggregatedPromise.setSuccess(records); } else { final Throwable aggregatedCause; if (causes == null) { aggregatedCause = new EndpointGroupException("empty result returned by DNS server"); } else { aggregatedCause = new EndpointGroupException("failed to receive DNS records"); for (Throwable c : causes) { aggregatedCause.addSuppressed(c); } } aggregatedPromise.setFailure(aggregatedCause); } } } }; questions.forEach(q -> resolver.resolveAll(q).addListener(listener)); future = aggregatedPromise; } attemptsSoFar++; future.addListener(this::onDnsRecords); }
From source file:com.linecorp.armeria.client.endpoint.dns.DnsEndpointGroup.java
License:Apache License
private void onDnsRecords(Future<? super List<DnsRecord>> future) { if (stopped) { if (future.isSuccess()) { @SuppressWarnings("unchecked") final List<DnsRecord> result = (List<DnsRecord>) future.getNow(); result.forEach(ReferenceCountUtil::safeRelease); }/*from ww w . j ava 2 s .c om*/ 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(this::sendQueries, 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(this::sendQueries, effectiveTtl, TimeUnit.SECONDS); } }
From source file:com.linecorp.armeria.client.http.HttpClientDelegate.java
License:Apache License
@Override public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { final Endpoint endpoint = ctx.endpoint().resolve().withDefaultPort(ctx.sessionProtocol().defaultPort()); autoFillHeaders(ctx, endpoint, req); final PoolKey poolKey = new PoolKey(InetSocketAddress.createUnresolved(endpoint.host(), endpoint.port()), ctx.sessionProtocol());/* w ww .jav a 2 s. co m*/ final EventLoop eventLoop = ctx.eventLoop(); final Future<Channel> channelFuture = pool(eventLoop).acquire(poolKey); final DecodedHttpResponse res = new DecodedHttpResponse(eventLoop); if (channelFuture.isDone()) { if (channelFuture.isSuccess()) { Channel ch = channelFuture.getNow(); invoke0(ch, ctx, req, res, poolKey); } else { res.close(channelFuture.cause()); } } else { channelFuture.addListener((Future<Channel> future) -> { if (future.isSuccess()) { Channel ch = future.getNow(); invoke0(ch, ctx, req, res, poolKey); } else { res.close(channelFuture.cause()); } }); } return res; }
From source file:com.linecorp.armeria.client.HttpClientDelegate.java
License:Apache License
@Override public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { final Endpoint endpoint = ctx.endpoint().resolve(ctx).withDefaultPort(ctx.sessionProtocol().defaultPort()); autoFillHeaders(ctx, endpoint, req); if (!sanitizePath(req)) { req.abort();//from ww w . j a v a 2s.c o m return HttpResponse.ofFailure(new IllegalArgumentException("invalid path: " + req.path())); } final EventLoop eventLoop = ctx.eventLoop(); final PoolKey poolKey = new PoolKey(endpoint.host(), endpoint.ipAddr(), endpoint.port(), ctx.sessionProtocol()); final Future<Channel> channelFuture = factory.pool(eventLoop).acquire(poolKey); final DecodedHttpResponse res = new DecodedHttpResponse(eventLoop); if (channelFuture.isDone()) { if (channelFuture.isSuccess()) { final Channel ch = channelFuture.getNow(); invoke0(ch, ctx, req, res, poolKey); } else { res.close(channelFuture.cause()); } } else { channelFuture.addListener((Future<Channel> future) -> { if (future.isSuccess()) { final Channel ch = future.getNow(); invoke0(ch, ctx, req, res, poolKey); } else { res.close(channelFuture.cause()); } }); } return res; }
From source file:com.linecorp.armeria.client.HttpRemoteInvoker.java
License:Apache License
@Override public <T> Future<T> invoke(EventLoop eventLoop, URI uri, ClientOptions options, ClientCodec codec, Method method, Object[] args) throws Exception { requireNonNull(uri, "uri"); requireNonNull(options, "options"); requireNonNull(codec, "codec"); requireNonNull(method, "method"); final Scheme scheme = Scheme.parse(uri.getScheme()); final SessionProtocol sessionProtocol = validateSessionProtocol(scheme.sessionProtocol()); final InetSocketAddress remoteAddress = convertToSocketAddress(uri, sessionProtocol.isTls()); final PoolKey poolKey = new PoolKey(remoteAddress, sessionProtocol); final Future<Channel> channelFuture = pool(eventLoop).acquire(poolKey); final Promise<T> resultPromise = eventLoop.newPromise(); codec.prepareRequest(method, args, resultPromise); if (channelFuture.isSuccess()) { Channel ch = channelFuture.getNow(); invoke0(codec, ch, method, args, options, resultPromise, poolKey); } else {/* w w w.ja v a 2 s . c om*/ channelFuture.addListener((Future<Channel> future) -> { if (future.isSuccess()) { Channel ch = future.getNow(); invoke0(codec, ch, method, args, options, resultPromise, poolKey); } else { resultPromise.setFailure(channelFuture.cause()); } }); } return resultPromise; }
From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java
License:Apache License
private void notifyConnect(K key, Future<Channel> future, Promise<Channel> promise) { assert future.isDone(); try {//from w w w .j a va 2s. c o m if (future.isSuccess()) { Channel channel = future.getNow(); channel.attr(KeyedChannelPoolUtil.POOL).set(this); channelPoolHandler.channelCreated(key, channel); channel.closeFuture().addListener(f -> channelPoolHandler.channelClosed(key, channel)); promise.setSuccess(channel); } else { promise.setFailure(future.cause()); } } catch (Exception e) { promise.setFailure(e); } }
From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java
License:Apache License
private void notifyHealthCheck(final K key, Future<Boolean> future, Channel ch, Promise<Channel> promise) { assert ch.eventLoop().inEventLoop(); if (future.isSuccess()) { if (future.getNow() == Boolean.TRUE) { try { ch.attr(KeyedChannelPoolUtil.POOL).set(this); channelPoolHandler.channelAcquired(key, ch); promise.setSuccess(ch);// ww w.ja va 2s. c o m } catch (Throwable cause) { closeAndFail(ch, cause, promise); } } else { closeChannel(ch); acquireHealthyFromPoolOrNew(key, promise); } } else { closeChannel(ch); acquireHealthyFromPoolOrNew(key, promise); } }
From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java
License:Apache License
private void releaseAndOfferIfHealthy(K key, Channel channel, Promise<Void> promise, Future<Boolean> future) throws Exception { if (future.getNow()) { //channel turns out to be healthy, offering and releasing it. releaseAndOffer(key, channel, promise); } else { //channel ont healthy, just releasing it. channelPoolHandler.channelReleased(key, channel); closeAndFail(channel, UNHEALTHY_NON_OFFERED_TO_POOL, promise); }/*from w w w . j a va 2 s . c om*/ }
From source file:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override/*from w w w . ja v a2 s . c om*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, request.dstAddrType())); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.spotify.netty4.handler.codec.zmtp.ListenableFutureAdapter.java
License:Apache License
@Override public void operationComplete(final Future<V> future) throws Exception { if (future.isSuccess()) { set(future.getNow()); } else {/* ww w . ja va2 s . c om*/ setException(future.cause()); } }