List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener
GenericFutureListener
From source file:io.aos.netty5.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception { if (message instanceof Socks4CmdRequest) { final Socks4CmdRequest request = (Socks4CmdRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override//from w w w.j ava2 s . c o m public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS)) .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 Socks4CmdResponse(Socks4CmdStatus.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.host(), request.port()).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 Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CmdRequest) { final Socks5CmdRequest request = (Socks5CmdRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel() .writeAndFlush( new Socks5CmdResponse(Socks5CmdStatus.SUCCESS, request.addressType())) .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 Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType())); 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.host(), request.port()).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 Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:io.apigee.trireme.container.netty.UpgradedSocketHandler.java
License:Open Source License
@Override public void shutdownOutput(final IOCompletionHandler<Integer> handler) { log.debug("Shutting down output"); ChannelFuture future = channel.shutdownOutput(); future.addListener(new GenericFutureListener<Future<Void>>() { @Override/* ww w . ja v a 2 s. co m*/ public void operationComplete(Future<Void> voidFuture) { log.debug("Shutdown complete"); handler.ioComplete(0, 0); } }); }
From source file:io.apigee.trireme.container.netty.UpgradedSocketHandler.java
License:Open Source License
public int write(ByteBuffer buf, final IOCompletionHandler<Integer> handler) { final int len = buf.remaining(); ByteBuf nettyBuf = Unpooled.wrappedBuffer(buf); ChannelFuture future = channel.writeAndFlush(nettyBuf); if (log.isDebugEnabled()) { log.debug("Writing {} bytes to the upgraded socket", len); }//from w ww . ja v a 2 s .c om future.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> voidFuture) { if (log.isDebugEnabled()) { log.debug("Upgraded socket write complete"); } handler.ioComplete(0, len); } }); return len; }
From source file:io.flood.rpc.network.AcceptorImpl.java
License:Apache License
private void bind(final SocketAddress address) { id = SocketIdGenerator.nextId();//from www . ja v a 2 s . com boot = new ServerBootstrap(); boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel ch) throws Exception { LinkedHashMap<String, ChannelHandler> handlers = getHandlers(); for (Map.Entry<String, ChannelHandler> entry : handlers.entrySet()) { ch.pipeline().addLast(entry.getKey(), entry.getValue()); } ch.pipeline().addLast("messageDecoder", new MessageDecoder()); ch.pipeline().addLast("messageEncoder", new MessageEncoder()); ch.pipeline().addLast("messageHandler", new MessageHandler(AcceptorImpl.this)); } }); try { final ChannelFuture future = boot.bind(address).sync(); if (future.isSuccess()) { id = SocketIdGenerator.nextId(); LOG.info(format(id, "socket bind success({})"), address); ConnectionManager.put(id, Connection.Type.Server, future.channel()); onBindCompleted(future); future.channel().closeFuture() .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() { public void operationComplete(Future<? super Void> completefuture) throws Exception { LOG.info(format(id, "socket closed()")); serverChannel.remove(future.channel()); } }); } else { LOG.error(format(id, "socket bind failed({})"), address, future.cause()); } } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:io.flood.rpc.network.ConnectionManager.java
License:Apache License
public static void put(final int id, Connection.Type type, Channel channel) { channel.closeFuture().addListener(new GenericFutureListener() { public void operationComplete(Future future) throws Exception { remove(id);/*from ww w .j ava 2 s. co m*/ } }); connectionMap.put(id, new Connection(id, type, channel)); }
From source file:io.flood.rpc.network.ConnectorImpl.java
License:Apache License
private ChannelFuture connect0(final SocketAddress address, final int retryTime) { id = SocketIdGenerator.nextId();/*w ww.ja va 2s . com*/ final ChannelFuture future = boot.connect(address); future.addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(io.netty.util.concurrent.Future<? super Void> completeFuture) throws Exception { broadcastComplete(future); if (completeFuture.isSuccess()) { channel = future.channel(); LOG.info(LogHelper.format(id, "connected to server ({}=>{})"), channel.localAddress(), channel.remoteAddress()); ConnectionManager.put(id, Connection.Type.Client, channel); future.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> completeFuture) throws Exception { LOG.info( LogHelper.format(id, "connection closed ,after {} millisecond will be reconnect"), retryTime); if (!isInitiative.get()) { Thread.sleep(retryTime); connect0(address, retryTime); } } }); } else { LOG.info(LogHelper.format(id, "connet to server failed({})"), address); } } }); return future; }
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(//from w ww . j av a2 s . co m new GenericFutureListener<Future<PushNotificationResponse<SimpleApnsPushNotification>>>() { @Override 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.grpc.netty.NettyClientTransport.java
License:Apache License
@Override public ListenableFuture<SocketStats> getStats() { final SettableFuture<SocketStats> result = SettableFuture.create(); if (channel.eventLoop().inEventLoop()) { // This is necessary, otherwise we will block forever if we get the future from inside // the event loop. result.set(getStatsHelper(channel)); return result; }/*from w ww.j a va2 s. c o m*/ channel.eventLoop().submit(new Runnable() { @Override public void run() { result.set(getStatsHelper(channel)); } }).addListener(new GenericFutureListener<Future<Object>>() { @Override public void operationComplete(Future<Object> future) throws Exception { if (!future.isSuccess()) { result.setException(future.cause()); } } }); return result; }
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);/*from w w w . java 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);/*w w w. j a v a2 s . c om*/ 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); } } } }); }