Search in sources :

Example 71 with HeadersFrame

use of org.eclipse.jetty.http2.frames.HeadersFrame in project jetty.project by eclipse.

the class HttpClientTransportOverHTTP2Test method testLastStreamId.

@Test
public void testLastStreamId() throws Exception {
    prepareServer(new RawHTTP2ServerConnectionFactory(new HttpConfiguration(), new ServerSessionListener.Adapter() {

        @Override
        public Map<Integer, Integer> onPreface(Session session) {
            Map<Integer, Integer> settings = new HashMap<>();
            settings.put(SettingsFrame.MAX_CONCURRENT_STREAMS, 1);
            return settings;
        }

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            MetaData.Request request = (MetaData.Request) frame.getMetaData();
            if (HttpMethod.HEAD.is(request.getMethod())) {
                stream.getSession().close(ErrorCode.REFUSED_STREAM_ERROR.code, null, Callback.NOOP);
            } else {
                MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
            }
            return null;
        }
    }));
    server.start();
    CountDownLatch latch = new CountDownLatch(2);
    AtomicInteger lastStream = new AtomicInteger();
    AtomicReference<Stream> streamRef = new AtomicReference<>();
    CountDownLatch streamLatch = new CountDownLatch(1);
    client = new HttpClient(new HttpClientTransportOverHTTP2(new HTTP2Client()) {

        @Override
        protected HttpConnectionOverHTTP2 newHttpConnection(HttpDestination destination, Session session) {
            return new HttpConnectionOverHTTP2(destination, session) {

                @Override
                protected HttpChannelOverHTTP2 newHttpChannel(boolean push) {
                    return new HttpChannelOverHTTP2(getHttpDestination(), this, getSession(), push) {

                        @Override
                        public void setStream(Stream stream) {
                            super.setStream(stream);
                            streamRef.set(stream);
                            streamLatch.countDown();
                        }
                    };
                }
            };
        }

        @Override
        protected void onClose(HttpConnectionOverHTTP2 connection, GoAwayFrame frame) {
            super.onClose(connection, frame);
            lastStream.set(frame.getLastStreamId());
            latch.countDown();
        }
    }, null);
    QueuedThreadPool clientExecutor = new QueuedThreadPool();
    clientExecutor.setName("client");
    client.setExecutor(clientExecutor);
    client.start();
    // Prime the connection to allow client and server prefaces to be exchanged.
    ContentResponse response = client.newRequest("localhost", connector.getLocalPort()).path("/zero").timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    org.eclipse.jetty.client.api.Request request = client.newRequest("localhost", connector.getLocalPort()).method(HttpMethod.HEAD).path("/one");
    request.send(result -> {
        if (result.isFailed())
            latch.countDown();
    });
    Assert.assertTrue(streamLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Stream stream = streamRef.get();
    Assert.assertNotNull(stream);
    Assert.assertEquals(lastStream.get(), stream.getId());
}
Also used : HashMap(java.util.HashMap) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) OutputStream(java.io.OutputStream) InputStream(java.io.InputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) GoAwayFrame(org.eclipse.jetty.http2.frames.GoAwayFrame) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) RawHTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpClient(org.eclipse.jetty.client.HttpClient) HTTP2Client(org.eclipse.jetty.http2.client.HTTP2Client) HttpDestination(org.eclipse.jetty.client.HttpDestination) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 72 with HeadersFrame

use of org.eclipse.jetty.http2.frames.HeadersFrame in project jetty.project by eclipse.

the class HTTP2ServerConnection method upgrade.

public boolean upgrade(Request request) {
    if (HttpMethod.PRI.is(request.getMethod())) {
        getParser().directUpgrade();
    } else {
        HttpField settingsField = request.getFields().getField(HttpHeader.HTTP2_SETTINGS);
        if (settingsField == null)
            throw new BadMessageException("Missing " + HttpHeader.HTTP2_SETTINGS + " header");
        String value = settingsField.getValue();
        final byte[] settings = B64Code.decodeRFC4648URL(value == null ? "" : value);
        if (LOG.isDebugEnabled())
            LOG.debug("{} settings {}", this, TypeUtil.toHexString(settings));
        SettingsFrame settingsFrame = SettingsBodyParser.parseBody(BufferUtil.toBuffer(settings));
        if (settingsFrame == null) {
            LOG.warn("Invalid {} header value: {}", HttpHeader.HTTP2_SETTINGS, value);
            throw new BadMessageException();
        }
        getParser().standardUpgrade();
        upgradeFrames.add(new PrefaceFrame());
        upgradeFrames.add(settingsFrame);
        // Remember the request to send a response from onOpen().
        upgradeFrames.add(new HeadersFrame(1, new Request(request), null, true));
    }
    return true;
}
Also used : PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) HttpField(org.eclipse.jetty.http.HttpField) BadMessageException(org.eclipse.jetty.http.BadMessageException) Request(org.eclipse.jetty.http.MetaData.Request) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame)

