Example usage for org.springframework.mock.web MockHttpServletResponse getContentAsByteArray

List of usage examples for org.springframework.mock.web MockHttpServletResponse getContentAsByteArray

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getContentAsByteArray.

Prototype

public byte[] getContentAsByteArray() 

Source Link

Usage

From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java

/**
 * Mimic workflow when cached portlet data using "validation" method is available.
 * //from   w  w w  .j a v  a2 s.  c  om
 * @throws PortletContainerException 
 * @throws IOException 
 * @throws PortletException 
 */
@Test
public void doServeResourceCachedContentValidationMethodTest()
        throws PortletException, IOException, PortletContainerException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    Date now = new Date();
    CacheControlImpl cacheControl = new CacheControlImpl();
    cacheControl.setUseCachedContent(true);
    cacheControl.setExpirationTime(300);
    cacheControl.setETag("123456");
    CachedPortletData cachedPortletData = new CachedPortletData();
    cachedPortletData.setContentType("application/json");
    byte[] content = "{ \"hello\": \"world\" }".getBytes();
    cachedPortletData.setByteData(content);
    cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime());
    cachedPortletData.setEtag("123456");
    cachedPortletData.setTimeStored(now);

    setupPortletExecutionMocks(request);

    when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response))
            .thenReturn(cacheControl);
    when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request))
            .thenReturn(cachedPortletData);

    portletRenderer.doServeResource(portletWindowId, request, response);
    // verify content matches what was in cache (no array support in Assert.assertEquals, check byte for byte)
    byte[] fromResponse = response.getContentAsByteArray();
    Assert.assertEquals(content.length, fromResponse.length);
    for (int i = 0; i < content.length; i++) {
        Assert.assertEquals(content[i], fromResponse[i]);
    }
    Assert.assertEquals(200, response.getStatus());
    // verify we enter the first branch and never execute portletContainer#doServeResource
    verify(portletContainer, never()).doServeResource(isA(PortletWindow.class),
            isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class));
    // verify we never enter the other branch of the "should render cached output" if statement
    verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class));
}

From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java

/**
 * Same as {@link #doServeResourceCachedContentValidationMethodTest()}, but simulate browser
 * sending If-None-Match header with mismatched etag. Response is 200 with content and new etag
 * //ww w  .  j a  va  2  s. c  o m
 * @throws PortletException
 * @throws IOException
 * @throws PortletContainerException
 */
@Test
public void doServeResourceCachedContentValidationMethodIfNoneMatchInvalidTest()
        throws PortletException, IOException, PortletContainerException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader("If-None-Match", "123456");
    MockHttpServletResponse response = new MockHttpServletResponse();
    Date now = new Date();
    CacheControlImpl cacheControl = new CacheControlImpl();
    cacheControl.setUseCachedContent(true);
    cacheControl.setExpirationTime(300);
    cacheControl.setETag("123457");
    CachedPortletData cachedPortletData = new CachedPortletData();
    cachedPortletData.setContentType("application/json");
    byte[] content = "{ \"hello\": \"world\" }".getBytes();
    cachedPortletData.setByteData(content);
    cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime());
    cachedPortletData.setEtag("123457");
    cachedPortletData.setTimeStored(now);

    setupPortletExecutionMocks(request);

    when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response))
            .thenReturn(cacheControl);
    when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request))
            .thenReturn(cachedPortletData);

    portletRenderer.doServeResource(portletWindowId, request, response);
    // verify content matches what was in cache (no array support in Assert.assertEquals, check byte for byte)
    byte[] fromResponse = response.getContentAsByteArray();
    Assert.assertEquals(content.length, fromResponse.length);
    for (int i = 0; i < content.length; i++) {
        Assert.assertEquals(content[i], fromResponse[i]);
    }
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("123457", response.getHeader("ETag"));
    // verify we enter the first branch and never execute portletContainer#doServeResource
    verify(portletContainer, never()).doServeResource(isA(PortletWindow.class),
            isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class));
    // verify we never enter the other branch of the "should render cached output" if statement
    verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class));
}

From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java

/**
 * Verify headers stored in cache are replayed on the response for cached doServeResource content.
 * /*from  www.  ja  v  a2 s  .  c  o  m*/
 * @throws PortletContainerException 
 * @throws IOException 
 * @throws PortletException 
 */
