Example usage for io.netty.channel ChannelFuture addListener

List of usage examples for io.netty.channel ChannelFuture addListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture addListener.

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:com.rs3e.network.session.impl.UpdateSession.java

License:Open Source License

@Override
public void message(Object obj) {
    if (handshakeComplete) {
        if (obj instanceof FileRequest) {
            FileRequest request = (FileRequest) obj;

            synchronized (fileQueue) {
                if (request.isPriority()) {
                    fileQueue.addFirst(request);
                } else {
                    fileQueue.addLast(request);
                }/*from  w w w  .  j  a  v  a  2 s  .  c o m*/

                if (idle) {
                    service.addPendingSession(this);
                    idle = false;
                }
            }
        } else if (obj instanceof UpdateEncryptionMessage) {
            UpdateEncryptionMessage encryption = (UpdateEncryptionMessage) obj;
            XorEncoder encoder = channel.pipeline().get(XorEncoder.class);
            encoder.setKey(encryption.getKey());
        }
    } else {
        UpdateVersionMessage version = (UpdateVersionMessage) obj;

        int status;
        if (version.getVersion() == Constants.ServerRevision) {
            status = UpdateStatusMessage.STATUS_OK;
        } else {
            status = UpdateStatusMessage.STATUS_OUT_OF_DATE;
        }

        ChannelFuture future = channel.write(new UpdateStatusMessage(status));
        if (status == UpdateStatusMessage.STATUS_OK) {
            /*
             * the client won't re-connect so an ondemand session cannot
             * time out
             */
            channel.pipeline().remove(ReadTimeoutHandler.class);
            handshakeComplete = true;
        } else {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:com.sangupta.swift.netty.http.HttpStaticFileServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST);
        return;/*from   w w w  .  j  av a 2  s  . c o m*/
    }

    if (request.getMethod() != HttpMethod.GET) {
        NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    final String path = NettyUtils.sanitizeUri(uri);
    if (path == null) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(documentRoot, path);
    if (file.isHidden() || !file.exists()) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            NettyUtils.sendListing(context, file);
        } else {
            NettyUtils.sendRedirect(context, uri + '/');
        }

        return;
    }

    if (!file.isFile()) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince);

        if (ifModifiedSinceDate != null) {
            // Only compare up to the second because the datetime format we send to the client
            // does not have milliseconds
            long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
            long fileLastModifiedSeconds = file.lastModified() / 1000;

            if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
                NettyUtils.sendNotModified(context);
                return;
            }
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    final long fileLength = file.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, fileLength);
    NettyUtils.setContentTypeHeader(response, file);
    NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour

    // check for keep alive
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    context.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (context.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                context.newProgressivePromise());
    } else {
        sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                context.newProgressivePromise());
    }

    //      sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
    //
    //         @Override
    //         public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
    //            if (total < 0) { // total unknown
    //               System.err.println(future.channel() + " Transfer progress: " + progress);
    //            } else {
    //               System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
    //            }
    //         }
    //
    //         @Override
    //         public void operationComplete(ChannelProgressiveFuture future) {
    //            System.err.println(future.channel() + " Transfer complete.");
    //         }
    //         
    //      });

    // Write the end marker
    ChannelFuture lastContentFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.sangupta.swift.netty.proxy.ProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext channelHandlerContext) {
    final Channel inboundChannel = channelHandlerContext.channel();

    // Start the connection attempt.
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(inboundChannel.eventLoop()).channel(channelHandlerContext.channel().getClass())
            .handler(new ProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    ChannelFuture channelFuture = bootstrap.connect(remoteHost, remotePort);
    outboundChannel = channelFuture.channel();

    channelFuture.addListener(new ChannelFutureListener() {
        @Override/*from   w  ww.j av  a2  s . co m*/
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.sangupta.swift.netty.spdy.SpdyStaticFileServerHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext context, final FullHttpRequest request)
        throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST);
        return;//www . j  a v a2s . c o  m
    }

    // check for server name
    if (this.checkServerName) {
        String host = request.headers().get(HttpHeaders.Names.HOST);
        if (!host.startsWith(this.swiftServer.getServerName())) {
            NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST);
            return;
        }
    }

    // check method
    if (request.getMethod() != HttpMethod.GET) {
        NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;
    }

    // check for SPDY support
    final boolean spdyRequest = request.headers().contains(NettyUtils.SPDY_STREAM_ID);

    // check for URI path to be proper
    final String uri = request.getUri();
    final String path = NettyUtils.sanitizeUri(uri);
    if (path == null) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(documentRoot, path);
    if (file.isHidden() || !file.exists()) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            NettyUtils.sendListing(context, file, request.headers().get(NettyUtils.SPDY_STREAM_ID));
            return;
        }

        // redirect to the listing page
        NettyUtils.sendRedirect(context, uri + '/');
        return;
    }

    if (!file.isFile()) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince);

        if (ifModifiedSinceDate != null) {
            // Only compare up to the second because the datetime format we send to the client
            // does not have milliseconds
            long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
            long fileLastModifiedSeconds = file.lastModified() / 1000;

            if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
                NettyUtils.sendNotModified(context);
                return;
            }
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    final long fileLength = file.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, fileLength);
    NettyUtils.setContentTypeHeader(response, file);
    NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour

    // check for keep alive
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    } else {
        context.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    // Write the initial line and the header.
    context.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (context.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                context.newProgressivePromise());
    } else {
        sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                context.newProgressivePromise());
    }

    //      sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
    //
    //         @Override
    //         public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
    //            if (total < 0) { // total unknown
    //               System.err.println(future.channel() + " Transfer progress: " + progress);
    //            } else {
    //               System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
    //            }
    //         }
    //
    //         @Override
    //         public void operationComplete(ChannelProgressiveFuture future) {
    //            System.err.println(future.channel() + " Transfer complete.");
    //         }
    //         
    //      });

    // Write the end marker
    ChannelFuture lastContentFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.sheldon.javaPrj.netty.TimeServerHandler.java

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    final ByteBuf time = ctx.alloc().buffer(4);
    time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

    final ChannelFuture f = ctx.writeAndFlush(time); // (3)
    f.addListener(new ChannelFutureListener() {
        @Override/* w w  w  . j av a2s . c  om*/
        public void operationComplete(ChannelFuture future) {
            assert f == future;
            ctx.close();
        }
    }); // (4)
}

