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.phei.netty.nio.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from www  . jav  a  2 s .c  o m
        return;
    }

    if (request.method() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.uri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

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

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

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().getAndConvert(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaderUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaderUtil.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

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

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    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.");
        }
    });

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

From source file:com.phei.netty.nio.http.upload.HttpUploadServerHandler.java

License:Apache License

private void writeResponse(Channel channel) {
    // Convert the response content to a ChannelBuffer.
    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);//from  w  w  w  . j a va2s .  co  m

    // Decide whether to close the connection or not.
    boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
            || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers()
                    .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (!close) {
        // There's no need to add 'Content-Length' header
        // if this is the last response.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    }

    Set<Cookie> cookies;
    String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
    if (value == null) {
        cookies = Collections.emptySet();
    } else {
        cookies = ServerCookieDecoder.decode(value);
    }
    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        for (Cookie cookie : cookies) {
            response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie));
        }
    }
    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.phei.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    //http??//from  ww  w .  j a va 2  s . c o  m
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }
    //??get?
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    //uri??
    final String uri = request.getUri();
    final String path = sanitizeUri(uri);

    //URI??
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    //file
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// ??
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.pokersu.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);// ww w  . j  av  a2 s . com
        buf.release();
        //            HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (/*!HttpUtil.isKeepAlive(req) || */ res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.qq.servlet.demo.netty.sample.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from  www.j a v  a  2s  .  c o  m
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

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

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

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

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

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

    // Write the content.
    ChannelFuture sendFileFuture;
    if (useSendFile) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise());
    }

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

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

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

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

