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.sakaiproject.kernel.rest.test.RestMySitesProviderKernelUnitT.java

@Test
public void testUserWithEnv() throws ServletException, IOException, JCRNodeFactoryServiceException,
        LoginException, RepositoryException {

    KernelManager km = new KernelManager();
    SessionManagerService sessionManagerService = km.getService(SessionManagerService.class);
    CacheManagerService cacheManagerService = km.getService(CacheManagerService.class);
    UserResolverService userResolverService = km.getService(UserResolverService.class);
    AuthzResolverService authzResolverService = km.getService(AuthzResolverService.class);
    JCRService jcrService = km.getService(JCRService.class);
    // bypass security
    authzResolverService.setRequestGrant("Populating Test JSON");

    // login to the repo with super admin
    SakaiJCRCredentials credentials = new SakaiJCRCredentials();
    Session jsession = jcrService.getRepository().login(credentials);
    jcrService.setSession(jsession);/*  w w w.  j  av a  2 s. c  om*/

    // setup the user environment for the admin user.
    /*
     * for (String userName : USERS) { String prefix =
     * PathUtils.getUserPrefix(userName); String userEnvironmentPath =
     * "/userenv" + prefix + "userenv";
     *
     * LOG.info("Saving "+userEnvironmentPath);
     * jcrNodeFactoryService.createFile(userEnvironmentPath); InputStream in =
     * ResourceLoader.openResource(USERBASE + userName + ".json",
     * RestMySitesProviderTest.class.getClassLoader());
     * jcrNodeFactoryService.setInputStream(userEnvironmentPath, in);
     * jsession.save(); in.close(); }
     */

    LOG.info("Getting RestMySitesProvider using key: " + RestMySitesProvider.SITES_ELEMENT);
    RegistryService registryService = km.getService(RegistryService.class);
    Registry<String, RestProvider> registry = registryService.getRegistry(RestProvider.REST_REGISTRY);
    RestMySitesProvider rmsp = (RestMySitesProvider) registry.getMap().get(RestMySitesProvider.SITES_ELEMENT);
    for (String key : registry.getMap().keySet()) {
        LOG.info(key + "--->" + registry.getMap().get(key));
    }
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);
    HttpSession session = createMock(HttpSession.class);

    Assert.assertNotNull(rmsp);

    expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();

    expect(request.getSession(true)).andReturn(session).anyTimes();
    expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
    expect(session.getAttribute("_u")).andReturn(new InternalUser("ib236")).anyTimes();
    expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
    expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
    expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
    expect(request.getParameter(RestMySitesProvider.INPUT_PARAM_NAME_STARTINDEX)).andReturn(null).anyTimes();
    expect(request.getParameter(RestMySitesProvider.INPUT_PARAM_NAME_COUNT)).andReturn(null).anyTimes();
    expect(request.getRequestedSessionId()).andReturn("sessionId").anyTimes();

    Cookie c = new Cookie("JSESSIONID", "sessionId");

    expect(request.getCookies()).andReturn(new Cookie[] { c }).anyTimes();
    expect(session.getId()).andReturn("sessionId").anyTimes();
    response.addCookie((Cookie) anyObject());
    expectLastCall().atLeastOnce();
    response.setContentType(RestProvider.CONTENT_TYPE);
    expectLastCall().atLeastOnce();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

    });
    expectLastCall().atLeastOnce();
    replay(request, response, session);

    SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request, response, userResolverService,
            sessionManagerService);
    sessionManagerService.bindRequest(sakaiServletRequest);

    LOG.info("Dispatching to provider... /rest/" + RestMySitesProvider.SITES_ELEMENT);
    rmsp.dispatch(new String[] { RestMySitesProvider.SITES_ELEMENT }, request, response);

    String responseString = new String(baos.toByteArray(), "UTF-8");
    LOG.info("Response was " + responseString);
    // FIXME: My sites works differently at the moment.    assertTrue(responseString.indexOf("\"entry\"") > 0);

    cacheManagerService.unbind(CacheScope.REQUEST);
    verify(request, response, session);

}

From source file:org.sakaiproject.kernel.rest.test.RestUserProviderKernelUnitT.java

