Search in sources :

Example 1 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testRejectedExecution.

// TODO make this test reliable
@Test
@Ignore
public void testRejectedExecution() throws Exception {
    _manager.stop();
    _threadPool.stop();
    final CountDownLatch latch = new CountDownLatch(1);
    BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(4);
    _threadPool = new QueuedThreadPool(4, 4, 60000, q);
    _manager = new SelectorManager(_threadPool, _scheduler, 1) {

        @Override
        protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey) throws IOException {
            SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, selectionKey, getScheduler());
            _lastEndPoint = endp;
            _lastEndPointLatch.countDown();
            return endp;
        }

        @Override
        public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            return new TestConnection(endpoint, latch);
        }
    };
    _threadPool.start();
    _manager.start();
    AtomicInteger timeout = new AtomicInteger();
    AtomicInteger rejections = new AtomicInteger();
    AtomicInteger echoed = new AtomicInteger();
    CountDownLatch closed = new CountDownLatch(20);
    for (int i = 0; i < 20; i++) {
        new Thread() {

            public void run() {
                try (Socket client = newClient()) {
                    client.setSoTimeout(5000);
                    SocketChannel server = _connector.accept();
                    server.configureBlocking(false);
                    _manager.accept(server);
                    // Write client to server
                    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
                    client.getOutputStream().flush();
                    client.shutdownOutput();
                    // Verify echo server to client
                    for (char c : "HelloWorld".toCharArray()) {
                        int b = client.getInputStream().read();
                        assertTrue(b > 0);
                        assertEquals(c, (char) b);
                    }
                    assertEquals(-1, client.getInputStream().read());
                    echoed.incrementAndGet();
                } catch (SocketTimeoutException x) {
                    x.printStackTrace();
                    timeout.incrementAndGet();
                } catch (Throwable x) {
                    rejections.incrementAndGet();
                } finally {
                    closed.countDown();
                }
            }
        }.start();
    }
    // unblock the handling
    latch.countDown();
    // wait for all clients to complete or fail
    closed.await();
    // assert some clients must have been rejected
    Assert.assertThat(rejections.get(), Matchers.greaterThan(0));
    // but not all of them
    Assert.assertThat(rejections.get(), Matchers.lessThan(20));
    // none should have timed out
    Assert.assertThat(timeout.get(), Matchers.equalTo(0));
    // and the rest should have worked
    Assert.assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get()));
    // and the selector is still working for new requests
    try (Socket client = newClient()) {
        client.setSoTimeout(5000);
        SocketChannel server = _connector.accept();
        server.configureBlocking(false);
        _manager.accept(server);
        // Write client to server
        client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
        client.getOutputStream().flush();
        client.shutdownOutput();
        // Verify echo server to client
        for (char c : "HelloWorld".toCharArray()) {
            int b = client.getInputStream().read();
            assertTrue(b > 0);
            assertEquals(c, (char) b);
        }
        assertEquals(-1, client.getInputStream().read());
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) SocketTimeoutException(java.net.SocketTimeoutException) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SelectableChannel(java.nio.channels.SelectableChannel) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger 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)

Example 3 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class SslContextFactoryReloadTest method testReloadWhileServing.

@Test
public void testReloadWhileServing() throws Exception {
    start(new EchoHandler());
    Scheduler scheduler = new ScheduledExecutorScheduler();
    scheduler.start();
    try {
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, null);
        SSLSocketFactory socketFactory = ctx.getSocketFactory();
        // Perform 4 reloads while connections are being served.
        AtomicInteger reloads = new AtomicInteger(4);
        long reloadPeriod = 500;
        AtomicBoolean running = new AtomicBoolean(true);
        scheduler.schedule(new Runnable() {

            @Override
            public void run() {
                if (reloads.decrementAndGet() == 0) {
                    running.set(false);
                } else {
                    try {
                        sslContextFactory.reload(sslContextFactory -> {
                            if (sslContextFactory.getKeyStorePath().endsWith(KEYSTORE_1))
                                sslContextFactory.setKeyStorePath(KEYSTORE_2);
                            else
                                sslContextFactory.setKeyStorePath(KEYSTORE_1);
                        });
                        scheduler.schedule(this, reloadPeriod, TimeUnit.MILLISECONDS);
                    } catch (Exception x) {
                        running.set(false);
                        reloads.set(-1);
                    }
                }
            }
        }, reloadPeriod, TimeUnit.MILLISECONDS);
        byte[] content = new byte[16 * 1024];
        while (running.get()) {
            try (SSLSocket client = (SSLSocket) socketFactory.createSocket("localhost", connector.getLocalPort())) {
                // We need to invalidate the session every time we open a new SSLSocket.
                // This is because when the client uses session resumption, it caches
                // the server certificates and then checks that it is the same during
                // a new TLS handshake. If the SslContextFactory is reloaded during the
                // TLS handshake, the client will see the new certificate and blow up.
                // Note that browsers can handle this case better: they will just not
                // use session resumption and fallback to the normal TLS handshake.
                client.getSession().invalidate();
                String request1 = "" + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Length: " + content.length + "\r\n" + "\r\n";
                OutputStream outputStream = client.getOutputStream();
                outputStream.write(request1.getBytes(StandardCharsets.UTF_8));
                outputStream.write(content);
                outputStream.flush();
                InputStream inputStream = client.getInputStream();
                HttpTester.Response response1 = HttpTester.parseResponse(HttpTester.from(inputStream));
                Assert.assertNotNull(response1);
                Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
                String request2 = "" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
                outputStream.write(request2.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                HttpTester.Response response2 = HttpTester.parseResponse(HttpTester.from(inputStream));
                Assert.assertNotNull(response2);
                Assert.assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
            }
        }
        Assert.assertEquals(0, reloads.get());
    } finally {
        scheduler.stop();
    }
}
Also used : Request(org.eclipse.jetty.server.Request) HttpTester(org.eclipse.jetty.http.HttpTester) Handler(org.eclipse.jetty.server.Handler) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpVersion(org.eclipse.jetty.http.HttpVersion) Scheduler(org.eclipse.jetty.util.thread.Scheduler) SSLSocket(javax.net.ssl.SSLSocket) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) HttpStatus(org.eclipse.jetty.http.HttpStatus) Server(org.eclipse.jetty.server.Server) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) IO(org.eclipse.jetty.util.IO) StandardCharsets(java.nio.charset.StandardCharsets) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) ServerConnector(org.eclipse.jetty.server.ServerConnector) Assert(org.junit.Assert) InputStream(java.io.InputStream) Scheduler(org.eclipse.jetty.util.thread.Scheduler) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpTester(org.eclipse.jetty.http.HttpTester) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Test(org.junit.Test)