Example 73 with HeadersFrame

use of org.eclipse.jetty.http2.frames.HeadersFrame in project jetty.project by eclipse.

the class HTTP2CServerTest method testHTTP_2_0_Direct.

@Test
public void testHTTP_2_0_Direct() throws Exception {
    final CountDownLatch latch = new CountDownLatch(3);
    byteBufferPool = new MappedByteBufferPool();
    generator = new Generator(byteBufferPool);
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:" + connector.getLocalPort()), "/test", HttpVersion.HTTP_2, new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            output.write(BufferUtil.toArray(buffer));
        }
        final AtomicReference<HeadersFrame> headersRef = new AtomicReference<>();
        final AtomicReference<DataFrame> dataRef = new AtomicReference<>();
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onSettings(SettingsFrame frame) {
                latch.countDown();
            }

            @Override
            public void onHeaders(HeadersFrame frame) {
                headersRef.set(frame);
                latch.countDown();
            }

            @Override
            public void onData(DataFrame frame) {
                dataRef.set(frame);
                latch.countDown();
            }
        }, 4096, 8192);
        parseResponse(client, parser);
        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
        HeadersFrame response = headersRef.get();
        Assert.assertNotNull(response);
        MetaData.Response responseMetaData = (MetaData.Response) response.getMetaData();
        Assert.assertEquals(200, responseMetaData.getStatus());
        DataFrame responseData = dataRef.get();
        Assert.assertNotNull(responseData);
        String s = BufferUtil.toString(responseData.getData());
        assertThat(s, containsString("Hello from Jetty using HTTP/2.0"));
        assertThat(s, containsString("uri=/test"));
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) AtomicReference(java.util.concurrent.atomic.AtomicReference) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) Socket(java.net.Socket) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 74 with HeadersFrame

use of org.eclipse.jetty.http2.frames.HeadersFrame in project jetty.project by eclipse.

the class HTTP2CServerTest method testHTTP_1_1_Upgrade.

