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.jjzhk.Chapter11.websocket.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // ?????//from   w w  w .j a va  2s  .  com
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // ??Keep-Alive?
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.jt.flash.proxy.handler.ProxyFrontendHandler.java

License:Apache License

private void processRequest(final ChannelHandlerContext ctx, final Object msg, final Channel inboundChannel,
        String host, final int port) {
    Bootstrap b = buildBackendBootstrap(ctx, inboundChannel, port);
    ChannelFuture f = b.connect(host, port);
    outboundChannel = f.channel();//from   w w w .  j a va 2  s. c o  m

    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                log.info("connect ok, write {}", msg);
                outboundChannel.writeAndFlush(msg);
                /*
                .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
                }
                });*/

            } else {
                log.warn("connect fail");
                inboundChannel.close();
            }
        }
    });
}

From source file:com.just.server.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/* w  w  w  . j a  v 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, uri);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

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

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

        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);
    HttpUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpUtil.isKeepAlive(request)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    ctx.write(response);

    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());

        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());

        lastContentFuture = sendFileFuture;
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) {
                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 (!HttpUtil.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.kalixia.ha.cloud.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*w ww  .j a  va  2  s  .  co 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.kalixia.ha.hub.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from   w  w w.j av  a2  s .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
                logger.debug("Transfer progress: " + progress);
            } else {
                logger.debug("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            logger.debug("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.king.platform.net.http.netty.ChannelManager.java

License:Apache License

private void sendOnChannel(final Channel channel, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {

    httpRequestContext.attachedToChannel(channel);

    scheduleTimeOutTasks(requestEventBus, httpRequestContext, httpRequestContext.getTotalRequestTimeoutMillis(),
            httpRequestContext.getIdleTimeoutMillis());

    ChannelFuture channelFuture = channel.writeAndFlush(httpRequestContext);
    channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override//from   ww  w.  j  a  v a 2s.c  om
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }
        }
    });

    logger.trace("Wrote {} to channel {}", httpRequestContext, channel);
}

From source file:com.king.platform.net.http.netty.ChannelManager.java

License:Apache License

private void sendOnNewChannel(final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {
    final ServerInfo serverInfo = httpRequestContext.getServerInfo();

    ChannelFuture channelFuture = connect(serverInfo);

    channelFuture.addListener(new ChannelFutureListener() {

        @Override//from  ww  w . j ava2 s. c o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {

                requestEventBus.triggerEvent(Event.CREATED_CONNECTION, serverInfo);

                requestEventBus.triggerEvent(Event.onConnected);

                Channel channel = future.channel();
                channel.attr(ServerInfo.ATTRIBUTE_KEY).set(serverInfo);
                logger.trace("Opened a new channel {}, for request {}", channel, httpRequestContext);
                sendOnChannel(channel, httpRequestContext, requestEventBus);

            } else {
                logger.trace("Failed to opened a new channel for request {}", httpRequestContext);
                Throwable cause = future.cause();
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, cause);
            }
        }
    });
}

From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java

License:Apache License

private void writeHeaders(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext,
        HttpRequest httpRequest, final RequestEventBus requestEventBus) {
    httpRequestContext.getTimeRecorder().startWriteHeaders();
    ChannelFuture channelFuture = ctx.write(httpRequest);
    channelFuture.addListener(new ChannelFutureListener() {
        @Override/*from  ww w.j  av a2s .  co  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                logger.trace("Wrote headers operation completed, future: {}", future);
                requestEventBus.triggerEvent(Event.onWroteHeaders);
                requestEventBus.triggerEvent(Event.TOUCH);
                httpRequestContext.getTimeRecorder().completedWriteHeaders();

            } else {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }

        }
    });
}

From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java

License:Apache License

private void writeHttpBody(final ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext,
        HttpBody httpBody, final RequestEventBus requestEventBus) {
    try {/*  w w w .j ava 2s.  co  m*/
        httpRequestContext.getTimeRecorder().startWriteBody();

        ChannelFuture channelFuture = httpBody.writeContent(ctx);

        channelFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                    throws Exception {
                requestEventBus.triggerEvent(Event.TOUCH);
                requestEventBus.triggerEvent(Event.onWroteContentProgressed, progress, total);

            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                logger.trace("Wrote content operation completed, future: {}", future);

                if (future.isSuccess()) {
                    httpRequestContext.getTimeRecorder().completedWriteBody();
                    writeLastHttpContent(ctx, httpRequestContext, requestEventBus);
                    requestEventBus.triggerEvent(Event.TOUCH);

                } else {
                    logger.error("Failed to write http body, future: " + future);
                    requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
                }
            }
        });

    } catch (IOException e) {
        requestEventBus.triggerEvent(Event.ERROR, httpRequestContext,
                new IOException("Failed to write body to server", e));
    }

}

From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java

License:Apache License

private void writeLastHttpContent(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {
    ChannelFuture future = ctx.writeAndFlush(new DefaultLastHttpContent());
    future.addListener(new ChannelFutureListener() {
        @Override//from  ww w . j a  va 2  s .  c  o m
        public void operationComplete(ChannelFuture future) throws Exception {
            logger.trace("writeLastHttpContent operation completed, future: {}", future);

            if (future.isSuccess()) {
                requestEventBus.triggerEvent(Event.onWroteContentCompleted);
                requestEventBus.triggerEvent(Event.TOUCH);
                httpRequestContext.getTimeRecorder().completedWriteLastBody();

            } else {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }

        }
    });
}