Search in sources :

Example 1 with ServerSessionListener

use of org.eclipse.jetty.http2.api.server.ServerSessionListener in project jetty.project by eclipse.

the class PrefaceTest method testOnPrefaceNotifiedForStandardUpgrade.

@Test
public void testOnPrefaceNotifiedForStandardUpgrade() throws Exception {
    Integer maxConcurrentStreams = 128;
    AtomicReference<CountDownLatch> serverPrefaceLatch = new AtomicReference<>(new CountDownLatch(1));
    AtomicReference<CountDownLatch> serverSettingsLatch = new AtomicReference<>(new CountDownLatch(1));
    HttpConfiguration config = new HttpConfiguration();
    prepareServer(new HttpConnectionFactory(config), new HTTP2CServerConnectionFactory(config) {

        @Override
        protected ServerSessionListener newSessionListener(Connector connector, EndPoint endPoint) {
            return new ServerSessionListener.Adapter() {

                @Override
                public Map<Integer, Integer> onPreface(Session session) {
                    Map<Integer, Integer> serverSettings = new HashMap<>();
                    serverSettings.put(SettingsFrame.MAX_CONCURRENT_STREAMS, maxConcurrentStreams);
                    serverPrefaceLatch.get().countDown();
                    return serverSettings;
                }

                @Override
                public void onSettings(Session session, SettingsFrame frame) {
                    serverSettingsLatch.get().countDown();
                }

                @Override
                public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
                    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();
    ByteBufferPool byteBufferPool = new MappedByteBufferPool();
    try (SocketChannel socket = SocketChannel.open()) {
        socket.connect(new InetSocketAddress("localhost", connector.getLocalPort()));
        String upgradeRequest = "" + "GET /one HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: \r\n" + "\r\n";
        ByteBuffer upgradeBuffer = ByteBuffer.wrap(upgradeRequest.getBytes(StandardCharsets.ISO_8859_1));
        socket.write(upgradeBuffer);
        // Make sure onPreface() is called on server.
        Assert.assertTrue(serverPrefaceLatch.get().await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS));
        // The 101 response is the reply to the client preface SETTINGS frame.
        ByteBuffer buffer = byteBufferPool.acquire(1024, true);
        http1: while (true) {
            BufferUtil.clearToFill(buffer);
            int read = socket.read(buffer);
            BufferUtil.flipToFlush(buffer, 0);
            if (read < 0)
                Assert.fail();
            int crlfs = 0;
            while (buffer.hasRemaining()) {
                byte b = buffer.get();
                if (b == '\r' || b == '\n')
                    ++crlfs;
                else
                    crlfs = 0;
                if (crlfs == 4)
                    break http1;
            }
        }
        // Reset the latches on server.
        serverPrefaceLatch.set(new CountDownLatch(1));
        serverSettingsLatch.set(new CountDownLatch(1));
        // After the 101, the client must send the connection preface.
        Generator generator = new Generator(byteBufferPool);
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        generator.control(lease, new PrefaceFrame());
        Map<Integer, Integer> clientSettings = new HashMap<>();
        clientSettings.put(SettingsFrame.ENABLE_PUSH, 1);
        generator.control(lease, new SettingsFrame(clientSettings, false));
        List<ByteBuffer> buffers = lease.getByteBuffers();
        socket.write(buffers.toArray(new ByteBuffer[buffers.size()]));
        // However, we should not call onPreface() again.
        Assert.assertFalse(serverPrefaceLatch.get().await(1, TimeUnit.SECONDS));
        // Although we should notify of the SETTINGS frame.
        Assert.assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS));
        CountDownLatch clientSettingsLatch = new CountDownLatch(1);
        AtomicBoolean responded = new AtomicBoolean();
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onSettings(SettingsFrame frame) {
                if (frame.isReply())
                    return;
                Assert.assertEquals(maxConcurrentStreams, frame.getSettings().get(SettingsFrame.MAX_CONCURRENT_STREAMS));
                clientSettingsLatch.countDown();
            }

            @Override
            public void onHeaders(HeadersFrame frame) {
                if (frame.isEndStream())
                    responded.set(true);
            }
        }, 4096, 8192);
        // HTTP/2 parsing.
        while (true) {
            parser.parse(buffer);
            if (responded.get())
                break;
            BufferUtil.clearToFill(buffer);
            int read = socket.read(buffer);
            BufferUtil.flipToFlush(buffer, 0);
            if (read < 0)
                Assert.fail();
        }
        Assert.assertTrue(clientSettingsLatch.await(5, TimeUnit.SECONDS));
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) Connector(org.eclipse.jetty.server.Connector) SocketChannel(java.nio.channels.SocketChannel) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) EndPoint(org.eclipse.jetty.io.EndPoint) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) HTTP2CServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) 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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Map(java.util.Map) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 2 with ServerSessionListener

use of org.eclipse.jetty.http2.api.server.ServerSessionListener in project jetty.project by eclipse.

the class AsyncServletTest method testStartAsyncThenServerIdleTimeout.

