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

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

Introduction

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

Prototype

public int getContentLength() 

Source Link

Usage

From source file:org.wrml.server.WrmlServletTest.java

@Test
public void requestWithHostAndPortHeaders() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, CAPRICA_SIX_ENDPOINT);
    request.setMethod(Method.Get.getProtocolGivenName());
    request.addHeader(WrmlServlet.WRML_HOST_HEADER_NAME, LOCALHOST);
    request.addHeader(WrmlServlet.WRML_PORT_HEADER_NAME, PORT_1);

    MockHttpServletResponse response = new MockHttpServletResponse();

    initMockWrmlRequest(request, Method.Get, CAPRICA_SIX_SPOOF_2_ENDPOINT, CAPRICA_SCHEMA_URI);

    _Servlet.service(request, response);

    // Verify Model Write
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals(DEFAULT_CONTENT_TYPE, response.getContentType());
    Assert.assertEquals(response.getContentAsByteArray().length, response.getContentLength());
}

From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServletTest.java

/**
 * @see AtomFeedDownloadServlet#doHead(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * @verifies send not modified error if atom feed has not changed
 *///w w  w.j a va2s.c o  m
@Test
public void doHead_shouldSendNotModifiedErrorIfAtomFeedHasNotChanged() throws Exception {
    // create servlet and corresponding request and response object to be sent
    AtomFeedDownloadServlet atomFeedDownloadServlet = new AtomFeedDownloadServlet();
    MockHttpServletRequest request = new MockHttpServletRequest("HEAD", "/atomfeed");
    request.setContextPath("/somecontextpath");
    MockHttpServletResponse response = new MockHttpServletResponse();

    // intentionally change atom feed in order to not depend from other tests
    AtomFeedUtil.objectCreated(new Encounter());

    // read atom feed header specific information from the header file
    String headerFileContent = AtomFeedUtil.readFeedHeaderFile();
    int contentLength = 0;
    String etagToken = "";
    Date lastModified = null;
    if (StringUtils.isNotBlank(headerFileContent)) {
        contentLength = headerFileContent.length() + Integer
                .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>"));
        etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>");
        try {
            lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT)
                    .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>"));
        } catch (ParseException e) {
            // ignore it here
        }
    }
    // set request headers 
    request.addHeader("If-None-Match", '"' + etagToken + '"');
    request.addHeader("If-Modified-Since", lastModified);

    atomFeedDownloadServlet.service(request, response);
    // check response headers
    Assert.assertEquals(contentLength, response.getContentLength());
    Assert.assertEquals("application/atom+xml", response.getContentType());
    Assert.assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus());
    Assert.assertNotNull(response.getHeader("Last-Modified"));
}

From source file:com.formkiq.core.service.workflow.WorkflowServiceImplTest.java

/**
 * print action.//from   w  w w.ja v  a2 s  .com
 * @throws IOException IOException
 */
@Test
public void testActions02() throws IOException {
    // given
    String html = "<p>html</p>";
    byte[] pdf = html.getBytes(CHARSET_UTF8);
    MockHttpServletResponse resp = new MockHttpServletResponse();
    WebFlow flow = expectStart(this.form).getRight();
    Map<String, Object> map = ImmutableMap.of("flow", flow);

    resetAll();

    this.req.setParameter("execution", "s1e1");
    this.req.setParameter("_eventId_download", "");

    // when
    expect(this.printRender.generateHTML(this.req, "flow/print", map)).andReturn(html);
    expect(this.printRender.createPDF(html)).andReturn(pdf);
    replayAll();

    ModelAndView result = this.ws.actions(this.req, resp);

    // then
    verifyAll();

    assertNull(result);
    assertEquals("application/pdf", resp.getContentType());
    assertEquals(html.length(), resp.getContentLength());
    assertEquals(html, resp.getContentAsString());
}

From source file:com.redblackit.web.server.EchoServletTest.java

/**
 * Do test//from w w w . j a va2 s  . c  om
 *
 * @param method
 * @param hasBody if content should be expected
 */
private void doTest(String method, boolean hasBody) throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod(method);
    request.setRequestURI(this.requestURI);

    final String msg = "doTest:" + method + ":hasBody=" + hasBody;
    logger.debug(msg + ":this=" + this);

    for (String headerName : headersMap.keySet()) {
        List<String> values = headersMap.get(headerName);
        if (values.size() == 1) {
            request.addHeader(headerName, values.get(0));
        } else {
            request.addHeader(headerName, values);
        }
        Enumeration<String> headerValues = request.getHeaders(headerName);
        int hi = 0;
        while (headerValues.hasMoreElements()) {
            logger.debug(msg + "request:header[" + headerName + "," + hi + "]=" + headerValues.nextElement());
            ++hi;
        }

        Assert.assertTrue(msg + "TEST ERROR:request:header[" + headerName + "]=" + values
                + ":shouldn't be empty (" + values.getClass() + ")", hi > 0);

    }

    int expectedContentLength = 0;
    if (hasBody && body != null && body.length() > 0) {
        request.setContent(body.getBytes());
        expectedContentLength = request.getContentLength();
    }

    MockHttpServletResponse response = new MockHttpServletResponse();
    echoServlet.service(request, response);

    String responseBody = response.getContentAsString();

    Assert.assertEquals("response code:" + response, HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals("requestURI and Location", requestURI, response.getHeader("Location"));

    Map<String, List<String>> responseHeadersMap = new TreeMap<String, List<String>>();
    for (String headerName : response.getHeaderNames()) {
        List<String> values = response.getHeaders(headerName);
        int hi = 0;
        for (String value : values) {
            logger.debug(msg + ":response:header[" + headerName + "," + hi + "]=" + value);
            ++hi;
        }

        if (hi == 0) {
            logger.debug(msg + ":response:header[" + headerName + "]=" + values + ":is empty ("
                    + values.getClass() + ")");
            values = Arrays.asList(new String[] { "" });
        }

        if (!(headerName.equals("Location") || headerName.equals("Content-Length"))) {
            responseHeadersMap.put(headerName, values);
        }
    }

    Assert.assertEquals("headers (excluding Location and Content-Length)", headersMap, responseHeadersMap);
    if (hasBody) {
        Assert.assertEquals("body", (body == null ? "" : body), responseBody);
    } else {
        Assert.assertEquals("body", "", responseBody);
    }

    Assert.assertEquals("contentLength", expectedContentLength, response.getContentLength());

}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test attempt to retrieve a good file by an admin, where a good file is one that exists and is retrievable by
 * authorized user./*from  w ww  .ja v a 2s.c  o  m*/
 *
 * Expected: Status 200
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 *
 * @throws IOException
 */
