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:com.barchart.http.server.PooledServerResponse.java

License:BSD License

@Override
public ChannelFuture finish() throws IOException {

    checkFinished();/*  w w w  .j  a va  2s .  com*/

    ChannelFuture writeFuture = null;

    // Handlers might call finish() on a cancelled/closed
    // channel, don't cause unnecessary pipeline exceptions
    if (context.channel().isOpen()) {

        if (isChunkedEncoding()) {

            if (!started) {
                log.debug("Warning, empty response");
                startResponse();
            }

            writeFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

            // MJS: TBD close the channel here
            // context.channel().close();

        } else {

            writeFuture = startResponse();

        }

    }

    close();

    if (writeFuture != null && !HttpHeaders.isKeepAlive(request)) {
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    // Record to access log
    logger.access(request, this, System.currentTimeMillis() - requestTime);

    // Keep alive, need to tell channel handler it can return us to the pool
    if (HttpHeaders.isKeepAlive(request)) {
        channelHandler.freeHandlers(context);
    }

    return writeFuture;

}

From source file:com.barchart.netty.server.http.pipeline.PooledHttpServerResponse.java

License:BSD License

@Override
public ChannelFuture finish() throws IOException {

    checkFinished();//from  w w w. ja v a 2 s.c o m

    ChannelFuture writeFuture = null;

    // Handlers might call finish() on a cancelled/closed
    // channel, don't cause unnecessary pipeline exceptions
    if (context.channel().isOpen()) {

        if (chunkSize > 0) {

            if (!started) {
                log.debug("Warning, empty response");
                startResponse();
            }

            out.flush();

            writeFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

        } else {

            writeFuture = startResponse();

        }

    }

    close();

    if (writeFuture != null && !HttpHeaders.isKeepAlive(request)) {
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    // Keep alive, need to tell channel handler it can return us to the pool
    if (HttpHeaders.isKeepAlive(request)) {
        keepaliveHelper.requestComplete(context);
    }

    return writeFuture;

}

From source file:com.bloom.zerofs.rest.HealthCheckHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    boolean forwardObj = false;
    if (obj instanceof HttpRequest) {
        if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) {
            nettyMetrics.healthCheckRequestRate.mark();
            startTimeInMs = System.currentTimeMillis();
            logger.trace("Handling health check request while in state " + restServerState.isServiceUp());
            request = (HttpRequest) obj;
            if (restServerState.isServiceUp()) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                        Unpooled.wrappedBuffer(GOOD));
                HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
                HttpHeaders.setContentLength(response, GOOD.length);
            } else {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD));
                HttpHeaders.setKeepAlive(response, false);
                HttpHeaders.setContentLength(response, BAD.length);
            }//from  www  .  j a  va2  s .c  om
            nettyMetrics.healthCheckRequestProcessingTimeInMs
                    .update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // Rest server could be down even if not for health check request. We intentionally don't take any action in this
            // handler for such cases and leave it to the downstream handlers to handle it
            forwardObj = true;
        }
    }
    if (obj instanceof LastHttpContent) {
        if (response != null) {
            // response was created when we received the request with health check uri
            ChannelFuture future = ctx.writeAndFlush(response);
            if (!HttpHeaders.isKeepAlive(response)) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
            request = null;
            response = null;
            nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // request was not for health check uri
            forwardObj = true;
        }
    } else if (request == null) {
        // http Content which is not LastHttpContent is not intended for this handler
        forwardObj = true;
    }
    if (forwardObj) {
        super.channelRead(ctx, obj);
    } else {
        ReferenceCountUtil.release(obj);
    }
}

From source file:com.bloom.zerofs.rest.HealthCheckHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!restServerState.isServiceUp()) {
        if (msg instanceof LastHttpContent) {
            // Start closing client channels after we've completed writing to them (even if they are keep-alive)
            logger.info("Health check request handler closing connection " + ctx.channel()
                    + " since in shutdown mode.");
            promise.addListener(ChannelFutureListener.CLOSE);
            nettyMetrics.healthCheckHandlerChannelCloseOnWriteCount.inc();
        }/*from www  .j  ava 2 s  .c o  m*/
    }
    super.write(ctx, msg, promise);
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Completes the request by closing the request and network channel (if {@code closeNetworkChannel} is {@code true}).
 * </p>//from  w ww  . ja v a2s. co  m
 * May also close the channel if the class internally is forcing a close (i.e. if {@link #close()} is called.
 * @param closeNetworkChannel network channel is closed if {@code true}.
 */
private void completeRequest(boolean closeNetworkChannel) {
    if ((closeNetworkChannel || forceClose) && ctx.channel().isOpen()) {
        writeFuture.addListener(ChannelFutureListener.CLOSE);
        logger.trace("Requested closing of channel {}", ctx.channel());
    }
    closeRequest();
}

From source file:com.bt.netty.TelnetServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    // Generate and write a response.
    String response;//from www . ja v  a 2  s.c  o m
    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.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) {
    HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status()));

    httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType());

    // Disable cache by default
    httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0");
    httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
    httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0");

    response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue()));

    httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion);

    // Set cookies
    httpresponse.headers().set(HttpHeaderNames.SET_COOKIE,
            ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies())));

    if (response.length() >= 0) {
        httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length());
    }/*from  w  w w  .j a  va  2s .co m*/

    if (HttpUtil.isKeepAlive(httprequest)) {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    ctx.write(httpresponse);

    if (response.stream() != null) {
        ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream())));
    }

    LastHttpContent fs = new DefaultLastHttpContent();
    ChannelFuture sendContentFuture = ctx.writeAndFlush(fs);
    if (!HttpUtil.isKeepAlive(httprequest)) {
        sendContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.caricah.iotracah.server.httpserver.netty.HttpServerHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    try {/*from   w ww. j av  a 2 s  .co m*/
        log.info(" exceptionCaught : Unhandled exception: ", cause);

        JSONObject error = new JSONObject();
        error.put("message", cause.getMessage());
        error.put("status", "failure");

        ByteBuf buffer = Unpooled.copiedBuffer(error.toString(), CharsetUtil.UTF_8);

        // Build the response object.
        FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.INTERNAL_SERVER_ERROR, buffer);

        ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
    } catch (Exception ex) {
        log.debug(" exceptionCaught : trying to close socket because we got an unhandled exception", ex);
    }

}

From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from   ww w .ja  va 2  s.  com*/
        return;
    }

    if (request.method() == POST) {
        new VersionProtocolMessageHandler().handleMessage(ctx, request);
        return;
    }

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

    final String uri = request.uri();
    final String path = sanitizeUri(uri);

    if (new URLServiceFilter(uri, ctx, request).doFilte()) {
        return;
    }

    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

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

    if (file.isDirectory()) {
        if (!HttpStaticVersionMonitorFileServer.OPEN_ACCESS) {
            sendWarningInfo(ctx);
            return;
        }

        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);
    response.headers().set("file_flag", "yes");
    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.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() {
        @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.cats.version.httpserver.HttpStaticFileServerHandler.java

License:Apache License

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

    String dirPath = dir.getPath();
    StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n").append("<html><head><title>")
            .append("Listing of: ").append(dirPath).append("</title></head><body>\r\n")

            .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n")

            .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n");

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }//w ww  .  j a v  a2  s.c om

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

        buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n");
    }

    buf.append("</ul></body></html>\r\n");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}