Example usage for javax.servlet ServletOutputStream ServletOutputStream

List of usage examples for javax.servlet ServletOutputStream ServletOutputStream

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream ServletOutputStream.

Prototype


protected ServletOutputStream() 

Source Link

Document

Does nothing, because this is an abstract class.

Usage

From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java

private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);/* w  w w .ja  v a2 s  .  c om*/
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http",
                "localhost", localPort, "fuse", "fuse", null);
        MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.servicecomb.foundation.vertx.http.TestStandardHttpServletResponseEx.java

@Test
public void flushBuffer() throws IOException {
    Buffer buffer = Buffer.buffer();
    ServletOutputStream output = new ServletOutputStream() {
        @Override// www  .ja  v  a  2  s  .co m
        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());
}

From source file:org.apache.sling.servlethelpers.ResponseBodySupport.java

public ServletOutputStream getOutputStream() {
    if (servletOutputStream == null) {
        servletOutputStream = new ServletOutputStream() {
            @Override//w ww .ja va  2  s. co  m
            public void write(int b) throws IOException {
                outputStream.write(b);
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
                throw new UnsupportedOperationException();
            }
        };
    }
    return servletOutputStream;
}

From source file:org.b3log.solo.processor.CaptchaProcessorTestCase.java

/**
 * get./*from w ww  .j a  va 2 s .  c o  m*/
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void get() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/captcha.do");
    when(request.getMethod()).thenReturn("GET");

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {

        private long size;

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(final WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            size++;
        }

        @Override
        public String toString() {
            return "size: " + String.valueOf(size);
        }
    });

    dispatcherServlet.service(request, response);

    Assert.assertTrue(StringUtils.startsWith(response.getOutputStream().toString(), "size: "));
}

From source file:org.datacleaner.monitor.server.controllers.ExecutionLogControllerTest.java

public void testExecutionLogXml() throws Exception {
    final HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    response.setContentType("application/xml");
    response.setCharacterEncoding("UTF-8");

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ServletOutputStream out = new ServletOutputStream() {
        @Override//from w  ww. ja  va  2s .c  o  m
        public void write(int b) throws IOException {
            baos.write(b);
        }
    };
    EasyMock.expect(response.getOutputStream()).andReturn(out);

    EasyMock.replay(response);

    executionLogController.executionLogXml("tenant1", "product_profiling-3", response);

    EasyMock.verify(response);

    String str = new String(baos.toByteArray());
    assertTrue("Got: " + str, str.indexOf("<ns3:execution-status>SUCCESS</ns3:execution-status>") != -1);
}

From source file:org.docx4j.template.jsp.engine.JspTemplateImpl.java

private void doInterpret(String requestURL, Map<String, Object> variables, OutputStream output)
        throws IOException, ServletException {
    /**//w w  w . ja v a2s .  c o  m
      * ServletContext?RequestDispatcher
      */
    ServletContext sc = request.getSession().getServletContext();
    /**
     * ???reqeustDispatcher
     */
    RequestDispatcher rd = sc.getRequestDispatcher(requestURL);
    /**
     * ByteArrayOutputStream?,??
     */
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /**
     * ServletOutputStreamwrite
     */
    final ServletOutputStream outputStream = new ServletOutputStream() {

        public void write(int b) throws IOException {
            /**
             * ?
             */
            baos.write(b);
        }

        @SuppressWarnings("unused")
        public boolean isReady() {
            return false;
        }

    };
    /**
     *  OutputStream  PrintWriter
     * OutputStreamWriter ????? charset ????
     */
    final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, config.getOutputEncoding()), true);
    /**
     * ?HttpServletResponse??response
     */
    HttpServletResponse resp = new HttpServletResponseWrapper(response) {
        /**
         * getOutputStream(ServletResponse)ServletOutputStream
         * ?response
         * ?byteArrayOutputStream
         */
        public ServletOutputStream getOutputStream() {
            return outputStream;
        }

        /**
         * ?getWriter(ServletResponse)PrintWriter
         * ???
         */
        public PrintWriter getWriter() {
            return pw;
        }
    };
    /**
     * ?jsp RequestDispatcher.include(ServletRequest request,
     * ServletResponse response) RequestDispatcher??response
     */
    rd.include(request, resp);
    pw.flush();
    /**
     * ByteArrayOutputStreamwriteTo?????ByteArray
     */
    baos.writeTo(output);
}

