Search in sources :

Example 21 with ByteBufferPool

use of org.eclipse.jetty.io.ByteBufferPool in project jetty.project by eclipse.

the class HttpSenderOverHTTP method sendContent.

@Override
protected void sendContent(HttpExchange exchange, HttpContent content, Callback callback) {
    try {
        HttpClient client = getHttpChannel().getHttpDestination().getHttpClient();
        ByteBufferPool bufferPool = client.getByteBufferPool();
        ByteBuffer chunk = null;
        while (true) {
            ByteBuffer contentBuffer = content.getByteBuffer();
            boolean lastContent = content.isLast();
            HttpGenerator.Result result = generator.generateRequest(null, null, chunk, contentBuffer, lastContent);
            if (LOG.isDebugEnabled())
                LOG.debug("Generated content ({} bytes) - {}/{}", contentBuffer == null ? -1 : contentBuffer.remaining(), result, generator);
            switch(result) {
                case NEED_CHUNK:
                    {
                        chunk = bufferPool.acquire(HttpGenerator.CHUNK_SIZE, false);
                        break;
                    }
                case FLUSH:
                    {
                        EndPoint endPoint = getHttpChannel().getHttpConnection().getEndPoint();
                        if (chunk != null)
                            endPoint.write(new ByteBufferRecyclerCallback(callback, bufferPool, chunk), chunk, contentBuffer);
                        else
                            endPoint.write(callback, contentBuffer);
                        return;
                    }
                case SHUTDOWN_OUT:
                    {
                        shutdownOutput();
                        break;
                    }
                case CONTINUE:
                    {
                        if (lastContent)
                            break;
                        callback.succeeded();
                        return;
                    }
                case DONE:
                    {
                        callback.succeeded();
                        return;
                    }
                default:
                    {
                        throw new IllegalStateException(result.toString());
                    }
            }
        }
    } catch (Throwable x) {
        if (LOG.isDebugEnabled())
            LOG.debug(x);
        callback.failed(x);
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) HttpClient(org.eclipse.jetty.client.HttpClient) EndPoint(org.eclipse.jetty.io.EndPoint) HttpGenerator(org.eclipse.jetty.http.HttpGenerator) ByteBuffer(java.nio.ByteBuffer)

Example 22 with ByteBufferPool

use of org.eclipse.jetty.io.ByteBufferPool in project jetty.project by eclipse.

the class PrefaceTest method testClientPrefaceReplySentAfterServerPreface.

@Test
public void testClientPrefaceReplySentAfterServerPreface() throws Exception {
    start(new ServerSessionListener.Adapter() {

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

        @Override
        public void onPing(Session session, PingFrame frame) {
            session.close(ErrorCode.NO_ERROR.code, null, Callback.NOOP);
        }
    });
    ByteBufferPool byteBufferPool = client.getByteBufferPool();
    try (SocketChannel socket = SocketChannel.open()) {
        socket.connect(new InetSocketAddress("localhost", connector.getLocalPort()));
        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, 0);
        generator.control(lease, new SettingsFrame(clientSettings, false));
        // The PING frame just to make sure the client stops reading.
        generator.control(lease, new PingFrame(true));
        List<ByteBuffer> buffers = lease.getByteBuffers();
        socket.write(buffers.toArray(new ByteBuffer[buffers.size()]));
        Queue<SettingsFrame> settings = new ArrayDeque<>();
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onSettings(SettingsFrame frame) {
                settings.offer(frame);
            }
        }, 4096, 8192);
        ByteBuffer buffer = byteBufferPool.acquire(1024, true);
        while (true) {
            BufferUtil.clearToFill(buffer);
            int read = socket.read(buffer);
            BufferUtil.flipToFlush(buffer, 0);
            if (read < 0)
                break;
            parser.parse(buffer);
        }
        Assert.assertEquals(2, settings.size());
        SettingsFrame frame1 = settings.poll();
        Assert.assertFalse(frame1.isReply());
        SettingsFrame frame2 = settings.poll();
        Assert.assertTrue(frame2.isReply());
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) SocketChannel(java.nio.channels.SocketChannel) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) PingFrame(org.eclipse.jetty.http2.frames.PingFrame) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) ByteBuffer(java.nio.ByteBuffer) ArrayDeque(java.util.ArrayDeque) EndPoint(org.eclipse.jetty.io.EndPoint) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) 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 23 with ByteBufferPool

use of org.eclipse.jetty.io.ByteBufferPool 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 24 with ByteBufferPool

use of org.eclipse.jetty.io.ByteBufferPool in project jetty.project by eclipse.

the class HTTP2ClientConnectionFactory method newConnection.

