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:de.jackwhite20.comix.handler.UpstreamHandler.java

License:Open Source License

@Override
public void channelInactive(ChannelHandlerContext ctx) {
    if (downstreamChannel != null) {
        if (downstreamChannel.isActive()) {
            downstreamChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }/*from  w  w  w . jav a2s .  c  o  m*/

        if (client != null)
            Comix.getInstance().removeClient(client);

        upstreamBytesIn = 0;
        downstreamBytesOut = 0;

        Comix.getLogger()
                .info("["
                        + ((client != null) ? client.getName()
                                : Util.formatSocketAddress(upstreamChannel.remoteAddress()))
                        + "] -> UpstreamHandler has disconnected");
    }
}

From source file:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void sendHttpResponse(ChannelHandlerContext context, FullHttpRequest request,
        FullHttpResponse response) {/*from   w  w w .j a  v a  2s .com*/
    if (response.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8);
        response.content().writeBytes(buf);
        buf.release();
    }
    setContentLength(response, response.content().readableBytes());

    ChannelFuture future = context.channel().writeAndFlush(response);
    if (!isKeepAlive(request) || response.getStatus().code() != 200) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:divconq.bus.net.ServerHandler.java

License:Open Source License

public 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);/*from   www . j  a  v  a  2  s .com*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);

    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200)
        f.addListener(ChannelFutureListener.CLOSE);
}

From source file:divconq.web.Response.java

License:Open Source License

public void write(Channel ch) {
    if ((this.status != HttpResponseStatus.OK) && (this.body.getLength() == 0))
        this.body.write(this.status.toString());

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, this.status);

    int clen = 0;
    this.body.setPosition(0);

    try {//from   ww  w . j  a v a  2 s  .c o  m
        clen = response.content().writeBytes(new InputWrapper(this.body), this.body.getLength());
    } catch (IOException e) {
    }

    response.headers().set(Names.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (this.keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(Names.CONTENT_LENGTH, clen);

        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Encode the cookies
    for (Cookie c : this.cookies.values())
        response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(c));

    for (Entry<CharSequence, String> h : this.headers.entrySet())
        response.headers().set(h.getKey(), h.getValue());

    Hub.instance.getSecurityPolicy().hardenHttpResponse(response);

    // Write the response.
    ChannelFuture future = ch.writeAndFlush(response);

    // Close the non-keep-alive connection after the write operation is done.
    if (!this.keepAlive)
        future.addListener(ChannelFutureListener.CLOSE);

    /*  we do not need to sync - HTTP is one request, one response.  we would not pile messages on this channel
     * 
     *  furthermore, when doing an upload stream we can actually get locked up here because the "write" from our stream
     *  is locked on the write process of the data bus and the response to the session is locked on the write of the response
     *  here - but all the HTTP threads are busy with their respective uploads.  If they all use the same data bus session 
     *  then all HTTP threads can get blocked trying to stream upload if even one of those has called an "OK" to upload and
     *  is stuck here.  so be sure not to use sync with HTTP responses.  this won't be a problem under normal use.
     *   
    try {
     future.sync();
    } 
    catch (InterruptedException x) {
     // TODO should we close channel?
    }
    */
}

From source file:divconq.web.Response.java

License:Open Source License

public void writeEnd(Channel ch) {
    // Write the response.
    ChannelFuture future = ch.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Close the non-keep-alive connection after the write operation is done.
    if (!this.keepAlive)
        future.addListener(ChannelFutureListener.CLOSE);

    /*  we do not need to sync - HTTP is one request, one response.  we would not pile messages on this channel
     * //from   ww  w.  ja  v a  2  s .  co  m
     *  furthermore, when doing an upload stream we can actually get locked up here because the "write" from our stream
     *  is locked on the write process of the data bus and the response to the session is locked on the write of the response
     *  here - but all the HTTP threads are busy with their respective uploads.  If they all use the same data bus session 
     *  then all HTTP threads can get blocked trying to stream upload if even one of those has called an "OK" to upload and
     *  is stuck here.  so be sure not to use sync with HTTP responses.  this won't be a problem under normal use.
     *   
    try {
     future.sync();
    } 
    catch (InterruptedException x) {
     // TODO should we close channel?
    }
    */
}

From source file:divconq.web.Response.java

License:Open Source License

public void writeChunked(Channel ch) {
    // Build the response object.
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.status);

    response.headers().set(Names.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (this.keepAlive) {
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }//  w ww  .  j a v a 2 s .c  om

    // TODO add a customer header telling how many messages are in the session adaptor's queue - if > 0

    // Encode the cookies
    for (Cookie c : this.cookies.values())
        response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(c));

    for (Entry<CharSequence, String> h : this.headers.entrySet())
        response.headers().set(h.getKey(), h.getValue());

    response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED);

    // Write the response.
    ChannelFuture future = ch.writeAndFlush(response);

    // Close the non-keep-alive connection after the write operation is done.
    if (!this.keepAlive)
        future.addListener(ChannelFutureListener.CLOSE);

    /*  we do not need to sync - HTTP is one request, one response.  we would not pile messages on this channel
    try {
     future.sync();
    } 
    catch (InterruptedException x) {
     // TODO should we close channel?
    }
    */
}

From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java

License:Open Source License

/**
 * Main functions/*w w w.  j av  a 2  s .co  m*/
 */

private void tractReadGet(ChannelHandlerContext ctx, String zipPath) {
    // Parse params
    String path = DPFManagerProperties.getReportsDir() + zipPath;
    if (!zipPath.endsWith(".zip")) {
        String hash = zipPath.substring(1, zipPath.length());
        StatusMessage sm = (StatusMessage) context.sendAndWaitResponse(BasicConfig.MODULE_DATABASE,
                new PostMessage(PostMessage.Type.ASK, hash));
        path = sm.getFolder().substring(0, sm.getFolder().length() - 1) + ".zip";
    }

    // Send the zip report
    File file = new File(path);
    if (file.exists()) {
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "r");

            long fileLength = raf.length();

            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            HttpUtil.setContentLength(response, fileLength);
            setContentTypeHeader(response, file);
            setDateAndCacheHeaders(response, file);
            response.headers().remove(HttpHeaderNames.CONNECTION);

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

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

            // Delete the zip after download?
            lastContentFuture.addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    //            file.delete();
                }
            });
            // Decide whether to close the connection or not.
            if (!HttpUtil.isKeepAlive(request)) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        } catch (Exception ignore) {
            sendError(ctx, NOT_FOUND);
        }
    } else {
        // No exists
        sendError(ctx, NOT_FOUND);
    }
}

From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java

License:Open Source License

private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:dpfmanager.shell.modules.server.post.HttpPostHandler.java

License:Open Source License

/**
 * Util functions/*  ww w . ja v a 2  s. c  om*/
 */

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

    // 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) {
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    }

    // Extra headers
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

    // 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:eastwind.webpush.WebPushHandler.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.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from   w  ww  . j  a  va2 s  .com*/
        buf.release();
    }

    // Send the response and close the connection if necessary.
    res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/json; charset=UTF-8");
    res.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    HttpUtil.setContentLength(res, res.content().readableBytes());
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}