From source file:org.iqvis.nvolv3.request.filter.ResponseWrapper.java

@Override
public ServletOutputStream getOutputStream() throws IOException {
    return new ServletOutputStream() {
        private TeeOutputStream tee = new TeeOutputStream(ResponseWrapper.super.getOutputStream(), bos);

        @Override/*  w ww.j a  v a2 s . c om*/
        public void write(int b) throws IOException {
            tee.write(b);
        }

        @Override
        public boolean isReady() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public void setWriteListener(WriteListener arg0) {
            // TODO Auto-generated method stub

        }
    };
}

From source file:org.neo4j.server.rest.dbms.AuthorizationFilterTest.java

@Before
public void setUp() throws Exception {
    when(servletResponse.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override// ww  w  .ja v a  2s  .c om
        public void write(int b) throws IOException {
            outputStream.write(b);
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
            throw new UnsupportedOperationException();
        }
    });
}

From source file:org.nuxeo.ecm.core.io.download.TestDownloadService.java

@Test
public void testBasicDownload() throws Exception {
    // blob to download
    String blobValue = "Hello World";
    Blob blob = Blobs.createBlob(blobValue);
    blob.setFilename("myFile.txt");
    blob.setDigest("12345");

    // prepare mocks
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn("GET");

    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletOutputStream sos = new ServletOutputStream() {
        @Override// w w  w  . j a v a  2 s .com
        public void write(int b) throws IOException {
            out.write(b);
        }
    };
    PrintWriter printWriter = new PrintWriter(sos);
    when(response.getOutputStream()).thenReturn(sos);
    when(response.getWriter()).thenReturn(printWriter);

    // send download request
    downloadService.downloadBlob(request, response, null, null, blob, null, null);

    // check that the blob gets returned
    assertEquals(blobValue, out.toString());
}

From source file:org.nuxeo.ecm.core.io.download.TestDownloadService.java

protected void doTestETagHeader(Boolean match) throws Exception {
    // Given a blob
    String blobValue = "Hello World";
    Blob blob = Blobs.createBlob(blobValue);
    blob.setFilename("myFile.txt");
    blob.setDigest("12345");

    String digestToTest;//from   www.j  a  v  a 2s  . c  o m
    if (match == null) {
        digestToTest = null;
    } else if (TRUE.equals(match)) {
        digestToTest = "12345";
    } else {
        digestToTest = "78787";
    }

    // When I send a request a given digest
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpServletRequest req = mock(HttpServletRequest.class);
    when(req.getHeader("If-None-Match")).thenReturn('"' + digestToTest + '"');
    when(req.getMethod()).thenReturn("GET");

    HttpServletResponse resp = mock(HttpServletResponse.class);
    ServletOutputStream sos = new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            out.write(b);
        }
    };
    @SuppressWarnings("resource")
    PrintWriter printWriter = new PrintWriter(sos);
    when(resp.getOutputStream()).thenReturn(sos);
    when(resp.getWriter()).thenReturn(printWriter);

    downloadService.downloadBlob(req, resp, null, null, blob, null, null);

    verify(req, atLeast(1)).getHeader("If-None-Match");

    // Then the response differs if the digest match
    if (TRUE.equals(match)) {
        assertEquals(0, out.toByteArray().length);
        verify(resp).sendError(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        assertEquals(blobValue, out.toString());
        verify(resp).setHeader("ETag", '"' + blob.getDigest() + '"');
    }
}