From source file:com.qq.servlet.demo.netty.sample.telnet.TelnetServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception {
    System.out.println(request);/*from ww  w . j av  a 2s. com*/
    // Generate and write a response.
    String response;
    boolean close = false;
    if (request.isEmpty()) {
        response = "Please type something.\r\n";
    } else if ("bye".equals(request.toLowerCase())) {
        response = "Have a good day!\r\n";
        close = true;
    } else {
        response = "Did you say '" + request + "'?\r\n";
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'bye'.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.qq.servlet.demo.netty.telnet.TelnetServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception {
    System.out.println(System.currentTimeMillis() + "\t" + request);
    //       Random random = new Random();
    //       Thread.sleep(random.nextInt(2000));
    Thread.sleep(1000);// www .j  a  v a 2s.  c o  m
    // Generate and write a response.
    String response = new Random().nextInt(100000000) + " " + System.currentTimeMillis();
    boolean close = false;
    if (request.isEmpty()) {
        response = "Please type something.\r\n";
    } else if ("bye".equals(request.toLowerCase())) {
        response = "Have a good day!\r\n";
        close = true;
    } else {
        response = "Did you say '" + request + "'?\r\n";
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'bye'.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * <p>Connects to the given APNs gateway on the given port.</p>
 *
 * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the
 * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection
 * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection
 * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p>
 *
 * @param host the APNs gateway to which to connect
 * @param port the port on which to connect to the APNs gateway
 *
 * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send
 * push notifications/*from  w  w w. ja  va 2 s  .c  o m*/
 *
 * @see ApnsClient#PRODUCTION_APNS_HOST
 * @see ApnsClient#DEVELOPMENT_APNS_HOST
 * @see ApnsClient#DEFAULT_APNS_PORT
 * @see ApnsClient#ALTERNATE_APNS_PORT
 *
 * @since 0.5
 */
public Future<Void> connect(final String host, final int port) {
    final Future<Void> connectionReadyFuture;

    if (this.bootstrap.config().group().isShuttingDown() || this.bootstrap.config().group().isShutdown()) {
        connectionReadyFuture = new FailedFuture<>(GlobalEventExecutor.INSTANCE, new IllegalStateException(
                "Client's event loop group has been shut down and cannot be restarted."));
    } else {
        synchronized (this.bootstrap) {
            // We only want to begin a connection attempt if one is not already in progress or complete; if we already
            // have a connection future, just return the existing promise.
            if (this.connectionReadyPromise == null) {
                this.metricsListener.handleConnectionAttemptStarted(this);

                final ChannelFuture connectFuture = this.bootstrap.connect(host, port);
                this.connectionReadyPromise = connectFuture.channel().newPromise();

                connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise;

                            if (connectionReadyPromise != null) {
                                // This may seem spurious, but our goal here is to accurately report the cause of
                                // connection failure; if we just wait for connection closure, we won't be able to
                                // tell callers anything more specific about what went wrong.
                                connectionReadyPromise.tryFailure(future.cause());
                            }
                        }
                    }
                });

                connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        synchronized (ApnsClient.this.bootstrap) {
                            if (ApnsClient.this.connectionReadyPromise != null) {
                                // We always want to try to fail the "connection ready" promise if the connection
                                // closes; if it has already succeeded, this will have no effect.
                                ApnsClient.this.connectionReadyPromise.tryFailure(new IllegalStateException(
                                        "Channel closed before HTTP/2 preface completed."));

                                ApnsClient.this.connectionReadyPromise = null;
                            }

                            if (ApnsClient.this.reconnectionPromise != null) {
                                log.debug("Disconnected. Next automatic reconnection attempt in {} seconds.",
                                        ApnsClient.this.reconnectDelaySeconds);

                                ApnsClient.this.scheduledReconnectFuture = future.channel().eventLoop()
                                        .schedule(new Runnable() {

                                            @Override
                                            public void run() {
                                                log.debug("Attempting to reconnect.");
                                                ApnsClient.this.connect(host, port);
                                            }
                                        }, ApnsClient.this.reconnectDelaySeconds, TimeUnit.SECONDS);

                                ApnsClient.this.reconnectDelaySeconds = Math.min(
                                        ApnsClient.this.reconnectDelaySeconds, MAX_RECONNECT_DELAY_SECONDS);
                            }
                        }
                    }
                });

                this.connectionReadyPromise.addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            synchronized (ApnsClient.this.bootstrap) {
                                if (ApnsClient.this.reconnectionPromise != null) {
                                    log.info("Connection to {} restored.", future.channel().remoteAddress());
                                    ApnsClient.this.reconnectionPromise.trySuccess();
                                } else {
                                    log.info("Connected to {}.", future.channel().remoteAddress());
                                }

                                ApnsClient.this.reconnectDelaySeconds = INITIAL_RECONNECT_DELAY_SECONDS;
                                ApnsClient.this.reconnectionPromise = future.channel().newPromise();
                            }

                            ApnsClient.this.metricsListener.handleConnectionAttemptSucceeded(ApnsClient.this);
                        } else {
                            log.info("Failed to connect.", future.cause());

                            ApnsClient.this.metricsListener.handleConnectionAttemptFailed(ApnsClient.this);
                        }
                    }
                });
            }

            connectionReadyFuture = this.connectionReadyPromise;
        }
    }

    return connectionReadyFuture;
}

From source file:com.repo.netty.proxy.HexDumpProxyFrontendHandler.java

License:Apache License

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

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();//from   w  w w .  j a  va2s.com
    f.addListener(new ChannelFutureListener() {
        @Override
        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.rr.echoserver.EchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    Threader<ChannelFuture> threader = new Threader<ChannelFuture>() {
        @Override//w w w  .  j  ava2s  .co m
        public ChannelFuture getValue() {
            System.out.println("About to write to " + ctx);
            return ctx.writeAndFlush(msg);
        }
    };
    ChannelFuture future;
    try {
        future = EchoServer.THREADED ? threader.executeOnDifferentThread() : threader.executeOnSameThread();
    } catch (InterruptedException ex) {
        throw new Error(ex);
    }
    System.out.println("Got future " + future);
    future.addListener(future1 -> System.out.println("Got completion " + future1));
}