Example 4 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project jetty.project by eclipse.

the class ThreadLimitHandlerTest method testLimit.

@Test
public void testLimit() throws Exception {
    ThreadLimitHandler handler = new ThreadLimitHandler("Forwarded");
    handler.setThreadLimit(4);
    AtomicInteger count = new AtomicInteger(0);
    AtomicInteger total = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(1);
    handler.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            response.setStatus(HttpStatus.OK_200);
            if ("/other".equals(target))
                return;
            try {
                count.incrementAndGet();
                total.incrementAndGet();
                latch.await();
            } catch (InterruptedException e) {
                throw new ServletException(e);
            } finally {
                count.decrementAndGet();
            }
        }
    });
    _server.setHandler(handler);
    _server.start();
    Socket[] client = new Socket[10];
    for (int i = 0; i < client.length; i++) {
        client[i] = new Socket("127.0.0.1", _connector.getLocalPort());
        client[i].getOutputStream().write(("GET /" + i + " HTTP/1.0\r\nForwarded: for=1.2.3.4\r\n\r\n").getBytes());
        client[i].getOutputStream().flush();
    }
    long wait = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
    while (count.get() < 4 && System.nanoTime() < wait) Thread.sleep(1);
    assertThat(count.get(), is(4));
    // check that other requests are not blocked
    assertThat(_local.getResponse("GET /other HTTP/1.0\r\nForwarded: for=6.6.6.6\r\n\r\n"), Matchers.containsString(" 200 OK"));
    // let the other requests go
    latch.countDown();
    while (total.get() < 10 && System.nanoTime() < wait) Thread.sleep(10);
    assertThat(total.get(), is(10));
    while (count.get() > 0 && System.nanoTime() < wait) Thread.sleep(10);
    assertThat(count.get(), is(0));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Test(org.junit.Test)

Example 5 with AtomicInteger

use of java.util.concurrent.atomic.AtomicInteger in project vert.x by eclipse.

the class Http1xTest method testInvalidTrailersInHttpClientResponse.

@Test
public void testInvalidTrailersInHttpClientResponse() throws Exception {
    server.requestHandler(req -> {
        NetSocket so = req.netSocket();
        so.write("HTTP/1.1 200 OK\r\n");
        so.write("Transfer-Encoding: chunked\r\n");
        so.write("\r\n");
        so.write("0\r\n");
        for (int i = 0; i < 2000; i++) {
            so.write("01234567");
        }
    });
    AtomicInteger status = new AtomicInteger();
    testHttpClientResponseDecodeError(err -> {
        switch(status.incrementAndGet()) {
            case 1:
                assertTrue(err instanceof TooLongFrameException);
                break;
            case 2:
                assertTrue(err instanceof VertxException);
                assertTrue(err.getMessage().equals("Connection was closed"));
                testComplete();
                break;
        }
    });
}
Also used : TooLongFrameException(io.netty.handler.codec.TooLongFrameException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Aggregations

AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8428 Test (org.junit.Test)3991 CountDownLatch (java.util.concurrent.CountDownLatch)1141 ArrayList (java.util.ArrayList)1107 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)906 List (java.util.List)808 IOException (java.io.IOException)751 AtomicReference (java.util.concurrent.atomic.AtomicReference)636 HashMap (java.util.HashMap)570 Map (java.util.Map)519 Test (org.testng.annotations.Test)428 TimeUnit (java.util.concurrent.TimeUnit)377 AtomicLong (java.util.concurrent.atomic.AtomicLong)376 Test (org.junit.jupiter.api.Test)376 HashSet (java.util.HashSet)353 File (java.io.File)350 ExecutorService (java.util.concurrent.ExecutorService)344 Arrays (java.util.Arrays)336 Collections (java.util.Collections)312 Set (java.util.Set)312