@Test
public void doServeResourceCachedContentReplayHeadersTest()
        throws PortletException, IOException, PortletContainerException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    Date now = new Date();
    CacheControlImpl cacheControl = new CacheControlImpl();
    cacheControl.setUseCachedContent(true);
    cacheControl.setExpirationTime(300);
    CachedPortletData cachedPortletData = new CachedPortletData();
    cachedPortletData.setContentType("application/json");
    byte[] content = "{ \"hello\": \"world\" }".getBytes();
    Map<String, List<Object>> headers = ImmutableMap.<String, List<Object>>of("header1",
            Arrays.<Object>asList("value1"), "header2", Arrays.<Object>asList("value2", "value3"));

    cachedPortletData.setHeaders(headers);
    cachedPortletData.setByteData(content);
    cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime());
    cachedPortletData.setTimeStored(now);

    setupPortletExecutionMocks(request);

    when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response))
            .thenReturn(cacheControl);
    when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request))
            .thenReturn(cachedPortletData);

    portletRenderer.doServeResource(portletWindowId, request, response);
    // verify content matches what was in cache (no array support in Assert.assertEquals, check byte for byte)
    byte[] fromResponse = response.getContentAsByteArray();
    Assert.assertEquals(content.length, fromResponse.length);
    for (int i = 0; i < content.length; i++) {
        Assert.assertEquals(content[i], fromResponse[i]);
    }
    Assert.assertEquals("value1", response.getHeader("header1"));
    Assert.assertEquals(Arrays.asList(new String[] { "value2", "value3" }), response.getHeaders("header2"));
    // verify we enter the first branch and never execute portletContainer#doServeResource
    verify(portletContainer, never()).doServeResource(isA(PortletWindow.class),
            isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class));
    // verify we never enter the other branch of the "should render cached output" if statement
    verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class));
}

From source file:org.kuali.mobility.shared.controllers.FileControllerTest.java

@Test
public void testGetFile() {
    String viewName;/*ww w  .j  a v a 2  s .  co m*/
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    MockHttpServletResponse response = new MockHttpServletResponse();
    try {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME);

        MockMultipartFile mockFile = new MockMultipartFile(FORM_FILE_NAME, FILE_NAME, CONTENT_TYPE, in);

        File file = new File(mockFile);

        when(getFileService().findFileById(file.getId())).thenReturn(file);

        getController().getFile(file.getId(), request, response);

        assertTrue("Content type of response is not text/plain.",
                CONTENT_TYPE.equals(response.getContentType()));
        assertTrue("Response content length does not match file length.",
                file.getFileSize() == response.getContentLength());
        String responseText = IOUtils.toString(response.getContentAsByteArray(), CONTENT_ENCODING);

        String fileContent = IOUtils.toString(file.getBytes(), CONTENT_ENCODING);
        assertTrue("Response content does not match file content.", fileContent.equals(responseText));

    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage(), ioe);
        fail("Could not get file because of an IOException.");
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage(), e);
        fail("Could not get file because of an Exception.");
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.ClobDatatypeStorageControllerTest.java