@Test
public void testGetFileRequestByAdmin() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;

    fileController.handleFileGetRequest(null, null, null, req, res);

    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));

    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);

    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good file request with null "Accept" header and null "If-Modified-Since" header
 * Expected: Status 200//  w  w  w . jav a2  s .  c  o m
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestNullAcceptModifiedSinceHeader() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;

    //run the handle request
    fileController.handleFileGetRequest("foo", null, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);

    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good file request with specific "Accept" header
 * Expected: Status 200//ww  w .j av  a  2s .  c om
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestSpecificAcceptHeader() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;
    String expectedMimeType = URLConnection.getFileNameMap().getContentTypeFor(dataFileOne.getName());

    //run the handle request
    fileController.handleFileGetRequest("foo", expectedMimeType, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);
    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good non-text file request with specific "Accept" header
 * Expected: Status 200/*from ww  w .  j  av a2 s  . c  om*/
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestBinaryFile() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", "file/foo");
    MockHttpServletResponse res = new MockHttpServletResponse();

    java.io.File binaryFile = new java.io.File(FileControllerTest.class.getResource(FILES_ONLY_ZIP).toURI());
    byte fileContents[] = IOUtils.toByteArray(new FileInputStream(binaryFile));
    long expectedContentLength = binaryFile.length();
    DataFile binaryDataFile = new DataFile("foo", "ZipFileName.zip",
            binaryFile.toURI().toURL().toExternalForm(), "application/zip", binaryFile.getPath(),
            binaryFile.length(), new ArrayList<String>());

    FileBizService fileBizService = fileController.getFileBizService();
    when(fileBizService.getFile("foo", admin)).thenReturn(binaryDataFile);
    when(fileBizService.getLastModifiedDate("foo")).thenReturn(lastModifiedDate);
    RequestUtil requestUtil = fileController.getRequestUtil();
    when(requestUtil.buildRequestUrl(any(HttpServletRequest.class))).thenReturn("foo");

    String expectedMimeType = URLConnection.getFileNameMap().getContentTypeFor(binaryDataFile.getName());

    //run the handle request
    fileController.handleFileGetRequest("foo", null, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertEquals(expectedMimeType, res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertEquals(expectedContentLength, res.getContentLength());

    byte[] responseContent = res.getContentAsByteArray();
    assertArrayEquals(fileContents, responseContent);

}

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

/**
 * Same as {@link #doServeResourceCachedContentValidationMethodTest()}, but simulate browser
 * sending If-None-Match header that matches the etag. Verify no content returned and a 304 status code.
 * /*from w  ww.j  a v  a2s  .com*/
 * @throws PortletException
 * @throws IOException
 * @throws PortletContainerException
 */
@Test
public void doServeResourceCachedContentValidationMethodNotModifiedTest()
        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("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);
    //byte [] fromResponse = response.getContentAsByteArray();

    Assert.assertEquals(0, response.getContentLength());
    Assert.assertEquals(304, 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 #doServeResourceCachedContentValidationMethodNotModifiedTest()}, however the CachedPortletData
 * is older than it's expiration time. Verify the renderer still detects the etag and returns 304 not modified.
 * //from w w  w  . j  av  a2 s  .c  om
 * @throws PortletException
 * @throws IOException
 * @throws PortletContainerException
 */
@Test
public void doServeResourceCachedContentValidationMethodNotModifiedInternalCacheExpiredTest()
        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("123456");
    CachedPortletData cachedPortletData = new CachedPortletData();
    cachedPortletData.setContentType("application/json");
    byte[] content = "{ \"hello\": \"world\" }".getBytes();
    cachedPortletData.setByteData(content);
    cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime());
    cachedPortletData.setEtag("123456");
    // set Time stored to a value prior to the expiration time
    cachedPortletData.setTimeStored(DateUtils.addSeconds(now, -310));

    setupPortletExecutionMocks(request);

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

    portletRenderer.doServeResource(portletWindowId, request, response);

    Assert.assertEquals(0, response.getContentLength());
    Assert.assertEquals(304, response.getStatus());
    // since the cached content is expired, a doServeResource is going to be invoked
    verify(portletContainer, times(1)).doServeResource(isA(PortletWindow.class),
            isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class));
    // portlet said we should useCachedContent, so don't expect an attempt to "cache output"
    verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class));
}