use of javax.servlet.ServletOutputStream in project jetty.project by eclipse.
the class AsyncIOServletTest method testOtherThreadOnAllDataRead.
@Test
public void testOtherThreadOnAllDataRead() throws Exception {
String success = "SUCCESS";
start(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
assertScope();
response.flushBuffer();
AsyncContext async = request.startAsync();
async.setTimeout(0);
ServletInputStream input = request.getInputStream();
ServletOutputStream output = response.getOutputStream();
if (request.getDispatcherType() == DispatcherType.ERROR)
throw new IllegalStateException();
input.setReadListener(new ReadListener() {
@Override
public void onDataAvailable() throws IOException {
assertScope();
async.start(() -> {
assertScope();
try {
sleep(1000);
if (!input.isReady())
throw new IllegalStateException();
if (input.read() != 'X')
throw new IllegalStateException();
if (!input.isReady())
throw new IllegalStateException();
if (input.read() != -1)
throw new IllegalStateException();
} catch (IOException x) {
throw new UncheckedIOException(x);
}
});
}
@Override
public void onAllDataRead() throws IOException {
output.write(success.getBytes(StandardCharsets.UTF_8));
async.complete();
}
@Override
public void onError(Throwable t) {
assertScope();
t.printStackTrace();
async.complete();
}
});
}
});
byte[] data = "X".getBytes(StandardCharsets.UTF_8);
CountDownLatch clientLatch = new CountDownLatch(1);
DeferredContentProvider content = new DeferredContentProvider();
client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(content).timeout(5, TimeUnit.SECONDS).send(new BufferingResponseListener() {
@Override
public void onComplete(Result result) {
if (result.isSucceeded()) {
Response response = result.getResponse();
String content = getContentAsString();
if (response.getStatus() == HttpStatus.OK_200 && success.equals(content))
clientLatch.countDown();
}
}
});
sleep(100);
content.offer(ByteBuffer.wrap(data));
content.close();
assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
use of javax.servlet.ServletOutputStream in project jetty.project by eclipse.
the class AsyncIOServletTest method testOnAllDataRead.
@Test
public void testOnAllDataRead() throws Exception {
String success = "SUCCESS";
start(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
assertScope();
response.flushBuffer();
AsyncContext async = request.startAsync();
async.setTimeout(5000);
ServletInputStream in = request.getInputStream();
ServletOutputStream out = response.getOutputStream();
in.setReadListener(new ReadListener() {
@Override
public void onDataAvailable() throws IOException {
assertScope();
try {
sleep(1000);
if (!in.isReady())
throw new IllegalStateException();
if (in.read() != 'X')
throw new IllegalStateException();
if (!in.isReady())
throw new IllegalStateException();
if (in.read() != -1)
throw new IllegalStateException();
} catch (IOException x) {
throw new UncheckedIOException(x);
}
}
@Override
public void onAllDataRead() throws IOException {
assertScope();
out.write(success.getBytes(StandardCharsets.UTF_8));
async.complete();
}
@Override
public void onError(Throwable t) {
assertScope();
t.printStackTrace();
async.complete();
}
});
}
});
byte[] data = "X".getBytes(StandardCharsets.UTF_8);
CountDownLatch clientLatch = new CountDownLatch(1);
DeferredContentProvider content = new DeferredContentProvider() {
@Override
public long getLength() {
return data.length;
}
};
client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(content).timeout(5, TimeUnit.SECONDS).send(new BufferingResponseListener() {
@Override
public void onComplete(Result result) {
if (result.isSucceeded()) {
Response response = result.getResponse();
String content = getContentAsString();
if (response.getStatus() == HttpStatus.OK_200 && success.equals(content))
clientLatch.countDown();
}
}
});
sleep(100);
content.offer(ByteBuffer.wrap(data));
content.close();
assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
use of javax.servlet.ServletOutputStream in project jetty.project by eclipse.
the class AsyncIOServletTest method testCompleteBeforeOnAllDataRead.
@Test
public void testCompleteBeforeOnAllDataRead() throws Exception {
String success = "SUCCESS";
AtomicBoolean allDataRead = new AtomicBoolean(false);
start(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
assertScope();
response.flushBuffer();
AsyncContext async = request.startAsync();
ServletInputStream input = request.getInputStream();
ServletOutputStream output = response.getOutputStream();
input.setReadListener(new ReadListener() {
@Override
public void onDataAvailable() throws IOException {
assertScope();
while (input.isReady()) {
int b = input.read();
if (b < 0) {
output.write(success.getBytes(StandardCharsets.UTF_8));
async.complete();
return;
}
}
}
@Override
public void onAllDataRead() throws IOException {
assertScope();
output.write("FAILURE".getBytes(StandardCharsets.UTF_8));
allDataRead.set(true);
throw new IllegalStateException();
}
@Override
public void onError(Throwable t) {
assertScope();
t.printStackTrace();
}
});
}
});
ContentResponse response = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).header(HttpHeader.CONNECTION, "close").content(new StringContentProvider("XYZ")).timeout(5, TimeUnit.SECONDS).send();
assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
assertThat(response.getContentAsString(), Matchers.equalTo(success));
}
use of javax.servlet.ServletOutputStream in project jetty.project by eclipse.
the class HttpClientStreamTest method testInputStreamResponseListenerClosedWhileWaiting.
@Test
public void testInputStreamResponseListenerClosedWhileWaiting() throws Exception {
byte[] chunk1 = new byte[] { 0, 1 };
byte[] chunk2 = new byte[] { 2, 3 };
start(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
response.setContentLength(chunk1.length + chunk2.length);
ServletOutputStream output = response.getOutputStream();
output.write(chunk1);
output.flush();
output.write(chunk2);
}
});
CountDownLatch failedLatch = new CountDownLatch(1);
CountDownLatch contentLatch = new CountDownLatch(1);
InputStreamResponseListener listener = new InputStreamResponseListener() {
@Override
public void onContent(Response response, ByteBuffer content, Callback callback) {
super.onContent(response, content, new Callback() {
@Override
public void failed(Throwable x) {
failedLatch.countDown();
callback.failed(x);
}
});
contentLatch.countDown();
}
};
client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).send(listener);
Response response = listener.get(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
// Wait until we get some content.
Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS));
// Close the stream.
InputStream stream = listener.getInputStream();
stream.close();
// Make sure that the callback has been invoked.
Assert.assertTrue(failedLatch.await(5, TimeUnit.SECONDS));
}
use of javax.servlet.ServletOutputStream in project Openfire by igniterealtime.
the class GraphServlet method writePDFContent.
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart[] charts, Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {
try {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
writer.setPageEvent(new PDFEventListener(request));
document.open();
int index = 0;
int chapIndex = 0;
for (Statistic stat : stats) {
String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " + JiveGlobals.formatDate(new Date(endtime));
Paragraph paragraph = new Paragraph(serverName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
document.add(paragraph);
paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
document.add(paragraph);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));
document.add(chapterTitle);
// total hack: no idea what tags people are going to use in the description
// possibly recommend that we only use a <p> tag?
String[] paragraphs = stat.getDescription().split("<p>");
for (String s : paragraphs) {
Paragraph p = new Paragraph(s);
document.add(p);
}
document.add(Chunk.NEWLINE);
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(width, height);
Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
charts[index++].draw(graphs2D, rectangle2D);
graphs2D.dispose();
float x = (document.getPageSize().width() / 2) - (width / 2);
contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
document.newPage();
}
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
// the contentlength is needed for MSIE!!!
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
} catch (DocumentException e) {
Log.error("error creating PDF document: " + e.getMessage());
}
}
Aggregations