Example usage for io.netty.channel ChannelFutureListener CLOSE

List of usage examples for io.netty.channel ChannelFutureListener CLOSE

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener CLOSE.

Prototype

ChannelFutureListener CLOSE

To view the source code for io.netty.channel ChannelFutureListener CLOSE.

Click Source Link

Document

A ChannelFutureListener that closes the Channel which is associated with the specified ChannelFuture .

Usage

From source file:netty.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest 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 a 2s . co m*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
        //            System.out.println( "sendHttpResponse = " + res);
    }

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

From source file:netty.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest req,
        final FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status() != HttpResponseStatus.OK) {
        final ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from w w  w. j  a va  2  s  . c  o m*/
        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.status() != HttpResponseStatus.OK) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:Netty4.book.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);/*from   w  ww . j ava 2s .  com*/
        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().get(HttpHeaderNames.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);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaderNames.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.writeAndFlush(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() {

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

        }

        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            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:netty4.protocol.http.HttpFileServerHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {

    System.out.println("channelRead thread: " + Thread.currentThread());
    TaskRunner.getInstance().submitTask(new Runnable() {
        @Override//from   www  .j av a2s  .c  o  m
        public void run() {
            try {
                if (!request.getDecoderResult().isSuccess()) {
                    sendError(ctx, BAD_REQUEST);
                    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;
                }
                RandomAccessFile randomAccessFile = null;
                try {
                    randomAccessFile = new RandomAccessFile(file, "r");// ??
                } catch (FileNotFoundException fnfe) {
                    sendError(ctx, NOT_FOUND);
                    return;
                }
                long fileLength;
                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);
                }
                System.out.println("TaskRunner thread: " + Thread.currentThread());
                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);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });
}

From source file:netty5.http.server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (HttpHeaderUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//w w  w .jav  a 2  s. co m
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:nettydb2webservice.NettyDB2WebServiceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    byte[] CONTENT = "".getBytes();
    if (msg instanceof HttpRequest) {
        KVPTable kvp = new KVPTable();
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*from w  w  w .j av a2s  .co m*/
        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        HttpMethod method = req.getMethod();
        if (req.getUri().equalsIgnoreCase("/api")) {
            CONTENT = kvp.toJSON().toJSONString().getBytes();
        }
        if (req.getUri().matches("/api/(.+)$")) {
            String[] parts = req.getUri().split("/");
            String key = parts[parts.length - 1];
            CONTENT = kvp.toJSON(key).toJSONString().getBytes();
        }
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "application/json");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:nettyHelloWorld.nettyServer.BidRequestHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

    System.out.println("foo" + msg);
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }//from   ww w.  ja  va  2 s .c  o m
        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }

    }

}

From source file:nettyhttpfileserverdemo.HttpFileServerHandler.java

@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);// w  w  w  . j  a  va  2 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;
    }

    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
    } //try-catch

    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 = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {

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

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.println("Transfer Complete");
        } //operationComplete()

    });

    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

}

From source file:nettyhttpfileserverdemo.HttpFileServerHandler.java

private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(
            "Failure: " + status.toString() + System.getProperty("line.separator"), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain;    charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:nettyhttpfileserverdemo.HttpFileServerHandler.java

private void sendListing(ChannelHandlerContext ctx, File dir) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
    StringBuilder buf = new StringBuilder();
    String dirPath = dir.getPath();

    buf.append("<!DOCTYPE html>").append(System.getProperty("line.separator"));
    buf.append("<html><head><title>");
    buf.append(dirPath);/*from   ww  w  . j a va  2 s  . c  o  m*/
    buf.append(" Directory: ");
    buf.append("</title></head><body>").append(System.getProperty("line.separator"));
    buf.append("<h3>");
    buf.append(dirPath).append(" Directory: ");
    buf.append("</h3>").append(System.getProperty("line.separator"));
    buf.append("<li>link:<a href=\"../\">..</a></li>").append(System.getProperty("line.separator"));
    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }

        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }

        buf.append("<li>link: <a href=\"");
        buf.append(name);
        buf.append("\">");
        buf.append(name);
        buf.append("</a></li>").append(System.getProperty("line.separator"));
    } //for        
    buf.append("</ul></body></html>").append(System.getProperty("line.separator"));

    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}