Search in sources :

Example 1 with Http2HeadersFrame

use of io.netty.handler.codec.http2.Http2HeadersFrame in project netty by netty.

the class Http2MultiplexCodecTest method outboundStreamShouldWriteResetFrameOnClose_headersSent.

@Test
public void outboundStreamShouldWriteResetFrameOnClose_headersSent() {
    childChannelInitializer.handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
            ctx.fireChannelActive();
        }
    };
    Http2StreamChannelBootstrap b = new Http2StreamChannelBootstrap();
    b.parentChannel(parentChannel).handler(childChannelInitializer);
    Channel childChannel = b.connect().channel();
    assertTrue(childChannel.isActive());
    Http2HeadersFrame headersFrame = parentChannel.readOutbound();
    assertNotNull(headersFrame);
    assertFalse(Http2CodecUtil.isStreamIdValid(headersFrame.streamId()));
    parentChannel.pipeline().fireUserEventTriggered(new Http2StreamActiveEvent(2, headersFrame));
    childChannel.close();
    parentChannel.runPendingTasks();
    Http2ResetFrame reset = parentChannel.readOutbound();
    assertEquals(2, reset.streamId());
    assertEquals(Http2Error.CANCEL.code(), reset.errorCode());
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 2 with Http2HeadersFrame

use of io.netty.handler.codec.http2.Http2HeadersFrame in project netty by netty.

the class Http2FrameCodecTest method streamErrorShouldNotFireExceptionForOutbound.

@Test
public void streamErrorShouldNotFireExceptionForOutbound() throws Exception {
    frameInboundWriter.writeInboundHeaders(3, request, 31, false);
    Http2Stream stream = frameCodec.connection().stream(3);
    assertNotNull(stream);
    StreamException streamEx = new StreamException(3, Http2Error.INTERNAL_ERROR, "foo");
    frameCodec.onError(frameCodec.ctx, true, streamEx);
    Http2FrameStreamEvent event = inboundHandler.readInboundMessageOrUserEvent();
    assertEquals(Http2FrameStreamEvent.Type.State, event.type());
    assertEquals(State.OPEN, event.stream().state());
    Http2HeadersFrame headersFrame = inboundHandler.readInboundMessageOrUserEvent();
    assertNotNull(headersFrame);
    // No exception expected
    inboundHandler.checkException();
    assertNull(inboundHandler.readInboundMessageOrUserEvent());
}
Also used : StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException) Test(org.junit.jupiter.api.Test)

Example 3 with Http2HeadersFrame

use of io.netty.handler.codec.http2.Http2HeadersFrame in project netty by netty.

the class Http2MultiplexTest method channelReadShouldRespectAutoReadAndNotProduceNPE.

@Test
public void channelReadShouldRespectAutoReadAndNotProduceNPE() throws Exception {
    LastInboundHandler inboundHandler = new LastInboundHandler();
    Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);
    assertTrue(childChannel.config().isAutoRead());
    Http2HeadersFrame headersFrame = inboundHandler.readInbound();
    assertNotNull(headersFrame);
    childChannel.config().setAutoRead(false);
    childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

        private int count;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ctx.fireChannelRead(msg);
            // Close channel after 2 reads so there is still something in the inboundBuffer when the close happens.
            if (++count == 2) {
                ctx.close();
            }
        }
    });
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("hello world"), 0, false);
    Http2DataFrame dataFrame0 = inboundHandler.readInbound();
    assertNotNull(dataFrame0);
    release(dataFrame0);
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("foo"), 0, false);
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("bar"), 0, false);
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("bar"), 0, false);
    assertNull(inboundHandler.readInbound());
    childChannel.config().setAutoRead(true);
    verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 3);
    inboundHandler.checkException();
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 4 with Http2HeadersFrame

use of io.netty.handler.codec.http2.Http2HeadersFrame in project netty by netty.

the class Http2StaticFileServerHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof Http2HeadersFrame) {
        Http2HeadersFrame headersFrame = (Http2HeadersFrame) msg;
        this.stream = headersFrame.stream();
        if (!GET.toString().equals(headersFrame.headers().method().toString())) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }
        final String uri = headersFrame.headers().path().toString();
        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
        CharSequence ifModifiedSince = headersFrame.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE);
        if (ifModifiedSince != null && !ifModifiedSince.toString().isEmpty()) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
            Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince.toString());
            // 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();
        Http2Headers headers = new DefaultHttp2Headers();
        headers.status("200");
        headers.setLong(HttpHeaderNames.CONTENT_LENGTH, fileLength);
        setContentTypeHeader(headers, file);
        setDateAndCacheHeaders(headers, file);
        // Write the initial line and the header.
        ctx.writeAndFlush(new DefaultHttp2HeadersFrame(headers).stream(stream));
        // Write the content.
        ChannelFuture sendFileFuture;
        sendFileFuture = ctx.writeAndFlush(new Http2DataChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192), stream), ctx.newProgressivePromise());
        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.");
            }
        });
    } else {
        // Unsupported message type
        System.out.println("Unsupported message type: " + msg);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) ChunkedFile(io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) ChannelProgressiveFuture(io.netty.channel.ChannelProgressiveFuture) Date(java.util.Date) DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) RandomAccessFile(java.io.RandomAccessFile) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2DataChunkedInput(io.netty.handler.codec.http2.Http2DataChunkedInput) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) RandomAccessFile(java.io.RandomAccessFile) ChunkedFile(io.netty.handler.stream.ChunkedFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) ChannelProgressiveFutureListener(io.netty.channel.ChannelProgressiveFutureListener)

Example 5 with Http2HeadersFrame

use of io.netty.handler.codec.http2.Http2HeadersFrame in project netty by netty.

the class Http2StaticFileServerHandler method sendError.

private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    Http2Headers headers = new DefaultHttp2Headers();
    headers.status(status.toString());
    headers.add(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers);
    headersFrame.stream(stream);
    Http2DataFrame dataFrame = new DefaultHttp2DataFrame(Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8), true);
    dataFrame.stream(stream);
    ctx.write(headersFrame);
    ctx.writeAndFlush(dataFrame);
}
Also used : DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) Http2DataFrame(io.netty.handler.codec.http2.Http2DataFrame) DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) Http2HeadersFrame(io.netty.handler.codec.http2.Http2HeadersFrame) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers)

Aggregations

StreamException (io.netty.handler.codec.http2.Http2Exception.StreamException)6 Http2HeadersFrame (io.netty.handler.codec.http2.Http2HeadersFrame)6 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)3 DefaultHttp2Headers (io.netty.handler.codec.http2.DefaultHttp2Headers)3 DefaultHttp2HeadersFrame (io.netty.handler.codec.http2.DefaultHttp2HeadersFrame)3 Http2DataFrame (io.netty.handler.codec.http2.Http2DataFrame)3 Test (org.junit.jupiter.api.Test)3 Channel (io.netty.channel.Channel)2 Http2Headers (io.netty.handler.codec.http2.Http2Headers)2 ClosedChannelException (java.nio.channels.ClosedChannelException)2 Test (org.junit.Test)2 RequestInfo (com.github.ambry.network.RequestInfo)1 Bootstrap (io.netty.bootstrap.Bootstrap)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelProgressiveFuture (io.netty.channel.ChannelProgressiveFuture)1 ChannelProgressiveFutureListener (io.netty.channel.ChannelProgressiveFutureListener)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1