From source file:com.slyak.services.proxy.handler.Socks5CommandRequestHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext requestChannelContext,
        final DefaultSocks5CommandRequest msg) throws Exception {
    if (Socks5CommandType.CONNECT.equals(msg.type())) {
        log.debug("Start to connect remote server : {}:{}", msg.dstAddr(), msg.dstPort());
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(remoteEventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override//w w  w . j  a  va 2 s. co  m
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new IdleStateHandler(0, 0, 30));
                        pipeline.addLast(new IdleEventHandler());
                        pipeline.addLast(new Remote2RequestHandler(requestChannelContext.channel()));
                        pipeline.addLast(ExceptionHandler.INSTANCE);
                    }
                });
        final ChannelFuture future = bootstrap.connect(msg.dstAddr(), msg.dstPort());
        this.remoteChannel = future.channel();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture connectFuture) throws Exception {
                if (connectFuture.isSuccess()) {
                    log.debug("Connected to remote server");
                    requestChannelContext.pipeline().addLast(new Request2RemoteHandler(remoteChannel));
                    Socks5CommandResponse response = new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, Socks5AddressType.IPv4);
                    //add client to dest handler to receive response
                    requestChannelContext.writeAndFlush(response);
                } else {
                    log.debug("Failed to connect to remote server");
                    Socks5CommandResponse commandResponse = new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.FAILURE, Socks5AddressType.IPv4);
                    requestChannelContext.writeAndFlush(commandResponse);
                }
            }
        });
    } else {
        log.debug("Fire channel read");
        requestChannelContext.fireChannelRead(msg);
    }
}

