List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:io.jsync.http.impl.DefaultHttpServerResponse.java
License:Open Source License
private void doSendFile(String filename, String notFoundResource, final Handler<AsyncResult<Void>> resultHandler) { if (headWritten) { throw new IllegalStateException("Head already written"); }//w w w. j av a 2 s . c om checkWritten(); File file = new File(PathAdjuster.adjust(async, filename)); if (!file.exists()) { if (notFoundResource != null) { setStatusCode(HttpResponseStatus.NOT_FOUND.code()); sendFile(notFoundResource, (String) null, resultHandler); } else { sendNotFound(); } } else if (file.isDirectory()) { // send over a 403 Forbidden sendForbidden(); } else { if (!contentLengthSet()) { putHeader(io.jsync.http.HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length())); } if (!contentTypeSet()) { int li = filename.lastIndexOf('.'); if (li != -1 && li != filename.length() - 1) { String ext = filename.substring(li + 1, filename.length()); String contentType = MimeUtils.getMimeTypeForExtension(ext); if (contentType != null) { putHeader(io.jsync.http.HttpHeaders.CONTENT_TYPE, contentType); } } } prepareHeaders(); conn.queueForWrite(response); conn.sendFile(file); // write an empty last content to let the http encoder know the response is complete channelFuture = conn.write(LastHttpContent.EMPTY_LAST_CONTENT); headWritten = written = true; if (resultHandler != null) { channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { final AsyncResult<Void> res; if (future.isSuccess()) { res = new DefaultFutureResult<>((Void) null); } else { res = new DefaultFutureResult<>(future.cause()); } async.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } if (!keepAlive) { closeConnAfterWrite(); } conn.responseComplete(); } }
From source file:io.jsync.http.impl.DefaultHttpServerResponse.java
License:Open Source License
private void closeConnAfterWrite() { if (channelFuture != null) { channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { conn.close();//from ww w. jav a 2 s . c o m } }); } }
From source file:io.jsync.http.impl.ServerConnection.java
License:Open Source License
NetSocket createNetSocket() { DefaultNetSocket socket = new DefaultNetSocket(async, channel, context, server.tcpHelper, false); Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(1); connectionMap.put(channel, socket);/* w ww. j a v a 2 s . c om*/ // Flush out all pending data endReadAndFlush(); // remove old http handlers and replace the old handler with one that handle plain sockets ChannelPipeline pipeline = channel.pipeline(); ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class); if (compressor != null) { pipeline.remove(compressor); } pipeline.remove("httpDecoder"); if (pipeline.get("chunkedWriter") != null) { pipeline.remove("chunkedWriter"); } channel.pipeline().replace("handler", "handler", new AsyncNetHandler(server.async, connectionMap) { @Override public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception { // remove from the real mapping server.connectionMap.remove(channel); super.exceptionCaught(chctx, t); } @Override public void channelInactive(ChannelHandlerContext chctx) throws Exception { // remove from the real mapping server.connectionMap.remove(channel); super.channelInactive(chctx); } @Override public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpContent) { ReferenceCountUtil.release(msg); return; } super.channelRead(chctx, msg); } }); // check if the encoder can be removed yet or not. if (lastWriteFuture == null) { channel.pipeline().remove("httpEncoder"); } else { lastWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel.pipeline().remove("httpEncoder"); } }); } return socket; }
From source file:io.jsync.net.impl.ConnectionBase.java
License:Open Source License
protected void addFuture(final Handler<AsyncResult<Void>> doneHandler, final ChannelFuture future) { if (future != null) { future.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (doneHandler != null) { context.execute(new Runnable() { public void run() { if (channelFuture.isSuccess()) { doneHandler.handle(new DefaultFutureResult<>((Void) null)); } else { doneHandler.handle(new DefaultFutureResult<Void>(channelFuture.cause())); }/*from ww w . j a va2s .c o m*/ } }); } else if (!channelFuture.isSuccess()) { handleException(channelFuture.cause()); } } }); } }
From source file:io.jsync.net.impl.ConnectionBase.java
License:Open Source License
protected ChannelFuture sendFile(File file) { final RandomAccessFile raf; try {//from ww w . ja v a 2 s . co m raf = new RandomAccessFile(file, "r"); long fileLength = file.length(); // Write the content. ChannelFuture writeFuture; if (!supportsFileRegion()) { // Cannot use zero-copy writeFuture = write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = write(region); } writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { raf.close(); } }); return writeFuture; } catch (IOException e) { handleException(e); return null; } }
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.jav a 2 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); } } } }); }
From source file:io.jsync.net.impl.DefaultNetServer.java
License:Open Source License
public NetServer listen(final int port, final String host, final Handler<AsyncResult<NetServer>> listenHandler) { if (connectHandler == null) { throw new IllegalStateException("Set connect handler first"); }//ww w. j av a 2 s . com if (listening) { throw new IllegalStateException("Listen already called"); } listening = true; this.host = host; synchronized (async.sharedNetServers()) { id = new ServerID(port, host); DefaultNetServer shared = (DefaultNetServer) async.sharedNetServers().get(id); if (shared == null || port == 0) { // Wildcard port will imply a new actual server each time serverChannelGroup = new DefaultChannelGroup("async-acceptor-channels", GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(availableWorkers); bootstrap.channel(NioServerSocketChannel.class); tcpHelper.checkSSL(async); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { SslHandler sslHandler = tcpHelper.createSslHandler(async, false); 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 ServerHandler()); } }); tcpHelper.applyConnectionOptions(bootstrap); if (connectHandler != null) { // Share the event loop thread to also serve the NetServer's network traffic. handlerManager.addHandler(connectHandler, actualCtx); } try { InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(host), port); bindFuture = bootstrap.bind(addr).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { runListeners(); } }); this.addListener(new Runnable() { @Override public void run() { if (bindFuture.isSuccess()) { log.trace("Net server listening on " + host + ":" + bindFuture.channel().localAddress()); // Update port to actual port - wildcard port 0 might have been used DefaultNetServer.this.port = ((InetSocketAddress) bindFuture.channel() .localAddress()).getPort(); DefaultNetServer.this.id = new ServerID(DefaultNetServer.this.port, id.host); async.sharedNetServers().put(id, DefaultNetServer.this); } else { async.sharedNetServers().remove(id); } } }); serverChannelGroup.add(bindFuture.channel()); } catch (final Throwable t) { // Make sure we send the exception back through the handler (if any) if (listenHandler != null) { async.runOnContext(new VoidHandler() { @Override protected void handle() { listenHandler.handle(new DefaultFutureResult<NetServer>(t)); } }); } else { // No handler - log so user can see failure actualCtx.reportException(t); } listening = false; return this; } if (port != 0) { async.sharedNetServers().put(id, this); } actualServer = this; } else { // Server already exists with that host/port - we will use that checkConfigs(actualServer, this); actualServer = shared; this.port = shared.port(); if (connectHandler != null) { // Share the event loop thread to also serve the NetServer's network traffic. actualServer.handlerManager.addHandler(connectHandler, actualCtx); } } // just add it to the future so it gets notified once the bind is complete actualServer.addListener(new Runnable() { public void run() { if (listenHandler != null) { final AsyncResult<NetServer> res; if (actualServer.bindFuture.isSuccess()) { res = new DefaultFutureResult<NetServer>(DefaultNetServer.this); } else { listening = false; res = new DefaultFutureResult<>(actualServer.bindFuture.cause()); } actualCtx.execute(actualServer.bindFuture.channel().eventLoop(), new Runnable() { @Override public void run() { listenHandler.handle(res); } }); } else if (!actualServer.bindFuture.isSuccess()) { // No handler - log so user can see failure actualCtx.reportException(actualServer.bindFuture.cause()); listening = false; } } }); } return this; }
From source file:io.jsync.net.impl.DefaultNetSocket.java
License:Open Source License
@Override public NetSocket sendFile(String filename, final Handler<AsyncResult<Void>> resultHandler) { File f = new File(PathAdjuster.adjust(async, filename)); if (f.isDirectory()) { throw new IllegalArgumentException("filename must point to a file and not to a directory"); }//from ww w . ja v a 2 s . c o m ChannelFuture future = super.sendFile(f); if (resultHandler != null) { future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { final AsyncResult<Void> res; if (future.isSuccess()) { res = new DefaultFutureResult<>((Void) null); } else { res = new DefaultFutureResult<>(future.cause()); } async.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } return this; }
From source file:io.netty.example.uptime.UptimeClient.java
License:Apache License
static void connect() { bs.connect().addListener(new ChannelFutureListener() { @Override//from www . j a v a 2 s. com public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() != null) { handler.startTime = -1; handler.println("Failed to connect: " + future.cause()); } } }); }
From source file:io.nodyn.tcp.TCPWrap.java
License:Apache License
public void listen(int backlog) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(this.process.getEventLoop().getEventLoopGroup()); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override//from w w w. jav a 2 s.co m protected void initChannel(Channel ch) throws Exception { ch.config().setAutoRead(false); // ch.pipeline().addLast("debug", new DebugHandler("server")); ch.pipeline().addLast("emit.connection", new ConnectionEventHandler(TCPWrap.this.process, TCPWrap.this)); ch.pipeline().addLast("handle", new UnrefHandler(TCPWrap.this)); } }); this.channelFuture = bootstrap.bind(this.addr, this.port); this.channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // TODO callback error } }); ref(); }