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:io.vertx.core.http.impl.FileStreamChannel.java

License:Open Source License

FileStreamChannel(Handler<AsyncResult<Long>> resultHandler, VertxHttp2Stream stream, long offset, long length) {
    super(null, Id.INSTANCE);

    pipeline().addLast(new ChannelInitializer<Channel>() {
        @Override/*  ww w . ja  v a 2s  .co m*/
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new ChunkedWriteHandler());
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof RandomAccessFile) {
                        ChannelFuture fut = ctx.writeAndFlush(new ChunkedFile((RandomAccessFile) evt, offset,
                                length, 8192 /* default chunk size */ ));
                        fut.addListener(f -> {
                            if (resultHandler != null) {
                                if (f.isSuccess()) {
                                    resultHandler.handle(Future.succeededFuture(bytesWritten));
                                } else {
                                    resultHandler.handle(Future.failedFuture(f.cause()));
                                }
                            }
                            fut.addListener(ChannelFutureListener.CLOSE);
                        });
                    }
                }
            });
        }
    });

    this.stream = stream;
}

From source file:io.vertx.core.http.impl.Http1xClientConnection.java

License:Open Source License

public void handleMessage(Object msg) {
    Throwable error = validateMessage(msg);
    if (error != null) {
        fail(error);//from   w  w  w .  j a v a  2  s  .c  o  m
    } else if (msg instanceof HttpObject) {
        HttpObject obj = (HttpObject) msg;
        handleHttpMessage(obj);
    } else if (msg instanceof WebSocketFrame) {
        WebSocketFrameInternal frame = decodeFrame((WebSocketFrame) msg);
        switch (frame.type()) {
        case BINARY:
        case CONTINUATION:
        case TEXT:
        case PONG:
            handleWsFrame(frame);
            break;
        case PING:
            // Echo back the content of the PING frame as PONG frame as specified in RFC 6455 Section 5.5.2
            chctx.writeAndFlush(new PongWebSocketFrame(frame.getBinaryData().copy()));
            break;
        case CLOSE:
            handleWsFrame(frame);
            if (!closeFrameSent) {
                // Echo back close frame and close the connection once it was written.
                // This is specified in the WebSockets RFC 6455 Section  5.4.1
                CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(frame.closeStatusCode(),
                        frame.closeReason());
                chctx.writeAndFlush(closeFrame).addListener(ChannelFutureListener.CLOSE);
                closeFrameSent = true;
            }
            break;
        default:
            throw new IllegalStateException("Invalid type: " + frame.type());
        }
    } else {
        throw new IllegalStateException("Invalid object " + msg);
    }
}

From source file:io.vertx.core.http.impl.Http1xServerConnection.java

License:Open Source License

private void handleOther(Object msg) {
    if (msg instanceof WebSocketFrame) {
        WebSocketFrameInternal frame = decodeFrame((WebSocketFrame) msg);
        switch (frame.type()) {
        case PING:
            // Echo back the content of the PING frame as PONG frame as specified in RFC 6455 Section 5.5.2
            chctx.writeAndFlush(new PongWebSocketFrame(frame.getBinaryData()));
            return;
        case CLOSE:
            if (!closeFrameSent) {
                // Echo back close frame and close the connection once it was written.
                // This is specified in the WebSockets RFC 6455 Section  5.4.1
                CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(frame.closeStatusCode(),
                        frame.closeReason());
                chctx.writeAndFlush(closeFrame).addListener(ChannelFutureListener.CLOSE);
                closeFrameSent = true;//w  ww  . ja  v a  2  s  .c  o  m
            }
            break;
        }
        if (ws != null) {
            ws.handleFrame(frame);
        }
    }

    if (msg instanceof PingWebSocketFrame) {
        PingWebSocketFrame frame = (PingWebSocketFrame) msg;
        // Echo back the content of the PING frame as PONG frame as specified in RFC 6455 Section 5.5.2
        frame.content().retain();
        chctx.writeAndFlush(new PongWebSocketFrame(frame.content()));
        return;
    } else if (msg instanceof CloseWebSocketFrame) {
        if (!closeFrameSent) {
            CloseWebSocketFrame frame = (CloseWebSocketFrame) msg;
            // Echo back close frame and close the connection once it was written.
            // This is specified in the WebSockets RFC 6455 Section  5.4.1
            CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(frame.statusCode(), frame.reasonText());
            chctx.writeAndFlush(closeFrame).addListener(ChannelFutureListener.CLOSE);
            closeFrameSent = true;
        }
    }

}

From source file:io.vertx.core.http.impl.Http1xServerConnection.java

License:Open Source License

