List of usage examples for io.netty.util.concurrent Future addListener
Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
From source file:io.airlift.drift.transport.netty.client.ConnectionPool.java
License:Apache License
private static void closeConnection(Future<Channel> future) { future.addListener(ignored -> { if (future.isSuccess()) { Channel channel = future.getNow(); channel.close();//from w ww .j a va 2s . c om } }); }
From source file:io.airlift.drift.transport.netty.InvocationAttempt.java
License:Apache License
private void tryNextAddress() { // request was already canceled if (future.isCancelled()) { return;/*from ww w .j ava 2 s . c o m*/ } if (!addresses.hasNext()) { Throwable cause = lastException.get(); if (cause != null) { future.fatalError(cause); } else { future.fatalError(new TTransportException("No hosts available")); } return; } HostAndPort address = addresses.next(); Future<Channel> channelFuture = connectionManager.getConnection(address); currentTask.set(channelFuture); channelFuture.addListener(new SafeFutureCallback<Channel>() { @Override public void safeOnSuccess(Channel channel) { tryInvocation(channel, address); } @Override public void safeOnFailure(Throwable t) { lastException.set(t); onConnectionFailed.accept(address); tryNextAddress(); } }); }
From source file:io.codis.nedis.NedisClientPoolImpl.java
License:Apache License
private Future<NedisClient> newClient() { Future<NedisClientImpl> f = NedisClientBuilder.create().group(group).channel(channelClass) .timeoutMs(timeoutMs).belongTo(this).connect(remoteAddress); final Promise<NedisClient> promise = getEventExecutor(f).newPromise(); f.addListener(new FutureListener<NedisClientImpl>() { @Override//from ww w. j ava 2 s .co m public void operationComplete(Future<NedisClientImpl> future) throws Exception { if (future.isSuccess()) { initialize(promise, future.getNow(), State.AUTH); } else { promise.tryFailure(future.cause()); } } }); return promise; }
From source file:io.getlime.push.service.PushMessageSenderService.java
License:Apache License
private void sendMessageToIos(final ApnsClient apnsClient, final PushMessageBody pushMessageBody, final PushMessageAttributes attributes, final String pushToken, final String iosTopic, final PushSendingCallback callback) throws PushServerException { final String token = TokenUtil.sanitizeTokenString(pushToken); final String payload = buildApnsPayload(pushMessageBody, attributes == null ? false : attributes.getSilent()); // In case there are no attributes, the message is not silent Date validUntil = pushMessageBody.getValidUntil(); final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, iosTopic, payload, validUntil, DeliveryPriority.IMMEDIATE, pushMessageBody.getCollapseKey()); final Future<PushNotificationResponse<SimpleApnsPushNotification>> sendNotificationFuture = apnsClient .sendNotification(pushNotification); sendNotificationFuture.addListener( new GenericFutureListener<Future<PushNotificationResponse<SimpleApnsPushNotification>>>() { @Override//from w w w . j a v a 2 s . co m public void operationComplete( Future<PushNotificationResponse<SimpleApnsPushNotification>> future) throws Exception { try { final PushNotificationResponse<SimpleApnsPushNotification> pushNotificationResponse = future .get(); if (pushNotificationResponse != null) { if (!pushNotificationResponse.isAccepted()) { Logger.getLogger(PushMessageSenderService.class.getName()).log(Level.SEVERE, "Notification rejected by the APNs gateway: " + pushNotificationResponse.getRejectionReason()); if (pushNotificationResponse.getRejectionReason().equals("BadDeviceToken")) { Logger.getLogger(PushMessageSenderService.class.getName()).log(Level.SEVERE, "\t... due to bad device token value."); callback.didFinishSendingMessage(PushSendingCallback.Result.FAILED_DELETE, null); } else if (pushNotificationResponse.getTokenInvalidationTimestamp() != null) { Logger.getLogger(PushMessageSenderService.class.getName()).log(Level.SEVERE, "\t... and the token is invalid as of " + pushNotificationResponse.getTokenInvalidationTimestamp()); callback.didFinishSendingMessage(PushSendingCallback.Result.FAILED_DELETE, null); } } else { callback.didFinishSendingMessage(PushSendingCallback.Result.OK, null); } } else { Logger.getLogger(PushMessageSenderService.class.getName()).log(Level.SEVERE, "Notification rejected by the APNs gateway: unknown error, will retry"); callback.didFinishSendingMessage(PushSendingCallback.Result.PENDING, null); } } catch (ExecutionException | InterruptedException e) { callback.didFinishSendingMessage(PushSendingCallback.Result.FAILED, null); } } }); }
From source file:io.jsync.http.impl.DefaultHttpClient.java
License:Open Source License
void internalConnect(final Handler<ClientConnection> connectHandler, final Handler<Throwable> connectErrorHandler) { if (bootstrap == null) { // Share the event loop thread to also serve the HttpClient's network traffic. AsyncEventLoopGroup pool = new AsyncEventLoopGroup(); pool.addWorker(actualCtx.getEventLoop()); bootstrap = new Bootstrap(); bootstrap.group(pool);/* w ww . j a v a 2 s. c o m*/ bootstrap.channel(NioSocketChannel.class); tcpHelper.checkSSL(async); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { pipeline.addLast("ssl", tcpHelper.createSslHandler(async, true, host, port)); } pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false)); if (tryUseCompression) { pipeline.addLast("inflater", new HttpContentDecompressor(true)); } pipeline.addLast("handler", new ClientHandler()); } }); } tcpHelper.applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { final Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (tcpHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { connected(ch, connectHandler); } else { connectionFailed(ch, connectErrorHandler, new SSLHandshakeException("Failed to create SSL connection")); } } }); } else { connected(ch, connectHandler); } } else { connectionFailed(ch, connectErrorHandler, channelFuture.cause()); } } }); }
From source file:io.jsync.net.impl.DefaultNetClient.java
License:Open Source License
private void connect(final int port, final String host, final Handler<AsyncResult<NetSocket>> connectHandler, final int remainingAttempts) { if (bootstrap == null) { tcpHelper.checkSSL(async);/*from ww w . j a va2s.c o m*/ bootstrap = new Bootstrap(); bootstrap.group(actualCtx.getEventLoop()); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { SslHandler sslHandler = tcpHelper.createSslHandler(async, true); pipeline.addLast("ssl", sslHandler); } if (tcpHelper.isSSL()) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } pipeline.addLast("handler", new AsyncNetHandler(async, socketMap)); } }); configurable = false; } tcpHelper.applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { final Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (tcpHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { connected(ch, connectHandler); } else { failed(ch, future.cause(), connectHandler); } } }); } else { connected(ch, connectHandler); } } else { if (remainingAttempts > 0 || remainingAttempts == -1) { actualCtx.execute(ch.eventLoop(), new Runnable() { public void run() { log.debug("Failed to create connection. Will retry in " + reconnectInterval + " milliseconds"); //Set a timer to retry connection async.setTimer(reconnectInterval, new Handler<Long>() { public void handle(Long timerID) { connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1); } }); } }); } else { failed(ch, channelFuture.cause(), connectHandler); } } } }); }
From source file:io.lettuce.core.AbstractRedisClient.java
License:Apache License
private static CompletableFuture<Void> toCompletableFuture(Future<?> future) { CompletableFuture<Void> promise = new CompletableFuture<>(); if (future.isDone() || future.isCancelled()) { if (future.isSuccess()) { promise.complete(null);/*from w w w . j a v a 2 s . c om*/ } else { promise.completeExceptionally(future.cause()); } return promise; } future.addListener(f -> { if (f.isSuccess()) { promise.complete(null); } else { promise.completeExceptionally(f.cause()); } }); return promise; }
From source file:io.lettuce.core.resource.Futures.java
License:Apache License
/** * Create a promise that emits a {@code Boolean} value on completion of the {@code future} * * @param future the future.//from w ww.j a va2 s . c om * @return Promise emitting a {@code Boolean} value. {@literal true} if the {@code future} completed successfully, otherwise * the cause wil be transported. */ static Promise<Boolean> toBooleanPromise(Future<?> future) { DefaultPromise<Boolean> result = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); if (future.isDone() || future.isCancelled()) { if (future.isSuccess()) { result.setSuccess(true); } else { result.setFailure(future.cause()); } return result; } future.addListener((GenericFutureListener<Future<Object>>) f -> { if (f.isSuccess()) { result.setSuccess(true); } else { result.setFailure(f.cause()); } }); return result; }
From source file:io.urmia.api.handler.RestApiHandler.java
License:Open Source License
private void setupProxyToGET(final ChannelHandlerContext ctx, final FullObjectName fon) throws Exception { log.info("proxy GET storage node: download mode: {}", true); final Future<List<String>> futureStorageNodes = mds.storedNodes(ctx.executor(), fon.attributes.etag); futureStorageNodes.addListener(new GenericFutureListener<Future<List<String>>>() { @Override// w w w . ja v a2 s.c om public void operationComplete(Future<List<String>> future) throws Exception { if (future.isSuccess()) { final List<String> st = future.getNow(); Optional<ServiceInstance<NodeType>> si = findStorageInstanceUp(st); if (!si.isPresent()) { log.error("failed to find running node, req: {}", objectRequest); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); return; } List<ServiceInstance<NodeType>> l = Lists.newArrayList(si.get()); log.info("proxy storage node: {}, download mode: {}, durability: {}", st, true, objectRequest.getDurability()); HttpProxyFrontendHandler proxy = new HttpProxyFrontendHandler(l, mds, httpRequest, ctx, true, Optional.<FullObjectName>absent()); ctx.pipeline().remove("encoder"); ctx.pipeline().addLast("proxy", proxy); proxyMode = true; ctx.read(); // todo: can ve removed? } else { log.error("failed to fetch futureStorageNodes, req: {}", objectRequest, future.cause()); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } }); }
From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java
License:Apache License
private void doResolveUncached(String hostname, Promise<InetAddress> promise, DnsCache resolveCache, boolean trySearchDomain) { if (trySearchDomain) { Promise<InetAddress> original = promise; promise = new DefaultPromise<>(executor()); FutureListener<InetAddress> globalListener = future -> { if (future.isSuccess()) { original.setSuccess(future.getNow()); } else { FutureListener<InetAddress> sdListener = new FutureListener<InetAddress>() { int count; @Override//from w w w. ja v a2 s. c o m public void operationComplete(Future<InetAddress> future) throws Exception { if (future.isSuccess()) { original.trySuccess(future.getNow()); } else { if (count < searchDomains.size()) { String searchDomain = searchDomains.get(count++); Promise<InetAddress> p = new DefaultPromise<>(executor()); doResolveUncached(hostname + "." + searchDomain, p, resolveCache, false); p.addListener(this); } else { original.tryFailure(future.cause()); } } } }; future.addListener(sdListener); } }; promise.addListener(globalListener); } if (searchDomains(hostname)) { promise.tryFailure(new UnknownHostException(hostname)); } else { final DnsNameResolverContext<InetAddress> ctx = new DnsNameResolverContext<InetAddress>(this, hostname, promise, resolveCache) { @Override protected boolean finishResolve(Class<? extends InetAddress> addressType, List<DnsCacheEntry> resolvedEntries) { final int numEntries = resolvedEntries.size(); for (int i = 0; i < numEntries; i++) { final InetAddress a = resolvedEntries.get(i).address(); if (addressType.isInstance(a)) { setSuccess(promise(), a); return true; } } return false; } }; ctx.resolve(); } }