Search in sources :

Example 6 with InputStream

use of java.io.InputStream 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 7 with InputStream

use of java.io.InputStream 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 8 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class AbstractServerTest method parseResponse.

protected boolean parseResponse(Socket client, Parser parser, long timeout) throws IOException {
    byte[] buffer = new byte[2048];
    InputStream input = client.getInputStream();
    client.setSoTimeout((int) timeout);
    while (true) {
        try {
            int read = input.read(buffer);
            if (read < 0)
                return true;
            parser.parse(ByteBuffer.wrap(buffer, 0, read));
            if (client.isClosed())
                return true;
        } catch (SocketTimeoutException x) {
            return false;
        }
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) InputStream(java.io.InputStream)

Example 9 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testBlockedReadIdle.

@Test
public void testBlockedReadIdle() throws Exception {
    Socket client = newClient();
    InputStream clientInputStream = client.getInputStream();
    OutputStream clientOutputStream = client.getOutputStream();
    client.setSoTimeout(5000);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    clientOutputStream.write("HelloWorld".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
        int b = clientInputStream.read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
    int idleTimeout = 500;
    _lastEndPoint.setIdleTimeout(idleTimeout);
    // Write 8 and cause block waiting for 10
    _blockAt = 10;
    clientOutputStream.write("12345678".getBytes(StandardCharsets.UTF_8));
    clientOutputStream.flush();
    // read until idle shutdown received
    long start = System.currentTimeMillis();
    int b = clientInputStream.read();
    assertEquals('E', b);
    long idle = System.currentTimeMillis() - start;
    assertTrue(idle > idleTimeout / 2);
    assertTrue(idle < idleTimeout * 2);
    for (char c : "E: 12345678".toCharArray()) {
        b = clientInputStream.read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    b = clientInputStream.read();
    assertEquals(-1, b);
    // But endpoint is still open.
    if (_lastEndPoint.isOpen())
        // Wait for another idle callback
        Thread.sleep(idleTimeout * 2);
    // endpoint is closed.
    assertFalse(_lastEndPoint.isOpen());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket) Test(org.junit.Test)

Example 10 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class SelectChannelEndPointInterestsTest method testReadBlockedThenWriteBlockedThenReadableThenWritable.

@Test
public void testReadBlockedThenWriteBlockedThenReadableThenWritable() throws Exception {
    final AtomicInteger size = new AtomicInteger(1024 * 1024);
    final AtomicReference<Exception> failure = new AtomicReference<>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final AtomicBoolean writeBlocked = new AtomicBoolean();
    init(new Interested() {

        @Override
        public void onFillable(EndPoint endPoint, AbstractConnection connection) {
            ByteBuffer input = BufferUtil.allocate(2);
            int read = fill(endPoint, input);
            if (read == 1) {
                byte b = input.get();
                if (b == 1) {
                    connection.fillInterested();
                    ByteBuffer output = ByteBuffer.allocate(size.get());
                    endPoint.write(new Callback() {
                    }, output);
                    latch1.countDown();
                } else {
                    latch2.countDown();
                }
            } else {
                failure.set(new Exception("Unexpectedly read " + read + " bytes"));
            }
        }

        @Override
        public void onIncompleteFlush() {
            writeBlocked.set(true);
        }

        private int fill(EndPoint endPoint, ByteBuffer buffer) {
            try {
                return endPoint.fill(buffer);
            } catch (IOException x) {
                failure.set(x);
                return 0;
            }
        }
    });
    Socket client = new Socket();
    client.connect(connector.getLocalAddress());
    client.setSoTimeout(5000);
    SocketChannel server = connector.accept();
    server.configureBlocking(false);
    selectorManager.accept(server);
    OutputStream clientOutput = client.getOutputStream();
    clientOutput.write(1);
    clientOutput.flush();
    Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
    // We do not read to keep the socket write blocked
    clientOutput.write(2);
    clientOutput.flush();
    Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
    // Sleep before reading to allow waking up the server only for read
    Thread.sleep(1000);
    // Now read what was written, waking up the server for write
    InputStream clientInput = client.getInputStream();
    while (size.getAndDecrement() > 0) clientInput.read();
    client.close();
    Assert.assertNull(failure.get());
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

InputStream (java.io.InputStream)33681 IOException (java.io.IOException)12617 ByteArrayInputStream (java.io.ByteArrayInputStream)7643 Test (org.junit.Test)7105 FileInputStream (java.io.FileInputStream)6956 File (java.io.File)5058 InputStreamReader (java.io.InputStreamReader)3045 URL (java.net.URL)3010 OutputStream (java.io.OutputStream)2893 BufferedInputStream (java.io.BufferedInputStream)2558 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2228 ArrayList (java.util.ArrayList)2193 FileOutputStream (java.io.FileOutputStream)2191 BufferedReader (java.io.BufferedReader)2039 Properties (java.util.Properties)1679 FileNotFoundException (java.io.FileNotFoundException)1503 HashMap (java.util.HashMap)1264 HttpURLConnection (java.net.HttpURLConnection)1144 Map (java.util.Map)866 Document (org.w3c.dom.Document)847