Search in sources :

Example 16 with Generator

use of org.eclipse.jetty.http2.generator.Generator in project jetty.project by eclipse.

the class HTTP2CServerTest method testHTTP_2_0_DirectWithoutH2C.

@Test
public void testHTTP_2_0_DirectWithoutH2C() throws Exception {
    AtomicLong fills = new AtomicLong();
    // Remove "h2c", leaving only "http/1.1".
    connector.clearConnectionFactories();
    HttpConnectionFactory connectionFactory = new HttpConnectionFactory() {

        @Override
        public Connection newConnection(Connector connector, EndPoint endPoint) {
            HttpConnection connection = new HttpConnection(getHttpConfiguration(), connector, endPoint, getHttpCompliance(), isRecordHttpComplianceViolations()) {

                @Override
                public void onFillable() {
                    fills.incrementAndGet();
                    super.onFillable();
                }
            };
            return configure(connection, connector, endPoint);
        }
    };
    connector.addConnectionFactory(connectionFactory);
    connector.setDefaultProtocol(connectionFactory.getProtocol());
    // Now send a HTTP/2 direct request, which
    // will have the PRI * HTTP/2.0 preface.
    byteBufferPool = new MappedByteBufferPool();
    generator = new Generator(byteBufferPool);
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
        // We sent a HTTP/2 preface, but the server has no "h2c" connection
        // factory so it does not know how to handle this request.
        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        String responseLine = reader.readLine();
        Assert.assertThat(responseLine, Matchers.containsString(" 426 "));
        while (true) {
            if (reader.read() < 0)
                break;
        }
    }
    // Make sure we did not spin.
    Thread.sleep(1000);
    Assert.assertThat(fills.get(), Matchers.lessThan(5L));
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) InputStreamReader(java.io.InputStreamReader) HttpConnection(org.eclipse.jetty.server.HttpConnection) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) EndPoint(org.eclipse.jetty.io.EndPoint) Matchers.containsString(org.hamcrest.Matchers.containsString) ByteBuffer(java.nio.ByteBuffer) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) AtomicLong(java.util.concurrent.atomic.AtomicLong) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 17 with Generator

use of org.eclipse.jetty.http2.generator.Generator in project jetty.project by eclipse.

the class HTTP2ServerTest method testRequestWithContinuationFrames.

private void testRequestWithContinuationFrames(PriorityFrame priorityFrame, Callable<ByteBufferPool.Lease> frames) throws Exception {
    final CountDownLatch serverLatch = new CountDownLatch(1);
    startServer(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            if (priorityFrame != null) {
                PriorityFrame priority = frame.getPriority();
                Assert.assertNotNull(priority);
                Assert.assertEquals(priorityFrame.getStreamId(), priority.getStreamId());
                Assert.assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId());
                Assert.assertEquals(priorityFrame.getWeight(), priority.getWeight());
                Assert.assertEquals(priorityFrame.isExclusive(), priority.isExclusive());
            }
            serverLatch.countDown();
            MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
            HeadersFrame responseFrame = new HeadersFrame(stream.getId(), metaData, null, true);
            stream.headers(responseFrame, Callback.NOOP);
            return null;
        }
    });
    generator = new Generator(byteBufferPool, 4096, 4);
    ByteBufferPool.Lease lease = frames.call();
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
        output.flush();
        Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS));
        final CountDownLatch clientLatch = new CountDownLatch(1);
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onHeaders(HeadersFrame frame) {
                if (frame.isEndStream())
                    clientLatch.countDown();
            }
        }, 4096, 8192);
        boolean closed = parseResponse(client, parser);
        Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
        Assert.assertFalse(closed);
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) OutputStream(java.io.OutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) PriorityFrame(org.eclipse.jetty.http2.frames.PriorityFrame) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) HttpServletResponse(javax.servlet.http.HttpServletResponse) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) OutputStream(java.io.OutputStream) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Socket(java.net.Socket) Generator(org.eclipse.jetty.http2.generator.Generator)

Example 18 with Generator

use of org.eclipse.jetty.http2.generator.Generator in project jetty.project by eclipse.

the class HttpClientTransportOverHTTP2Test method testClientStopsServerDoesNotCloseClientCloses.

