use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.
the class HTTP2ServerTest method testCommitFailure.
@Test
public void testCommitFailure() throws Exception {
final long delay = 1000;
final AtomicBoolean broken = new AtomicBoolean();
startServer(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// Wait for the SETTINGS frames to be exchanged.
Thread.sleep(delay);
broken.set(true);
} catch (InterruptedException x) {
throw new InterruptedIOException();
}
}
});
server.stop();
ServerConnector connector2 = new ServerConnector(server, new HTTP2ServerConnectionFactory(new HttpConfiguration())) {
@Override
protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException {
return new SocketChannelEndPoint(channel, selectSet, key, getScheduler()) {
@Override
public void write(Callback callback, ByteBuffer... buffers) throws IllegalStateException {
if (broken.get())
callback.failed(new IOException("explicitly_thrown_by_test"));
else
super.write(callback, buffers);
}
};
}
};
server.addConnector(connector2);
server.start();
ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
generator.control(lease, new PrefaceFrame());
generator.control(lease, new SettingsFrame(new HashMap<>(), false));
MetaData.Request metaData = newRequest("GET", new HttpFields());
generator.control(lease, new HeadersFrame(1, metaData, null, true));
try (Socket client = new Socket("localhost", connector2.getLocalPort())) {
OutputStream output = client.getOutputStream();
for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
// The server will close the connection abruptly since it
// cannot write and therefore cannot even send the GO_AWAY.
Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter(), 4096, 8192);
boolean closed = parseResponse(client, parser, 2 * delay);
Assert.assertTrue(closed);
}
}
use of java.util.concurrent.atomic.AtomicBoolean 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.AtomicBoolean in project jetty.project by eclipse.
the class ProxyServletLoadTest method test.
@Test
public void test() throws Exception {
startServer(new HttpServlet() {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getHeader("Via") != null)
resp.addHeader(PROXIED_HEADER, "true");
IO.copy(req.getInputStream(), resp.getOutputStream());
}
});
startProxy();
startClient();
// Number of clients to simulate
int clientCount = Runtime.getRuntime().availableProcessors();
// Latch for number of clients still active (used to terminate test)
final CountDownLatch activeClientLatch = new CountDownLatch(clientCount);
// Atomic Boolean to track that its OK to still continue looping.
// When this goes false, that means one of the client threads has
// encountered an error condition, and should allow all remaining
// client threads to finish cleanly.
final AtomicBoolean success = new AtomicBoolean(true);
int iterations = 1000;
// Start clients
for (int i = 0; i < clientCount; i++) {
ClientLoop r = new ClientLoop(activeClientLatch, success, client, "localhost", serverConnector.getLocalPort(), iterations);
String name = "client-" + i;
Thread thread = new Thread(r, name);
thread.start();
}
Assert.assertTrue(activeClientLatch.await(Math.max(clientCount * iterations * 10, 5000), TimeUnit.MILLISECONDS));
Assert.assertTrue(success.get());
}
use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.
the class HttpServerTestBase method testInterruptedRequest.
@Test
public void testInterruptedRequest() throws Exception {
final AtomicBoolean fourBytesRead = new AtomicBoolean(false);
final AtomicBoolean earlyEOFException = new AtomicBoolean(false);
configureServer(new AbstractHandler.ErrorDispatchHandler() {
@Override
public void doNonErrorHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
int contentLength = request.getContentLength();
ServletInputStream inputStream = request.getInputStream();
for (int i = 0; i < contentLength; i++) {
try {
inputStream.read();
} catch (EofException e) {
earlyEOFException.set(true);
throw new QuietServletException(e);
}
if (i == 3)
fourBytesRead.set(true);
}
}
});
StringBuffer request = new StringBuffer("GET / HTTP/1.0\n");
request.append("Host: localhost\n");
request.append("Content-length: 6\n\n");
request.append("foo");
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
OutputStream os = client.getOutputStream();
os.write(request.toString().getBytes());
os.flush();
client.shutdownOutput();
String response = readResponse(client);
client.close();
assertThat("response contains 500", response, Matchers.containsString(" 500 "));
assertThat("The 4th byte (-1) has not been passed to the handler", fourBytesRead.get(), is(false));
assertThat("EofException has been caught", earlyEOFException.get(), is(true));
}
use of java.util.concurrent.atomic.AtomicBoolean 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();
}
}
Aggregations