@Test
public void testNewUser() throws ServletException, IOException {
    KernelManager km = new KernelManager();
    SessionManagerService sessionManagerService = km.getService(SessionManagerService.class);
    CacheManagerService cacheManagerService = km.getService(CacheManagerService.class);
    UserResolverService userResolverService = km.getService(UserResolverService.class);

    RegistryService registryService = km.getService(RegistryService.class);
    Registry<String, RestProvider> registry = registryService.getRegistry(RestProvider.REST_REGISTRY);
    RestUserProvider rup = (RestUserProvider) registry.getMap().get("user");

    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);
    HttpSession session = createMock(HttpSession.class);

    expect(request.getMethod()).andReturn("POST").anyTimes();

    expect(request.getParameter("firstName")).andReturn("Ian").atLeastOnce();
    expect(request.getParameter("lastName")).andReturn("Ian").atLeastOnce();
    expect(request.getParameter("email")).andReturn("ian@sakai.org").atLeastOnce();
    expect(request.getParameter("eid")).andReturn("ib236").atLeastOnce();
    expect(request.getParameter("password")).andReturn("password").atLeastOnce();
    expect(request.getParameter("userType")).andReturn("student").atLeastOnce();

    response.setContentType("text/plain");
    expectLastCall().atLeastOnce();/*from w w w  .  ja  v  a 2s.  co m*/

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ServletOutputStream out = new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

    };
    expect(response.getOutputStream()).andReturn(out).anyTimes();

    expect(request.getRemoteUser()).andReturn(null).anyTimes();
    expect(request.getRequestedSessionId()).andReturn("SESSIONID-123-1").anyTimes();
    expect(session.getId()).andReturn("SESSIONID-123-1").anyTimes();
    Cookie cookie = new Cookie("SAKAIID", "SESSIONID-123-1");
    expect(request.getCookies()).andReturn(new Cookie[] { cookie }).anyTimes();

    expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
    expect(request.getSession(true)).andReturn(session).anyTimes();
    expect(request.getSession(false)).andReturn(session).anyTimes();
    expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
    expect(session.getAttribute("_u")).andReturn(null).anyTimes();
    expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
    expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
    expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
    response.addCookie((Cookie) anyObject());
    expectLastCall().anyTimes();

    replay(request, response, session);

    SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request, response, userResolverService,
            sessionManagerService);
    sessionManagerService.bindRequest(sakaiServletRequest);

    rup.dispatch(new String[] { "user", "new" }, request, response);

    String respBody = new String(baos.toByteArray(), "UTF-8");
    System.err.println("Response Was " + respBody);
    assertTrue(respBody.indexOf("uuid") > 0);
    assertTrue(respBody.indexOf("OK") > 0);

    cacheManagerService.unbind(CacheScope.REQUEST);
    verify(request, response, session);

}

From source file:org.sakaiproject.nakamura.http.i18n.I18nFilterTest.java

@Test
public void filterMatchedPathFailToOutputStream() throws Exception {
    when(request.getPathInfo()).thenReturn("/dev/index.html");

    // inject some data into the response for the filter to use
    writeToResponse("__MSG__REPLACE_ME__", true);

    // throw an exception when getting the writer so that an attempt is made to get the
    // output stream
    reset(response);/*  w  w w .  j a va2s . co  m*/
    when(response.getWriter()).thenThrow(new IllegalStateException());
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public void write(int arg0) throws IOException {
            baos.write(arg0);
        }
    });

    filter.doFilter(request, response, chain);

    ArgumentCaptor<ServletResponse> acResponse = ArgumentCaptor.forClass(ServletResponse.class);
    verify(chain).doFilter(eq(request), acResponse.capture());
    verify(response, atLeastOnce()).getWriter();

    assertTrue(acResponse.getValue() instanceof CapturingHttpServletResponse);
    String output = sw.toString();
    assertTrue(StringUtils.isBlank(output));

    output = baos.toString("UTF-8");
    assertFalse(StringUtils.isBlank(output));
    assertFalse(output.contains("__MSG__REPLACE_ME__"));
    assertTrue(output.contains("Yay, In the language bundle!"));
}

From source file:org.siphon.servlet.DummyHttpServletResponse.java