@Override
public void close() {
    if (ws == null) {
        super.close();
    } else {/*  w w  w . ja v  a 2  s. co  m*/
        endReadAndFlush();
        chctx.writeAndFlush(new CloseWebSocketFrame(true, 0, 1000, null))
                .addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.vertx.core.http.impl.Http1xServerConnection.java

License:Open Source License

@Override
public void closeWithPayload(ByteBuf byteBuf) {
    if (ws == null) {
        super.close();
    } else {/*from  ww w.j  av  a  2s . c  o m*/
        endReadAndFlush();
        chctx.writeAndFlush(new CloseWebSocketFrame(true, 0, byteBuf)).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.vertx.test.core.EventLoopGroupTest.java

License:Open Source License

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {/*w  w w  . j  a  va 2 s.  c o  m*/
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channel(NioServerSocketChannel.class);
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(() -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    bs.bind("localhost", 1234).sync();
    vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
        assertTrue(ar.succeeded());
        NetSocket so = ar.result();
        so.write(Buffer.buffer("hello"));
    });
    await();
}

From source file:io.viewserver.network.netty.websocket.WebSocketServerHandler.java

License:Apache License

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

    ChannelFuture channelFuture = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.werval.server.netty.HttpRequestAggregator.java

License:Apache License

private void handleHttpContent(ChannelHandlerContext context, HttpContent chunk, List<Object> out)
        throws IOException {
    HttpRequest currentRequestHeader = aggregatedRequestHeader;
    assert currentRequestHeader != null;

    int readableBytes = chunk.content().readableBytes();
    if (maxContentLength != -1 && consumedContentlength + readableBytes > maxContentLength) {
        LOG.warn("Request Entity is too large, content length exceeded {} bytes.", maxContentLength);
        ByteBuf body = copiedBuffer("HTTP content length exceeded " + maxContentLength + " bytes.", US_ASCII);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE, body);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=" + US_ASCII.name().toLowerCase(US));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(CONNECTION, CLOSE);
        context.write(response).addListener(ChannelFutureListener.CLOSE); // HERE
        return;/*from w w  w. j a  v a2s. com*/
    }

    // Append chunk data to aggregated buffer or file
    if (chunk.content().isReadable()) {
        // Test disk threshold
        if (consumedContentlength + readableBytes > diskThreshold) {
            // Overflow to disk
            if (bodyFile == null) {
                // Start
                bodyFile = new File(diskOverflowDirectory, TEMP_FILE_ID_GEN.newIdentity());
                try (OutputStream bodyOutputStream = new FileOutputStream(bodyFile)) {
                    if (bodyBuf != null) {
                        bodyBuf.readBytes(bodyOutputStream, bodyBuf.readableBytes());
                        bodyBuf.release();
                        bodyBuf = null;
                    }
                    chunk.content().readBytes(bodyOutputStream, readableBytes);
                }
            } else {
                // Continue
                try (OutputStream bodyOutputStream = new FileOutputStream(bodyFile, true)) {
                    chunk.content().readBytes(bodyOutputStream, readableBytes);
                }
            }
        } else {
            // In-memory
            if (bodyBuf == null) {
                // Start
                bodyBuf = chunk.content().retain();
            } else {
                // Continue
                bodyBuf = wrappedBuffer(bodyBuf, chunk.content().retain());
            }
        }
        consumedContentlength += readableBytes;
    }

    // Last Chunk?
    final boolean last;
    if (!chunk.getDecoderResult().isSuccess()) {
        currentRequestHeader.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
        last = true;
    } else {
        last = chunk instanceof LastHttpContent;
    }

    if (last) {
        // Merge trailing headers
        if (chunk instanceof LastHttpContent) {
            currentRequestHeader.headers().add(((LastHttpContent) chunk).trailingHeaders());
        }

        // Set the 'Content-Length' header
        currentRequestHeader.headers().set(CONTENT_LENGTH, String.valueOf(consumedContentlength));

        // Create aggregated request
        FullHttpRequest fullRequest;
        ByteBuf content = null;
        if (bodyFile != null) {
            content = new FileByteBuff(bodyFile);
        } else if (bodyBuf != null) {
            content = bodyBuf.retain();
        }
        if (content != null) {
            fullRequest = new DefaultFullHttpRequest(currentRequestHeader.getProtocolVersion(),
                    currentRequestHeader.getMethod(), currentRequestHeader.getUri(), content);
        } else {
            fullRequest = new DefaultFullHttpRequest(currentRequestHeader.getProtocolVersion(),
                    currentRequestHeader.getMethod(), currentRequestHeader.getUri());
        }
        fullRequest.headers().set(currentRequestHeader.headers());

        // All done
        aggregatedRequestHeader = null;
        consumedContentlength = 0;

        // Fire aggregated request
        out.add(fullRequest);
    }
}

From source file:io.werval.server.netty.WervalHttpHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext nettyContext, Throwable cause) throws IOException {
    if (cause instanceof ReadTimeoutException) {
        LOG.trace("{} Read timeout, connection has been closed.", requestIdentity);
    } else if (cause instanceof WriteTimeoutException) {
        LOG.trace("{} Write timeout, connection has been closed.", requestIdentity);
    } else if (cause instanceof DevShellRebuildException) {
        byte[] htmlErrorPage = ((DevShellRebuildException) cause).htmlErrorPage().getBytes(UTF_8);
        DefaultFullHttpResponse nettyResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
        nettyResponse.headers().set(CONTENT_LENGTH, htmlErrorPage.length);
        ((ByteBufHolder) nettyResponse).content().writeBytes(htmlErrorPage);
        nettyContext.writeAndFlush(nettyResponse).addListeners(
                f -> app.events()//from   ww w  . j  av a  2  s .  co  m
                        .emit(new HttpEvent.ResponseSent(requestIdentity, Status.INTERNAL_SERVER_ERROR)),
                new HttpRequestCompleteChannelFutureListener(requestHeader), ChannelFutureListener.CLOSE);
    } else if (requestHeader != null) {
        // Write Outcome
        Outcome errorOutcome = app.handleError(requestHeader, cause);
        ChannelFuture writeFuture = writeOutcome(nettyContext, errorOutcome);
        // Listen to request completion
        writeFuture
                .addListeners(
                        f -> app.events()
                                .emit(new HttpEvent.ResponseSent(requestIdentity,
                                        errorOutcome.responseHeader().status())),
                        new HttpRequestCompleteChannelFutureListener(requestHeader));
    } else if (cause instanceof HttpRequestParsingException) {
        if (app.mode() == Mode.PROD) {
            LOG.trace("HTTP request parsing error, returning 400, was: {}", cause.getMessage(), cause);
        } else {
            LOG.warn("HTTP request parsing error, returning 400, was: {}", cause.getMessage(), cause);
        }
        DefaultFullHttpResponse nettyResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST);
        nettyResponse.headers().set(CONTENT_LENGTH, 0);
        nettyContext.writeAndFlush(nettyResponse).addListeners(
                f -> app.events().emit(new HttpEvent.ResponseSent(requestIdentity, Status.BAD_REQUEST)),
                new HttpRequestCompleteChannelFutureListener(requestHeader), ChannelFutureListener.CLOSE);
    } else {
        LOG.error(
                "HTTP Server encountered an unexpected error, please raise an issue with the complete stacktrace",
                cause);
        nettyContext.close();
    }
}