@Test
public void testClientStopsServerDoesNotCloseClientCloses() throws Exception {
    try (ServerSocket server = new ServerSocket(0)) {
        List<Session> sessions = new ArrayList<>();
        HTTP2Client h2Client = new HTTP2Client();
        HttpClient client = new HttpClient(new HttpClientTransportOverHTTP2(h2Client) {

            @Override
            protected HttpConnectionOverHTTP2 newHttpConnection(HttpDestination destination, Session session) {
                sessions.add(session);
                return super.newHttpConnection(destination, session);
            }
        }, null);
        QueuedThreadPool clientExecutor = new QueuedThreadPool();
        clientExecutor.setName("client");
        client.setExecutor(clientExecutor);
        client.start();
        CountDownLatch resultLatch = new CountDownLatch(1);
        client.newRequest("localhost", server.getLocalPort()).send(result -> {
            if (result.getResponse().getStatus() == HttpStatus.OK_200)
                resultLatch.countDown();
        });
        ByteBufferPool byteBufferPool = new MappedByteBufferPool();
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        Generator generator = new Generator(byteBufferPool);
        try (Socket socket = server.accept()) {
            socket.setSoTimeout(1000);
            OutputStream output = socket.getOutputStream();
            InputStream input = socket.getInputStream();
            ServerParser parser = new ServerParser(byteBufferPool, new ServerParser.Listener.Adapter() {

                @Override
                public void onHeaders(HeadersFrame request) {
                    // Server's preface.
                    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
                    // Reply to client's SETTINGS.
                    generator.control(lease, new SettingsFrame(new HashMap<>(), true));
                    // Response.
                    MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                    HeadersFrame response = new HeadersFrame(request.getStreamId(), metaData, null, true);
                    generator.control(lease, response);
                    try {
                        // Write the frames.
                        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
                    } catch (Throwable x) {
                        x.printStackTrace();
                    }
                }
            }, 4096, 8192);
            byte[] bytes = new byte[1024];
            while (true) {
                try {
                    int read = input.read(bytes);
                    if (read < 0)
                        Assert.fail();
                    parser.parse(ByteBuffer.wrap(bytes, 0, read));
                } catch (SocketTimeoutException x) {
                    break;
                }
            }
            Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
            // The client will send a GO_AWAY, but the server will not close.
            client.stop();
            // Give some time to process the stop/close operations.
            Thread.sleep(1000);
            Assert.assertTrue(h2Client.getBeans(Session.class).isEmpty());
            for (Session session : sessions) {
                Assert.assertTrue(session.isClosed());
                Assert.assertTrue(((HTTP2Session) session).isDisconnected());
            }
        }
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServerParser(org.eclipse.jetty.http2.parser.ServerParser) InputStream(java.io.InputStream) ServerSocket(java.net.ServerSocket) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) SocketTimeoutException(java.net.SocketTimeoutException) HttpClient(org.eclipse.jetty.client.HttpClient) HTTP2Client(org.eclipse.jetty.http2.client.HTTP2Client) HttpDestination(org.eclipse.jetty.client.HttpDestination) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 19 with Generator

use of org.eclipse.jetty.http2.generator.Generator in project jetty.project by eclipse.

the class AbstractServerTest method prepareServer.

private void prepareServer(ConnectionFactory connectionFactory) {
    QueuedThreadPool serverExecutor = new QueuedThreadPool();
    serverExecutor.setName("server");
    server = new Server(serverExecutor);
    connector = new ServerConnector(server, connectionFactory);
    server.addConnector(connector);
    path = "/test";
    byteBufferPool = new MappedByteBufferPool();
    generator = new Generator(byteBufferPool);
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) Server(org.eclipse.jetty.server.Server) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Generator(org.eclipse.jetty.http2.generator.Generator)

Example 20 with Generator

use of org.eclipse.jetty.http2.generator.Generator in project jetty.project by eclipse.

the class ContinuationParseTest method testParseOneByteAtATime.

@Test
public void testParseOneByteAtATime() throws Exception {
    ByteBufferPool byteBufferPool = new MappedByteBufferPool();
    HeadersGenerator generator = new HeadersGenerator(new HeaderGenerator(), new HpackEncoder());
    final List<HeadersFrame> frames = new ArrayList<>();
    Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

        @Override
        public void onHeaders(HeadersFrame frame) {
            frames.add(frame);
        }

        @Override
        public void onConnectionFailure(int error, String reason) {
            frames.add(new HeadersFrame(null, null, false));
        }
    }, 4096, 8192);
    // Iterate a few times to be sure the parser is properly reset.
    for (int i = 0; i < 2; ++i) {
        int streamId = 13;
        HttpFields fields = new HttpFields();
        fields.put("Accept", "text/html");
        fields.put("User-Agent", "Jetty");
        MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:8080"), "/path", HttpVersion.HTTP_2, fields);
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        generator.generateHeaders(lease, streamId, metaData, null, true);
        List<ByteBuffer> byteBuffers = lease.getByteBuffers();
        Assert.assertEquals(2, byteBuffers.size());
        ByteBuffer headersBody = byteBuffers.remove(1);
        int start = headersBody.position();
        int length = headersBody.remaining();
        int oneThird = length / 3;
        int lastThird = length - 2 * oneThird;
        // Adjust the length of the HEADERS frame.
        ByteBuffer headersHeader = byteBuffers.get(0);
        headersHeader.put(0, (byte) ((oneThird >>> 16) & 0xFF));
        headersHeader.put(1, (byte) ((oneThird >>> 8) & 0xFF));
        headersHeader.put(2, (byte) (oneThird & 0xFF));
        // Remove the END_HEADERS flag from the HEADERS header.
        headersHeader.put(4, (byte) (headersHeader.get(4) & ~Flags.END_HEADERS));
        // New HEADERS body.
        headersBody.position(start);
        headersBody.limit(start + oneThird);
        byteBuffers.add(headersBody.slice());
        // Split the rest of the HEADERS body into CONTINUATION frames.
        // First CONTINUATION header.
        byte[] continuationHeader1 = new byte[9];
        continuationHeader1[0] = (byte) ((oneThird >>> 16) & 0xFF);
        continuationHeader1[1] = (byte) ((oneThird >>> 8) & 0xFF);
        continuationHeader1[2] = (byte) (oneThird & 0xFF);
        continuationHeader1[3] = (byte) FrameType.CONTINUATION.getType();
        continuationHeader1[4] = Flags.NONE;
        continuationHeader1[5] = 0x00;
        continuationHeader1[6] = 0x00;
        continuationHeader1[7] = 0x00;
        continuationHeader1[8] = (byte) streamId;
        byteBuffers.add(ByteBuffer.wrap(continuationHeader1));
        // First CONTINUATION body.
        headersBody.position(start + oneThird);
        headersBody.limit(start + 2 * oneThird);
        byteBuffers.add(headersBody.slice());
        // Second CONTINUATION header.
        byte[] continuationHeader2 = new byte[9];
        continuationHeader2[0] = (byte) ((lastThird >>> 16) & 0xFF);
        continuationHeader2[1] = (byte) ((lastThird >>> 8) & 0xFF);
        continuationHeader2[2] = (byte) (lastThird & 0xFF);
        continuationHeader2[3] = (byte) FrameType.CONTINUATION.getType();
        continuationHeader2[4] = Flags.END_HEADERS;
        continuationHeader2[5] = 0x00;
        continuationHeader2[6] = 0x00;
        continuationHeader2[7] = 0x00;
        continuationHeader2[8] = (byte) streamId;
        byteBuffers.add(ByteBuffer.wrap(continuationHeader2));
        headersBody.position(start + 2 * oneThird);
        headersBody.limit(start + length);
        byteBuffers.add(headersBody.slice());
        frames.clear();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            while (buffer.hasRemaining()) {
                parser.parse(ByteBuffer.wrap(new byte[] { buffer.get() }));
            }
        }
        Assert.assertEquals(1, frames.size());
        HeadersFrame frame = frames.get(0);
        Assert.assertEquals(streamId, frame.getStreamId());
        Assert.assertTrue(frame.isEndStream());
        MetaData.Request request = (MetaData.Request) frame.getMetaData();
        Assert.assertEquals(metaData.getMethod(), request.getMethod());
        Assert.assertEquals(metaData.getURI(), request.getURI());
        for (int j = 0; j < fields.size(); ++j) {
            HttpField field = fields.getField(j);
            Assert.assertTrue(request.getFields().contains(field));
        }
        PriorityFrame priority = frame.getPriority();
        Assert.assertNull(priority);
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ArrayList(java.util.ArrayList) HeadersGenerator(org.eclipse.jetty.http2.generator.HeadersGenerator) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HeaderGenerator(org.eclipse.jetty.http2.generator.HeaderGenerator) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) HpackEncoder(org.eclipse.jetty.http2.hpack.HpackEncoder) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) HttpField(org.eclipse.jetty.http.HttpField) Test(org.junit.Test)

Aggregations

ByteBufferPool (org.eclipse.jetty.io.ByteBufferPool)29 ByteBuffer (java.nio.ByteBuffer)28 MappedByteBufferPool (org.eclipse.jetty.io.MappedByteBufferPool)28 Parser (org.eclipse.jetty.http2.parser.Parser)27 Test (org.junit.Test)25 ArrayList (java.util.ArrayList)21 HeaderGenerator (org.eclipse.jetty.http2.generator.HeaderGenerator)21 HttpFields (org.eclipse.jetty.http.HttpFields)10 MetaData (org.eclipse.jetty.http.MetaData)10 Generator (org.eclipse.jetty.http2.generator.Generator)10 HashMap (java.util.HashMap)6 HostPortHttpField (org.eclipse.jetty.http.HostPortHttpField)6 OutputStream (java.io.OutputStream)5 Socket (java.net.Socket)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)5 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)5 PrefaceFrame (org.eclipse.jetty.http2.frames.PrefaceFrame)5 SettingsFrame (org.eclipse.jetty.http2.frames.SettingsFrame)5 HttpField (org.eclipse.jetty.http.HttpField)4