@Test
public void shouldReturnClobDataAsFileByUuid() throws Exception {
    ClobDatatypeStorage clob = datatypeService
            .getClobDatatypeStorageByUuid(RestTestConstants1_9.CLOBDATATYPESTORAGE_RESOURCE_UUID);

    Assert.assertNotNull(clob);/*from w  w w  .j a  v  a  2  s.c  om*/
    int size = clob.getValue().getBytes().length;
    MockHttpServletResponse response = handle(
            newGetRequest(getURI() + "/" + RestTestConstants1_9.CLOBDATATYPESTORAGE_RESOURCE_UUID));

    Assert.assertEquals(size, response.getContentAsByteArray().length);
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

protected <T> T getJsonObject(ObjectMapper mapper, String url, Map<String, String> parameterMap,
        int expectedStatus, Class<T> expectedClass) throws Exception {
    MockHttpServletRequest request = createRequest(servletContext, GET, url, parameterMap, getUser(),
            getUserRoles());/*  www.  j  ava2  s  . c om*/
    MockHttpServletResponse response = createResponse();
    request.addHeader(ACCEPT, MediaType.APPLICATION_JSON);
    dispatch(request, response);
    assertEquals(expectedStatus, response.getStatus());

    System.err.printf("json: %s%n", response.getContentAsString());

    InputStream in = new ByteArrayInputStream(response.getContentAsByteArray());

    return mapper.readValue(in, expectedClass);
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

protected <T> T getXmlObject(JAXBContext context, String url, Map<String, String> parameterMap,
        int expectedStatus, Class<T> expectedClass) throws Exception {
    MockHttpServletRequest request = createRequest(servletContext, GET, url, parameterMap, getUser(),
            getUserRoles());/*from   w w  w.  j  a v  a  2  s  .  c  o  m*/
    MockHttpServletResponse response = createResponse();
    request.addHeader(ACCEPT, MediaType.APPLICATION_XML);
    dispatch(request, response);
    assertEquals(expectedStatus, response.getStatus());

    System.err.printf("xml: %s%n", response.getContentAsString());

    InputStream in = new ByteArrayInputStream(response.getContentAsByteArray());

    Unmarshaller unmarshaller = context.createUnmarshaller();

    T result = expectedClass.cast(unmarshaller.unmarshal(in));
    return result;
}

From source file:org.osaf.cosmo.BaseMockServletTestCase.java

/**
 *//*w  w w.j a v  a2 s  . c o  m*/
protected Document readXmlResponse(MockHttpServletResponse response) throws Exception {
    ByteArrayInputStream in = new ByteArrayInputStream(response.getContentAsByteArray());
    BUILDER_FACTORY.setNamespaceAware(true);
    return BUILDER_FACTORY.newDocumentBuilder().parse(in);
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.test.XSLTEntityHandlerTest.java

public void xtestRTF() throws Exception {
    String transform = "/uk/ac/cam/caret/sakai/rwiki/component/service/impl/xhtml2fo.xslt";
    StringBuffer sb = new StringBuffer();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream(testinputhtml)));
    String line = reader.readLine();
    while (line != null) {
        sb.append(line).append("\n");
        line = reader.readLine();//from  ww w .j a v a 2s  . c om
    }

    RWikiCurrentObjectImpl rwco = new RWikiCurrentObjectImpl();
    RWikiEntity rwe = new RWikiEntityImpl(rwco);
    rwco.setContent(sb.toString());
    rwco.setGroupAdmin(false);
    rwco.setId("/site/sdf-sdf-sdf-sdf-sdf-sfd/SomePage/sdfgsfd/Home");
    rwco.setId("/site/sdf-sdf-sdf-sdf-sdf-sfd/SomePage/sdfgsfd/Home");
    rwco.setOwner("The Owner");
    rwco.setUser("The User");
    rwco.setVersion(new Date());
    rwco.setRevision(Integer.valueOf(5));

    MockHttpServletRequest request = new MockHttpServletRequest();

    XSLTEntityHandler xeh = new XSLTEntityHandler();
    xeh.setAccessURLStart("/wiki/");
    xeh.setAnchorLinkFormat("/wiki{0}.html#{1}");
    xeh.setXslt(transform);
    xeh.setMinorType("rtf");
    xeh.setDefaultStackTrace("Failed To generate Stack Trace : {0}");
    xeh.setErrorFormat("Error encounvered performing transform : {0} \n {1}");
    xeh.setAuthZPrefix("/wiki");
    xeh.setAnchorLinkFormat("/wiki{0}.html#{1}");
    xeh.setStandardLinkFormat("/wiki{0}.html");
    xeh.setHrefTagFormat("<a href=\"{0}\" >{1}</a>");
    xeh.setAccessURLStart("/wiki/");
    xeh.setFeedFormat(
            "<a href=\"{0}rtf\" target=\"feeds\"><img src=\"/library/image/sakai/rtf.gif\" border=\"0\"  alt=\"RTF\" /></a>");
    HashMap responseHeaders = new HashMap();
    responseHeaders.put("content-type", "text/rtf");
    xeh.setResponseHeaders(responseHeaders);
    HashMap outputProperties = new HashMap();
    outputProperties.put("{http://xml.apache.org/xalan}content-handler",
            "uk.ac.cam.caret.sakai.rwiki.component.service.impl.FOP2RTFSerializer");
    xeh.setOutputProperties(outputProperties);

    MockHttpServletResponse response = new MockHttpServletResponse();
    xeh.init();
    xeh.outputContent(rwe, rwe, request, response);
    File f = new File("testoutput.rtf");
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(response.getContentAsByteArray());
    fo.close();

    long start = System.currentTimeMillis();
    int iters = 10;
    for (int j = 0; j < iters; j++) {
        response = new MockHttpServletResponse();
        xeh.outputContent(rwe, rwe, request, response);
    }
    float timet = (float) 1.0 * (System.currentTimeMillis() - start);
    float tper = (float) (timet / (1.0 * iters));
    logger.info("Transform and Serialize Call Cost = " + tper + " ms");

}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.test.XSLTEntityHandlerTest.java

public void xtestPDF() throws Exception {
    String transform = "/uk/ac/cam/caret/sakai/rwiki/component/service/impl/xhtml2fo.xslt";
    StringBuffer sb = new StringBuffer();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream(testinputhtml)));
    String line = reader.readLine();
    while (line != null) {
        sb.append(line).append("\n");
        line = reader.readLine();/*from  ww w  .ja v  a2  s.  c  o  m*/
    }

    RWikiCurrentObjectImpl rwco = new RWikiCurrentObjectImpl();
    RWikiEntity rwe = new RWikiEntityImpl(rwco);
    rwco.setContent(sb.toString());
    rwco.setGroupAdmin(false);
    rwco.setId("/site/sdf-sdf-sdf-sdf-sdf-sfd/SomePage/sdfgsfd/Home");
    rwco.setId("/site/sdf-sdf-sdf-sdf-sdf-sfd/SomePage/sdfgsfd/Home");
    rwco.setOwner("The Owner");
    rwco.setUser("The User");
    rwco.setVersion(new Date());
    rwco.setRevision(Integer.valueOf(5));

    MockHttpServletRequest request = new MockHttpServletRequest();

    XSLTEntityHandler xeh = new XSLTEntityHandler();
    xeh.setAccessURLStart("/wiki/");
    xeh.setAnchorLinkFormat("/wiki{0}.html#{1}");
    xeh.setXslt(transform);
    xeh.setMinorType("pdf");
    xeh.setDefaultStackTrace("Failed To generate Stack Trace : {0}");
    xeh.setErrorFormat("Error encounvered performing transform : {0} \n {1}");
    xeh.setAuthZPrefix("/wiki");
    xeh.setAnchorLinkFormat("/wiki{0}.html#{1}");
    xeh.setStandardLinkFormat("/wiki{0}.html");
    xeh.setHrefTagFormat("<a href=\"{0}\" >{1}</a>");
    xeh.setAccessURLStart("/wiki/");
    xeh.setFeedFormat(
            "<a href=\"{0}pdf\" target=\"feeds\"><img src=\"/library/image/sakai/pdf.gif\" border=\"0\"  alt=\"PDF\" /></a>");
    HashMap responseHeaders = new HashMap();
    responseHeaders.put("content-type", "application/pdf");
    xeh.setResponseHeaders(responseHeaders);
    HashMap outputProperties = new HashMap();
    outputProperties.put("{http://xml.apache.org/xalan}content-handler",
            "uk.ac.cam.caret.sakai.rwiki.component.service.impl.FOP2PDFSerializer");
    xeh.setOutputProperties(outputProperties);

    MockHttpServletResponse response = new MockHttpServletResponse();
    xeh.init();
    xeh.outputContent(rwe, rwe, request, response);
    File f = new File("testoutput.pdf");
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(response.getContentAsByteArray());
    fo.close();

    long start = System.currentTimeMillis();
    int iters = 10;
    for (int j = 0; j < iters; j++) {
        response = new MockHttpServletResponse();
        xeh.outputContent(rwe, rwe, request, response);
    }
    float timet = (float) 1.0 * (System.currentTimeMillis() - start);
    float tper = (float) (timet / (1.0 * iters));
    logger.info("Transform and Serialize Call Cost = " + tper + " ms");

}