@Test
public void testHTTP_1_1_Upgrade() throws Exception {
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        output.write(("" + "GET /one HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: something, else, upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: \r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
        output.flush();
        InputStream input = client.getInputStream();
        Utf8StringBuilder upgrade = new Utf8StringBuilder();
        int crlfs = 0;
        while (true) {
            int read = input.read();
            if (read == '\r' || read == '\n')
                ++crlfs;
            else
                crlfs = 0;
            upgrade.append((byte) read);
            if (crlfs == 4)
                break;
        }
        assertTrue(upgrade.toString().startsWith("HTTP/1.1 101 "));
        byteBufferPool = new MappedByteBufferPool();
        generator = new Generator(byteBufferPool);
        final AtomicReference<HeadersFrame> headersRef = new AtomicReference<>();
        final AtomicReference<DataFrame> dataRef = new AtomicReference<>();
        final AtomicReference<CountDownLatch> latchRef = new AtomicReference<>(new CountDownLatch(2));
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onHeaders(HeadersFrame frame) {
                headersRef.set(frame);
                latchRef.get().countDown();
            }

            @Override
            public void onData(DataFrame frame) {
                dataRef.set(frame);
                latchRef.get().countDown();
            }
        }, 4096, 8192);
        parseResponse(client, parser);
        Assert.assertTrue(latchRef.get().await(5, TimeUnit.SECONDS));
        HeadersFrame response = headersRef.get();
        Assert.assertNotNull(response);
        MetaData.Response responseMetaData = (MetaData.Response) response.getMetaData();
        Assert.assertEquals(200, responseMetaData.getStatus());
        DataFrame responseData = dataRef.get();
        Assert.assertNotNull(responseData);
        String content = BufferUtil.toString(responseData.getData());
        // The upgrade request is seen as HTTP/1.1.
        assertThat(content, containsString("Hello from Jetty using HTTP/1.1"));
        assertThat(content, containsString("uri=/one"));
        // Send a HTTP/2 request.
        headersRef.set(null);
        dataRef.set(null);
        latchRef.set(new CountDownLatch(2));
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        generator.control(lease, new PrefaceFrame());
        generator.control(lease, new SettingsFrame(new HashMap<>(), false));
        MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:" + connector.getLocalPort()), "/two", HttpVersion.HTTP_2, new HttpFields());
        generator.control(lease, new HeadersFrame(3, metaData, null, true));
        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
        output.flush();
        parseResponse(client, parser);
        Assert.assertTrue(latchRef.get().await(5, TimeUnit.SECONDS));
        response = headersRef.get();
        Assert.assertNotNull(response);
        responseMetaData = (MetaData.Response) response.getMetaData();
        Assert.assertEquals(200, responseMetaData.getStatus());
        responseData = dataRef.get();
        Assert.assertNotNull(responseData);
        content = BufferUtil.toString(responseData.getData());
        assertThat(content, containsString("Hello from Jetty using HTTP/2.0"));
        assertThat(content, containsString("uri=/two"));
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) InputStream(java.io.InputStream) Utf8StringBuilder(org.eclipse.jetty.util.Utf8StringBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) Parser(org.eclipse.jetty.http2.parser.Parser) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) Socket(java.net.Socket) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 75 with HeadersFrame

use of org.eclipse.jetty.http2.frames.HeadersFrame in project jetty.project by eclipse.

the class HTTP2ServerTest method testRequestWithPriorityWithContinuationFramesWithEmptyHeadersFrame.

@Test
public void testRequestWithPriorityWithContinuationFramesWithEmptyHeadersFrame() throws Exception {
    PriorityFrame priority = new PriorityFrame(1, 13, 200, true);
    testRequestWithContinuationFrames(null, () -> {
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        generator.control(lease, new PrefaceFrame());
        generator.control(lease, new SettingsFrame(new HashMap<>(), false));
        MetaData.Request metaData = newRequest("GET", new HttpFields());
        generator.control(lease, new HeadersFrame(1, metaData, priority, true));
        // Take the HeadersFrame header and set the length to just the priority frame.
        List<ByteBuffer> buffers = lease.getByteBuffers();
        ByteBuffer headersFrameHeader = buffers.get(2);
        headersFrameHeader.put(0, (byte) 0);
        headersFrameHeader.putShort(1, (short) PriorityFrame.PRIORITY_LENGTH);
        // Insert a CONTINUATION frame header for the body of the HEADERS frame.
        lease.insert(3, buffers.get(4).slice(), false);
        return lease;
    });
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) HashMap(java.util.HashMap) PriorityFrame(org.eclipse.jetty.http2.frames.PriorityFrame) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) ByteBuffer(java.nio.ByteBuffer) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Test(org.junit.Test)

Aggregations

HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)114 HttpFields (org.eclipse.jetty.http.HttpFields)111 MetaData (org.eclipse.jetty.http.MetaData)111 Test (org.junit.Test)106 CountDownLatch (java.util.concurrent.CountDownLatch)98 Stream (org.eclipse.jetty.http2.api.Stream)98 Session (org.eclipse.jetty.http2.api.Session)90 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)82 FuturePromise (org.eclipse.jetty.util.FuturePromise)69 DataFrame (org.eclipse.jetty.http2.frames.DataFrame)57 Callback (org.eclipse.jetty.util.Callback)54 HttpServletResponse (javax.servlet.http.HttpServletResponse)53 Promise (org.eclipse.jetty.util.Promise)50 ByteBuffer (java.nio.ByteBuffer)40 HttpServletRequest (javax.servlet.http.HttpServletRequest)39 HTTP2Session (org.eclipse.jetty.http2.HTTP2Session)38 IOException (java.io.IOException)37 ServletException (javax.servlet.ServletException)36 HashMap (java.util.HashMap)33 HttpServlet (javax.servlet.http.HttpServlet)33