Search in sources :

Example 36 with ServletOutputStream

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));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) UncheckedIOException(java.io.UncheckedIOException) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 37 with ServletOutputStream

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));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) UncheckedIOException(java.io.UncheckedIOException) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 38 with ServletOutputStream

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));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletInputStream(javax.servlet.ServletInputStream) Test(org.junit.Test)

Example 39 with ServletOutputStream

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));
}
Also used : InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) ServletOutputStream(javax.servlet.ServletOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Callback(org.eclipse.jetty.util.Callback) Test(org.junit.Test)

Example 40 with ServletOutputStream

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());
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) ServletOutputStream(javax.servlet.ServletOutputStream) Rectangle2D(java.awt.geom.Rectangle2D) DefaultFontMapper(com.lowagie.text.pdf.DefaultFontMapper) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) PdfTemplate(com.lowagie.text.pdf.PdfTemplate) Date(java.util.Date) Paragraph(com.lowagie.text.Paragraph) Graphics2D(java.awt.Graphics2D) Statistic(org.jivesoftware.openfire.stats.Statistic) DocumentException(com.lowagie.text.DocumentException) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Aggregations

ServletOutputStream (javax.servlet.ServletOutputStream)515 IOException (java.io.IOException)211 HttpServletResponse (javax.servlet.http.HttpServletResponse)148 Test (org.junit.Test)112 HttpServletRequest (javax.servlet.http.HttpServletRequest)108 ServletException (javax.servlet.ServletException)90 InputStream (java.io.InputStream)63 File (java.io.File)57 ByteArrayOutputStream (java.io.ByteArrayOutputStream)40 FileInputStream (java.io.FileInputStream)40 PrintWriter (java.io.PrintWriter)27 CountDownLatch (java.util.concurrent.CountDownLatch)27 WriteListener (javax.servlet.WriteListener)27 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)27 HttpServlet (javax.servlet.http.HttpServlet)25 AsyncContext (javax.servlet.AsyncContext)23 ServletInputStream (javax.servlet.ServletInputStream)23 ArrayList (java.util.ArrayList)21 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)20 ByteArrayInputStream (java.io.ByteArrayInputStream)19