From source file:io.werval.server.netty.WervalHttpHandler.java

License:Apache License

private ChannelFuture writeOutcome(ChannelHandlerContext nettyContext, Outcome outcome) {
    // == Build the Netty Response
    ResponseHeader responseHeader = outcome.responseHeader();

    // Netty Version & Status
    HttpVersion responseVersion = HttpVersion.valueOf(responseHeader.version().toString());
    HttpResponseStatus responseStatus = HttpResponseStatus.valueOf(responseHeader.status().code());

    // Netty Headers & Body output
    final HttpResponse nettyResponse;
    final ChannelFuture writeFuture;
    if (outcome instanceof ChunkedInputOutcome) {
        ChunkedInputOutcome chunkedOutcome = (ChunkedInputOutcome) outcome;
        nettyResponse = new DefaultHttpResponse(responseVersion, responseStatus);
        // Headers
        applyResponseHeader(responseHeader, nettyResponse);
        nettyResponse.headers().set(TRANSFER_ENCODING, CHUNKED);
        nettyResponse.headers().set(TRAILER, X_WERVAL_CONTENT_LENGTH);
        // Body/*  w  w w  .ja v a2  s .c o m*/
        nettyContext.write(nettyResponse);
        writeFuture = nettyContext.writeAndFlush(new HttpChunkedBodyEncoder(
                new ChunkedStream(chunkedOutcome.inputStream(), chunkedOutcome.chunkSize())));
    } else if (outcome instanceof InputStreamOutcome) {
        InputStreamOutcome streamOutcome = (InputStreamOutcome) outcome;
        nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus);
        // Headers
        applyResponseHeader(responseHeader, nettyResponse);
        nettyResponse.headers().set(CONTENT_LENGTH, streamOutcome.contentLength());
        // Body
        try (InputStream bodyInputStream = streamOutcome.bodyInputStream()) {
            ((ByteBufHolder) nettyResponse).content().writeBytes(bodyInputStream,
                    new BigDecimal(streamOutcome.contentLength()).intValueExact());
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
        writeFuture = nettyContext.writeAndFlush(nettyResponse);
    } else if (outcome instanceof SimpleOutcome) {
        SimpleOutcome simpleOutcome = (SimpleOutcome) outcome;
        byte[] body = simpleOutcome.body().asBytes();
        nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus);
        // Headers
        applyResponseHeader(responseHeader, nettyResponse);
        nettyResponse.headers().set(CONTENT_LENGTH, body.length);
        // Body
        ((ByteBufHolder) nettyResponse).content().writeBytes(body);
        writeFuture = nettyContext.writeAndFlush(nettyResponse);
    } else {
        LOG.warn("{} Unhandled Outcome type '{}', no response body.", requestIdentity, outcome.getClass());
        nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus);
        applyResponseHeader(responseHeader, nettyResponse);
        writeFuture = nettyContext.writeAndFlush(nettyResponse);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("{} Sent a HttpResponse:\n{}", requestIdentity, nettyResponse.toString());
    }

    // Close the connection as soon as the response is sent if not keep alive
    if (!outcome.responseHeader().isKeepAlive() || nettyContext.executor().isShuttingDown()) {
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    // Done!
    return writeFuture;
}