private void testStartAsyncThenServerIdleTimeout(long sessionTimeout, long streamTimeout) throws Exception {
    prepareServer(new HTTP2ServerConnectionFactory(new HttpConfiguration()) {

        @Override
        protected ServerSessionListener newSessionListener(Connector connector, EndPoint endPoint) {
            return new HTTPServerSessionListener(connector, endPoint) {

                @Override
                public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
                    stream.setIdleTimeout(streamTimeout);
                    return super.onNewStream(stream, frame);
                }
            };
        }
    });
    connector.setIdleTimeout(sessionTimeout);
    ServletContextHandler context = new ServletContextHandler(server, "/");
    long timeout = Math.min(sessionTimeout, streamTimeout);
    CountDownLatch errorLatch = new CountDownLatch(1);
    context.addServlet(new ServletHolder(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = (AsyncContext) request.getAttribute(AsyncContext.class.getName());
            if (asyncContext == null) {
                AsyncContext context = request.startAsync();
                context.setTimeout(2 * timeout);
                request.setAttribute(AsyncContext.class.getName(), context);
                context.addListener(new AsyncListener() {

                    @Override
                    public void onComplete(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                        event.getAsyncContext().complete();
                    }

                    @Override
                    public void onError(AsyncEvent event) throws IOException {
                        errorLatch.countDown();
                    }

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                    }
                });
            } else {
                throw new ServletException();
            }
        }
    }), servletPath + "/*");
    server.start();
    prepareClient();
    client.start();
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    CountDownLatch clientLatch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            if (response.getStatus() == HttpStatus.OK_200 && frame.isEndStream())
                clientLatch.countDown();
        }
    });
    // When the server idle times out, but the request has been dispatched
    // then the server must ignore the idle timeout as per Servlet semantic.
    Assert.assertFalse(errorLatch.await(2 * timeout, TimeUnit.MILLISECONDS));
    Assert.assertTrue(clientLatch.await(2 * timeout, TimeUnit.MILLISECONDS));
}
Also used : Connector(org.eclipse.jetty.server.Connector) AsyncListener(javax.servlet.AsyncListener) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AsyncContext(javax.servlet.AsyncContext) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) EndPoint(org.eclipse.jetty.io.EndPoint) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stream(org.eclipse.jetty.http2.api.Stream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) HTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) AsyncListener(javax.servlet.AsyncListener) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session)

Example 3 with ServerSessionListener

use of org.eclipse.jetty.http2.api.server.ServerSessionListener in project jetty.project by eclipse.

the class AbstractTest method start.

protected void start(ServerSessionListener listener) throws Exception {
    prepareServer(new RawHTTP2ServerConnectionFactory(new HttpConfiguration(), listener));
    server.start();
    prepareClient();
    client.start();
}
Also used : RawHTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Example 4 with ServerSessionListener

use of org.eclipse.jetty.http2.api.server.ServerSessionListener in project jetty.project by eclipse.

the class RawHTTP2ProxyTest method startServer.

private Server startServer(String name, ServerSessionListener listener) throws Exception {
    QueuedThreadPool serverExecutor = new QueuedThreadPool();
    serverExecutor.setName(name);
    Server server = new Server(serverExecutor);
    RawHTTP2ServerConnectionFactory connectionFactory = new RawHTTP2ServerConnectionFactory(new HttpConfiguration(), listener);
    ServerConnector connector = new ServerConnector(server, 1, 1, connectionFactory);
    server.addConnector(connector);
    server.setAttribute("connector", connector);
    servers.add(server);
    server.start();
    return server;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) RawHTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory) Server(org.eclipse.jetty.server.Server) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Example 5 with ServerSessionListener

use of org.eclipse.jetty.http2.api.server.ServerSessionListener in project jetty.project by eclipse.

the class FlowControlStalledTest method start.

protected void start(FlowControlStrategy.Factory flowControlFactory, ServerSessionListener listener) throws Exception {
    QueuedThreadPool serverExecutor = new QueuedThreadPool();
    serverExecutor.setName("server");
    server = new Server(serverExecutor);
    RawHTTP2ServerConnectionFactory connectionFactory = new RawHTTP2ServerConnectionFactory(new HttpConfiguration(), listener);
    connectionFactory.setFlowControlStrategyFactory(flowControlFactory);
    connector = new ServerConnector(server, connectionFactory);
    server.addConnector(connector);
    server.start();
    client = new HTTP2Client();
    QueuedThreadPool clientExecutor = new QueuedThreadPool();
    clientExecutor.setName("client");
    client.setExecutor(clientExecutor);
    client.setFlowControlStrategyFactory(flowControlFactory);
    client.start();
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) RawHTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory) Server(org.eclipse.jetty.server.Server) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Aggregations

HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)7 RawHTTP2ServerConnectionFactory (org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory)5 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)3 Server (org.eclipse.jetty.server.Server)3 ServerConnector (org.eclipse.jetty.server.ServerConnector)3 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 HttpFields (org.eclipse.jetty.http.HttpFields)2 MetaData (org.eclipse.jetty.http.MetaData)2 Session (org.eclipse.jetty.http2.api.Session)2 Stream (org.eclipse.jetty.http2.api.Stream)2 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)2 Generator (org.eclipse.jetty.http2.generator.Generator)2 EndPoint (org.eclipse.jetty.io.EndPoint)2 Connector (org.eclipse.jetty.server.Connector)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InetSocketAddress (java.net.InetSocketAddress)1 ByteBuffer (java.nio.ByteBuffer)1 SocketChannel (java.nio.channels.SocketChannel)1