From source file:com.snh.chat.core.group.DefaultChannelGroupFuture.java

License:Apache License

/**
 * Creates a new instance.//  www.ja v  a 2s  .co m
 */
DefaultChannelGroupFuture(ChannelGroup group, Collection<ChannelFuture> futures, EventExecutor executor) {
    super(executor);
    if (group == null) {
        throw new NullPointerException("group");
    }
    if (futures == null) {
        throw new NullPointerException("futures");
    }

    this.group = group;

    Map<Channel, ChannelFuture> futureMap = new LinkedHashMap<Channel, ChannelFuture>();
    for (ChannelFuture f : futures) {
        futureMap.put(f.channel(), f);
    }

    this.futures = Collections.unmodifiableMap(futureMap);

    for (ChannelFuture f : this.futures.values()) {
        f.addListener(childListener);
    }

    // Done on arrival?
    if (this.futures.isEmpty()) {
        setSuccess0();
    }
}

From source file:com.snh.chat.core.group.DefaultChannelGroupFuture.java

License:Apache License

DefaultChannelGroupFuture(ChannelGroup group, Map<Channel, ChannelFuture> futures, EventExecutor executor) {
    super(executor);
    this.group = group;
    this.futures = Collections.unmodifiableMap(futures);
    for (ChannelFuture f : this.futures.values()) {
        f.addListener(childListener);
    }/* w ww. j a  v  a  2s . c o m*/

    // Done on arrival?
    if (this.futures.isEmpty()) {
        setSuccess0();
    }
}

From source file:com.sohail.alam.http.common.utils.HttpResponseSender.java

License:Apache License

/**
 * Send channel future.//from   w w  w  . j  a  v a 2s  . co m
 *
 * @param ctx                the ctx
 * @param status             the status
 * @param headersMap         the headers map
 * @param data               the data
 * @param useDefaultListener use default listener
 *
 * @return the channel future
 */
public static ChannelFuture send(ChannelHandlerContext ctx, HttpResponseStatus status,
        Map<String, String> headersMap, byte[] data, boolean useDefaultListener) {
    final HttpResponse response;
    // Create the headers map if null
    if (headersMap == null) {
        headersMap = new HashMap<String, String>();
    }
    // If data is not null then add content length header and send Full Http Response
    if (data != null) {
        ByteBuf dataBuffer = copiedBuffer(data);
        response = new DefaultFullHttpResponse(HTTP_1_1, status, dataBuffer);
        // If no content length is supplied then calculate it and add it
        if (headersMap.get(CONTENT_LENGTH) == null) {
            headersMap.put(CONTENT_LENGTH, String.valueOf(data.length));
        }
    }
    // If data is null then add content length header to 0
    else {
        response = new DefaultHttpResponse(HTTP_1_1, status);
        headersMap.put(CONTENT_LENGTH, String.valueOf(0));
    }
    // Iterate all headers from map and set response headers
    for (String header : headersMap.keySet()) {
        response.headers().set(header, headersMap.get(header));
    }
    // Send the response
    ChannelFuture future = ctx.channel().write(response);
    // Use default future listener if needed
    if (useDefaultListener) {
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    LOGGER.debug("Response sent successfully:\n{}", response);
                } else {
                    LOGGER.debug("FAILED TO SEND RESPONSE!!\n{}", response);
                }
            }
        });
    }

    return future;
}

From source file:com.soho.framework.server.netty.http.AsyncHttpServletHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception {
    if (e instanceof ServletResponse) {
        logger.info("Handler async task...");
        HttpServletResponse response = (HttpServletResponse) e;
        Runnable task = ThreadLocalAsyncExecutor.pollTask(response);
        task.run();//from w w  w.ja va 2 s  .  c o  m

        // write response...
        ChannelFuture future = ctx.channel().writeAndFlush(response);

        String keepAlive = response.getHeader(CONNECTION);
        if (null != keepAlive && HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(keepAlive)) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    } else {
        ctx.fireChannelRead(e);
    }
}