use of javax.servlet.WriteListener in project java-chassis by ServiceComb.
the class TestStandardHttpServletResponseEx method flushBuffer.
@Test
public void flushBuffer() throws IOException {
Buffer buffer = Buffer.buffer();
ServletOutputStream output = new ServletOutputStream() {
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
@Override
public void write(int b) throws IOException {
buffer.appendByte((byte) b);
}
};
response = new MockUp<HttpServletResponse>() {
@Mock
ServletOutputStream getOutputStream() {
return output;
}
}.getMockInstance();
responseEx = new StandardHttpServletResponseEx(response);
// no body
responseEx.flushBuffer();
Assert.assertEquals(0, buffer.length());
Buffer body = Buffer.buffer().appendString("body");
responseEx.setBodyBuffer(body);
responseEx.flushBuffer();
Assert.assertEquals("body", buffer.toString());
}
use of javax.servlet.WriteListener in project jetty.project by eclipse.
the class StreamResetTest method testResetAfterAsyncRequestAsyncWriteStalledByFlowControl.
@Test
public void testResetAfterAsyncRequestAsyncWriteStalledByFlowControl() throws Exception {
int windowSize = FlowControlStrategy.DEFAULT_WINDOW_SIZE;
CountDownLatch writeLatch = new CountDownLatch(1);
start(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext asyncContext = request.startAsync();
ServletOutputStream output = response.getOutputStream();
output.setWriteListener(new WriteListener() {
private boolean written;
@Override
public void onWritePossible() throws IOException {
while (output.isReady()) {
if (written) {
asyncContext.complete();
break;
} else {
output.write(new byte[10 * windowSize]);
written = true;
}
}
}
@Override
public void onError(Throwable t) {
writeLatch.countDown();
}
});
}
});
Deque<Callback> dataQueue = new ArrayDeque<>();
AtomicLong received = new AtomicLong();
CountDownLatch latch = new CountDownLatch(1);
Session client = newClient(new Session.Listener.Adapter());
MetaData.Request request = newRequest("GET", new HttpFields());
HeadersFrame frame = new HeadersFrame(request, null, true);
FuturePromise<Stream> promise = new FuturePromise<>();
client.newStream(frame, promise, new Stream.Listener.Adapter() {
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
dataQueue.offer(callback);
// Do not consume the data yet.
if (received.addAndGet(frame.getData().remaining()) == windowSize)
latch.countDown();
}
});
Stream stream = promise.get(5, TimeUnit.SECONDS);
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
// Reset and consume.
stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP);
dataQueue.forEach(Callback::succeeded);
Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS));
}
use of javax.servlet.WriteListener in project jetty.project by eclipse.
the class SSLAsyncIOServletTest method testAsyncIOWritesWithAggregation.
@Test
public void testAsyncIOWritesWithAggregation() throws Exception {
Random random = new Random();
String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final byte[] content = new byte[50000];
for (int i = 0; i < content.length; ++i) content[i] = (byte) chars.charAt(random.nextInt(chars.length()));
prepare(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(0);
final int bufferSize = 4096;
response.setBufferSize(bufferSize);
response.getOutputStream().setWriteListener(new WriteListener() {
private int writes;
private int written;
@Override
public void onWritePossible() throws IOException {
ServletOutputStream output = asyncContext.getResponse().getOutputStream();
do {
int toWrite = content.length - written;
if (toWrite == 0) {
asyncContext.complete();
return;
}
toWrite = Math.min(toWrite, bufferSize);
// trigger the condition where the bytes are aggregated.
if (writes == 1)
toWrite -= 16;
output.write(content, written, toWrite);
++writes;
written += toWrite;
} while (output.isReady());
}
@Override
public void onError(Throwable t) {
asyncContext.complete();
}
});
}
});
try (Socket client = newClient()) {
String request = "" + "GET " + contextPath + servletPath + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
OutputStream output = client.getOutputStream();
output.write(request.getBytes("UTF-8"));
output.flush();
InputStream inputStream = client.getInputStream();
HttpTester.Response response = HttpTester.parseResponse(inputStream);
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(content, response.getContent().getBytes("UTF-8"));
}
}
use of javax.servlet.WriteListener in project jetty.project by eclipse.
the class AsyncIOServletTest method testAsyncWriteLessThanContentLengthFlushed.
@Test
public void testAsyncWriteLessThanContentLengthFlushed() throws Exception {
CountDownLatch complete = new CountDownLatch(1);
start(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentLength(10);
AsyncContext async = request.startAsync();
ServletOutputStream out = response.getOutputStream();
AtomicInteger state = new AtomicInteger(0);
out.setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
while (true) {
if (!out.isReady())
return;
switch(state.get()) {
case 0:
state.incrementAndGet();
WriteListener listener = this;
new Thread(() -> {
try {
Thread.sleep(50);
listener.onWritePossible();
} catch (Exception e) {
}
}).start();
return;
case 1:
state.incrementAndGet();
out.flush();
break;
case 2:
state.incrementAndGet();
out.write("12345".getBytes());
break;
case 3:
async.complete();
complete.countDown();
return;
}
}
}
@Override
public void onError(Throwable t) {
}
});
}
});
AtomicBoolean failed = new AtomicBoolean(false);
CountDownLatch clientLatch = new CountDownLatch(3);
client.newRequest(newURI()).path(servletPath).onResponseHeaders(response -> {
if (response.getStatus() == HttpStatus.OK_200)
clientLatch.countDown();
}).onResponseContent(new Response.ContentListener() {
@Override
public void onContent(Response response, ByteBuffer content) {
// System.err.println("Content: "+BufferUtil.toDetailString(content));
}
}).onResponseFailure(new Response.FailureListener() {
@Override
public void onFailure(Response response, Throwable failure) {
clientLatch.countDown();
}
}).send(result -> {
failed.set(result.isFailed());
clientLatch.countDown();
clientLatch.countDown();
clientLatch.countDown();
});
assertTrue(complete.await(10, TimeUnit.SECONDS));
assertTrue(clientLatch.await(10, TimeUnit.SECONDS));
assertTrue(failed.get());
}
use of javax.servlet.WriteListener in project neo4j by neo4j.
the class BatchOperationService method batchProcessAndStream.
private Response batchProcessAndStream(final UriInfo uriInfo, final HttpHeaders httpHeaders, final HttpServletRequest req, final InputStream body) {
try {
final StreamingOutput stream = new StreamingOutput() {
@Override
public void write(final OutputStream output) throws IOException, WebApplicationException {
try {
final ServletOutputStream servletOutputStream = new ServletOutputStream() {
@Override
public void write(int i) throws IOException {
output.write(i);
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
try {
writeListener.onWritePossible();
} catch (IOException e) {
// Ignore
}
}
};
new StreamingBatchOperations(webServer).readAndExecuteOperations(uriInfo, httpHeaders, req, body, servletOutputStream);
representationWriteHandler.onRepresentationWritten();
} catch (Exception e) {
LOGGER.warn("Error executing batch request ", e);
} finally {
representationWriteHandler.onRepresentationFinal();
}
}
};
return Response.ok(stream).type(HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE)).build();
} catch (Exception e) {
return output.serverError(e);
}
}
Aggregations