public ServletOutputStream getOutputStream() throws IOException {
    return new ServletOutputStream() {

        @Override//from  www  .j  av a 2  s  .  c o  m
        public void write(int b) throws IOException {
            os.write(b);
        }

        public void flush() throws IOException {
            os.flush();
        }

        @Override
        public void close() throws IOException {
            super.close();
        }

        @Override
        public void setWriteListener(WriteListener arg0) {
        }

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

From source file:org.springframework.web.servlet.support.ResponseIncludeWrapper.java

/**
 * Return a printwriter, throws and exception if a OutputStream already
 * been returned.//ww  w  .j a  va 2s. c o m
 *
 * @return a PrintWriter object
 * @throws java.io.IOException if the outputstream already been called
 */
@Override
public PrintWriter getWriter() throws java.io.IOException {
    if (buffer == null) {
        if (captureBuffer == null) {

            captureBuffer = new StreamByteBuffer();
            captureOutputStream = captureBuffer.getOutputStream();

            sos = new ServletOutputStream() {
                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setWriteListener(WriteListener writeListener) {

                }

                @Override
                public void write(int b) throws IOException {
                    captureOutputStream.write(b);
                }
            };
            setCharacterEncoding(getCharacterEncoding());
            printWriter = new PrintWriter(new OutputStreamWriter(sos, getCharacterEncoding()));
        }
        return printWriter;
    }
    throw new IllegalStateException();
}

From source file:org.springframework.web.servlet.support.ResponseIncludeWrapper.java

/**
 * Return a OutputStream, throws and exception if a printwriter already
 * been returned./*from   w w  w  . j  a  v  a 2s  . c  o m*/
 *
 * @return a OutputStream object
 * @throws java.io.IOException if the printwriter already been called
 */
@Override
public ServletOutputStream getOutputStream() throws java.io.IOException {
    if (captureBuffer == null) {
        if (buffer == null) {
            buffer = new StreamByteBuffer();
            outputStream = buffer.getOutputStream();

            sos = new ServletOutputStream() {
                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setWriteListener(WriteListener writeListener) {

                }

                @Override
                public void write(int b) throws IOException {
                    outputStream.write(b);
                }
            };
        }
        return sos;
    }
    throw new IllegalStateException();
}

From source file:org.teiid.olingo.web.gzip.TestGzipMessageResponse.java

@Before
public void prepareResponse() throws IOException {
    streamBytes = new LinkedList<>();
    stream = new ServletOutputStream() {
        @Override/*from w  w w .  j a v a2s  . c  om*/
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            streamBytes.add((byte) b);
        }
    };
    response = new GzipMessageResponse(mockResponse(stream));
}

From source file:org.wings.recorder.Recorder.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    try {/*from w  ww . ja  v a2 s  .  c o  m*/
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            Map map = servletRequest.getParameterMap();
            if (map.containsKey(RECORDER_SCRIPT)) {
                log.info("recorder_script " + map.get(RECORDER_SCRIPT));
                String[] values = (String[]) map.get(RECORDER_SCRIPT);
                scriptName = values[0];
            }
            if (map.containsKey(RECORDER_START)) {
                if (list != null)
                    return;
                log.info(RECORDER_START);
                list = new LinkedList();
            } else if (map.containsKey(RECORDER_STOP)) {
                if (list == null)
                    return;
                log.info(RECORDER_STOP);
                writeCode();
                list = null;
            } else if (list != null) {
                String resource = httpServletRequest.getPathInfo();
                log.debug("PATH_INFO: " + resource);

                Request record;
                if ("GET".equalsIgnoreCase(httpServletRequest.getMethod()))
                    record = new GET(resource);
                else
                    record = new POST(resource);

                Enumeration parameterNames = httpServletRequest.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String name = (String) parameterNames.nextElement();
                    String[] values = httpServletRequest.getParameterValues(name);
                    addEvent(record, name, values);
                }
                Enumeration headerNames = httpServletRequest.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String name = (String) headerNames.nextElement();
                    if (name.equalsIgnoreCase("cookie") || name.equalsIgnoreCase("referer"))
                        continue;
                    addHeader(record, name, httpServletRequest.getHeader(name));
                }
                list.add(record);
            }
        }
    } finally {
        if (servletResponse instanceof HttpServletResponse) {
            filterChain.doFilter(servletRequest,
                    new HttpServletResponseWrapper((HttpServletResponse) servletResponse) {
                        public ServletOutputStream getOutputStream() throws IOException {
                            final ServletOutputStream out = super.getOutputStream();
                            return new ServletOutputStream() {
                                public void write(int b) throws IOException {
                                    out.write(b);
                                }

                                public void close() throws IOException {
                                    super.println("<hr/><div align=\"center\">");
                                    super.println("<form method=\"get\" action=\"\">");
                                    super.println("<input type=\"text\" name=\"recorder_script\" value=\""
                                            + scriptName + "\">");
                                    super.println(
                                            "<input type=\"submit\" name=\"recorder_start\" value=\"start\">");
                                    super.println(
                                            "<input type=\"submit\" name=\"recorder_stop\" value=\"stop\">");
                                    super.println("</div></form>");
                                    super.close();
                                }
                            };
                        }
                    });
        } else
            filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ProtocolServiceTest.java

@SuppressWarnings("unchecked")
@Test// ww w. j  av  a 2  s  .  co m
public void testOpenSaml2Spike() throws Exception {
    /*
     * Setup
     */
    DefaultBootstrap.bootstrap();

    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
    assertNotNull(builderFactory);

    SAMLObjectBuilder<AuthnRequest> requestBuilder = (SAMLObjectBuilder<AuthnRequest>) builderFactory
            .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    assertNotNull(requestBuilder);
    AuthnRequest samlMessage = requestBuilder.buildObject();
    samlMessage.setID(UUID.randomUUID().toString());
    samlMessage.setVersion(SAMLVersion.VERSION_20);
    samlMessage.setIssueInstant(new DateTime(0));

    SAMLObjectBuilder<Endpoint> endpointBuilder = (SAMLObjectBuilder<Endpoint>) builderFactory
            .getBuilder(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    Endpoint samlEndpoint = endpointBuilder.buildObject();
    samlEndpoint.setLocation("http://idp.be");
    samlEndpoint.setResponseLocation("http://sp.be/response");

    HttpServletResponse mockHttpServletResponse = EasyMock.createMock(HttpServletResponse.class);
    OutTransport outTransport = new HttpServletResponseAdapter(mockHttpServletResponse, true);

    BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();
    messageContext.setOutboundMessageTransport(outTransport);
    messageContext.setPeerEntityEndpoint(samlEndpoint);
    messageContext.setOutboundSAMLMessage(samlMessage);

    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    velocityEngine.init();
    HTTPPostEncoder encoder = new HTTPPostEncoder(velocityEngine, "/templates/saml2-post-binding.vm");

    /*
     * Expectations
     */
    mockHttpServletResponse.setHeader("Cache-control", "no-cache, no-store");
    mockHttpServletResponse.setHeader("Pragma", "no-cache");
    mockHttpServletResponse.setCharacterEncoding("UTF-8");
    mockHttpServletResponse.setContentType("text/html");
    mockHttpServletResponse.setHeader("Content-Type", "text/html");
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ServletOutputStream mockServletOutputStream = new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }
    };
    EasyMock.expect(mockHttpServletResponse.getOutputStream()).andReturn(mockServletOutputStream);

    /*
     * Perform
     */
    EasyMock.replay(mockHttpServletResponse);
    encoder.encode(messageContext);

    /*
     * Verify
     */
    EasyMock.verify(mockHttpServletResponse);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray());
    LOG.debug("SAML2 Request Browser POST: " + baos.toString());
    // JTidy comes with an outdated W3C DOM implementation. Cannot use it
    // anymore.
    // Tidy tidy = new Tidy();
    // Document document = tidy.parseDOM(byteArrayInputStream, null);

    // Node actionNode = XPathAPI.selectSingleNode(document,
    // "//form[@action='http&#x3a;&#x2f;&#x2f;idp.be']");
    // assertNotNull(actionNode);
}

From source file:uk.co.tfd.sm.proxy.ProxyServletVivoMan.java

@Test
public void testVivoFeed() throws Exception {

    when(request.getPathInfo()).thenReturn("/tests/vivo");
    when(request.getHeaderNames()).thenReturn(headerNames.elements());

    Map<String, String[]> requestParameters = ImmutableMap.of("id", new String[] { "n7934" });
    when(request.getParameterMap()).thenReturn(requestParameters);
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {

        @Override/*from w ww. ja v a2 s  .c o  m*/
        public void write(int v) throws IOException {
            byteArrayOutputStream.write(v);
        }
    });

    long s = System.currentTimeMillis();
    servlet.service(request, response);
    LOGGER.info("Took {} ", (System.currentTimeMillis() - s));

    verify(response, Mockito.atMost(0)).sendError(404);

    String output = byteArrayOutputStream.toString("UTF-8");
    LOGGER.info("Got Response {} ", output);
}