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());
}
}
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());
}
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();
}
}
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));
}
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;
}
});
}
Aggregations