@Override
public Connection newConnection(EndPoint endPoint, Map<String, Object> context) throws IOException {
    HTTP2Client client = (HTTP2Client) context.get(CLIENT_CONTEXT_KEY);
    ByteBufferPool byteBufferPool = (ByteBufferPool) context.get(BYTE_BUFFER_POOL_CONTEXT_KEY);
    Executor executor = (Executor) context.get(EXECUTOR_CONTEXT_KEY);
    Scheduler scheduler = (Scheduler) context.get(SCHEDULER_CONTEXT_KEY);
    Session.Listener listener = (Session.Listener) context.get(SESSION_LISTENER_CONTEXT_KEY);
    @SuppressWarnings("unchecked") Promise<Session> promise = (Promise<Session>) context.get(SESSION_PROMISE_CONTEXT_KEY);
    Generator generator = new Generator(byteBufferPool);
    FlowControlStrategy flowControl = client.getFlowControlStrategyFactory().newFlowControlStrategy();
    HTTP2ClientSession session = new HTTP2ClientSession(scheduler, endPoint, generator, listener, flowControl);
    Parser parser = new Parser(byteBufferPool, session, 4096, 8192);
    HTTP2ClientConnection connection = new HTTP2ClientConnection(client, byteBufferPool, executor, endPoint, parser, session, client.getInputBufferSize(), promise, listener);
    connection.addListener(connectionListener);
    return customize(connection, context);
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) Scheduler(org.eclipse.jetty.util.thread.Scheduler) Parser(org.eclipse.jetty.http2.parser.Parser) FlowControlStrategy(org.eclipse.jetty.http2.FlowControlStrategy) Promise(org.eclipse.jetty.util.Promise) Executor(java.util.concurrent.Executor) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Generator(org.eclipse.jetty.http2.generator.Generator)

Example 25 with ByteBufferPool

use of org.eclipse.jetty.io.ByteBufferPool in project jetty.project by eclipse.

the class HttpClientTimeoutTest method testIdleTimeout.

@Test
public void testIdleTimeout() throws Throwable {
    long timeout = 1000;
    start(new TimeoutHandler(2 * timeout));
    client.stop();
    final AtomicBoolean sslIdle = new AtomicBoolean();
    client = new HttpClient(new HttpClientTransportOverHTTP() {

        @Override
        public HttpDestination newHttpDestination(Origin origin) {
            return new HttpDestinationOverHTTP(getHttpClient(), origin) {

                @Override
                protected ClientConnectionFactory newSslClientConnectionFactory(ClientConnectionFactory connectionFactory) {
                    HttpClient client = getHttpClient();
                    return new SslClientConnectionFactory(client.getSslContextFactory(), client.getByteBufferPool(), client.getExecutor(), connectionFactory) {

                        @Override
                        protected SslConnection newSslConnection(ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine engine) {
                            return new SslConnection(byteBufferPool, executor, endPoint, engine) {

                                @Override
                                protected boolean onReadTimeout() {
                                    sslIdle.set(true);
                                    return super.onReadTimeout();
                                }
                            };
                        }
                    };
                }
            };
        }
    }, sslContextFactory);
    client.setIdleTimeout(timeout);
    client.start();
    try {
        client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).send();
        Assert.fail();
    } catch (Exception x) {
        Assert.assertFalse(sslIdle.get());
        Assert.assertThat(x.getCause(), Matchers.instanceOf(TimeoutException.class));
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) SSLEngine(javax.net.ssl.SSLEngine) SslClientConnectionFactory(org.eclipse.jetty.io.ssl.SslClientConnectionFactory) HttpClientTransportOverHTTP(org.eclipse.jetty.client.http.HttpClientTransportOverHTTP) ClientConnectionFactory(org.eclipse.jetty.io.ClientConnectionFactory) SslClientConnectionFactory(org.eclipse.jetty.io.ssl.SslClientConnectionFactory) EndPoint(org.eclipse.jetty.io.EndPoint) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) SslConnection(org.eclipse.jetty.io.ssl.SslConnection) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Executor(java.util.concurrent.Executor) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) Test(org.junit.Test)

Aggregations

ByteBufferPool (org.eclipse.jetty.io.ByteBufferPool)72 ByteBuffer (java.nio.ByteBuffer)53 Test (org.junit.Test)51 MappedByteBufferPool (org.eclipse.jetty.io.MappedByteBufferPool)40 Parser (org.eclipse.jetty.http2.parser.Parser)37 HttpFields (org.eclipse.jetty.http.HttpFields)29 MetaData (org.eclipse.jetty.http.MetaData)24 ArrayList (java.util.ArrayList)22 HashMap (java.util.HashMap)21 HeaderGenerator (org.eclipse.jetty.http2.generator.HeaderGenerator)21 PrefaceFrame (org.eclipse.jetty.http2.frames.PrefaceFrame)20 SettingsFrame (org.eclipse.jetty.http2.frames.SettingsFrame)20 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)19 OutputStream (java.io.OutputStream)16 Socket (java.net.Socket)16 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)14 IOException (java.io.IOException)13 CountDownLatch (java.util.concurrent.CountDownLatch)13 EndPoint (org.eclipse.jetty.io.EndPoint)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8