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

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

Introduction

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

Prototype

public String getContentAsString() throws UnsupportedEncodingException 

Source Link

Document

Get the content of the response body as a String , using the charset specified for the response by the application, either through HttpServletResponse methods or through a charset parameter on the Content-Type .

Usage

From source file:com.enonic.cms.framework.util.HttpServletRangeUtilTest.java

@Test
public void test_out_of_range_in_multipart() throws Exception {
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod("GET");
    httpServletRequest.setPathInfo("/input.dat");
    httpServletRequest.addHeader(HttpHeaders.RANGE, "bytes=0-5, 50000-50100");

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest(httpServletRequest, mockHttpServletResponse, "input.dat",
            "application/pdf", INPUT_FILE, false);

    assertEquals("", mockHttpServletResponse.getContentAsString());

    assertEquals(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, mockHttpServletResponse.getStatus());
}

From source file:com.google.api.server.spi.response.RestResponseResultWriterTest.java

private void writeError(int exceptionCode, int expectedCode, String reason,
        boolean enableExceptionCompatibility) throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    RestResponseResultWriter writer = new RestResponseResultWriter(response, null, true /* prettyPrint */,
            enableExceptionCompatibility);
    writer.writeError(new ServiceException(exceptionCode, "error"));
    ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper();
    ObjectNode content = mapper.readValue(response.getContentAsString(), ObjectNode.class);
    JsonNode outerError = content.path("error");
    assertThat(outerError.path("code").asInt()).isEqualTo(expectedCode);
    assertThat(outerError.path("message").asText()).isEqualTo("error");
    JsonNode innerError = outerError.path("errors").path(0);
    assertThat(innerError.path("domain").asText()).isEqualTo("global");
    assertThat(innerError.path("reason").asText()).isEqualTo(reason);
    assertThat(innerError.path("message").asText()).isEqualTo("error");
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriterTest.java

@Test
public void testPrettyPrint() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    ServletResponseResultWriter writer = new ServletResponseResultWriter(response, null,
            true /* prettyPrint */);
    writer.write(ImmutableMap.of("one", "two", "three", "four"));
    // If the response is pretty printed, there should be at least two newlines.
    String body = response.getContentAsString();
    int index = body.indexOf('\n');
    assertThat(index).isAtLeast(0);/*from   www . ja  v  a2 s  .  co m*/
    index = body.indexOf('\n', index + 1);
    assertThat(index).isAtLeast(0);
    // Unlike the Jackson pretty printer, which will either put no space around a colon or a space
    // on both sides, we want to ensure that a space comes after a colon, but not before.
    assertThat(body).contains("\": ");
    assertThat(body).doesNotContain("\" :");
}

From source file:com.enonic.cms.framework.util.HttpServletRangeUtilTest.java

@Test
public void test_process_request_plain_last_range_minus() throws Exception {
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod("GET");
    httpServletRequest.setPathInfo("/input.dat");
    httpServletRequest.addHeader(HttpHeaders.RANGE, "bytes=51-");

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest(httpServletRequest, mockHttpServletResponse, "input.dat",
            "application/pdf", INPUT_FILE, false);

    assertEquals("z", mockHttpServletResponse.getContentAsString());

    assertEquals(HttpServletResponse.SC_PARTIAL_CONTENT, mockHttpServletResponse.getStatus());
    assertEquals("application/pdf", mockHttpServletResponse.getContentType());
    assertEquals("inline;filename=\"input.dat\"",
            mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_DISPOSITION));
    assertEquals("1", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));

}

From source file:com.enonic.cms.framework.util.HttpServletRangeUtilTest.java

@Test
public void test_process_request_plain_range_minus() throws Exception {
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod("GET");
    httpServletRequest.setPathInfo("/input.dat");
    httpServletRequest.addHeader(HttpHeaders.RANGE, "bytes=50-");

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest(httpServletRequest, mockHttpServletResponse, "input.dat",
            "application/pdf", INPUT_FILE, false);

    assertEquals("Zz", mockHttpServletResponse.getContentAsString());

    assertEquals(HttpServletResponse.SC_PARTIAL_CONTENT, mockHttpServletResponse.getStatus());
    assertEquals("application/pdf", mockHttpServletResponse.getContentType());
    assertEquals("inline;filename=\"input.dat\"",
            mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_DISPOSITION));
    assertEquals("2", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));

}

From source file:com.enonic.cms.framework.util.HttpServletRangeUtilTest.java

@Test
public void test_process_request_plain_one_range() throws Exception {
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod("GET");
    httpServletRequest.setPathInfo("/input.dat");
    httpServletRequest.addHeader(HttpHeaders.RANGE, "bytes=0-5");

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest(httpServletRequest, mockHttpServletResponse, "input.dat",
            "application/pdf", INPUT_FILE, false);

    assertEquals("AaBbCc", mockHttpServletResponse.getContentAsString());

    assertEquals(HttpServletResponse.SC_PARTIAL_CONTENT, mockHttpServletResponse.getStatus());
    assertEquals("application/pdf", mockHttpServletResponse.getContentType());
    assertEquals("inline;filename=\"input.dat\"",
            mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_DISPOSITION));
    assertEquals("6", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));

}

From source file:com.google.api.server.spi.response.RestResponseResultWriterTest.java

private void writeError(boolean enableExceptionCompatibility, String customReason, String expectedReason,
        String customDomain, String expectedDomain) throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    RestResponseResultWriter writer = new RestResponseResultWriter(response, null, true /* prettyPrint */,
            enableExceptionCompatibility);
    writer.writeError(new ServiceException(400, "error", customReason, customDomain));
    ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper();
    ObjectNode content = mapper.readValue(response.getContentAsString(), ObjectNode.class);
    JsonNode innerError = content.path("error").path("errors").path(0);
    assertThat(innerError.path("domain").asText()).isEqualTo(expectedDomain);
    assertThat(innerError.path("reason").asText()).isEqualTo(expectedReason);
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectResponseBuilderTest.java

@Test
public void testBuilderUploadResponse() throws IOException {

    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

    request.setParameter("extAction", "action");
    request.setParameter("extMethod", "method");
    request.setParameter("extType", "type");
    request.setParameter("extTID", "1");

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    ExtDirectResponseBuilder.create(request, servletResponse)
            .addResultProperty("additionalProperty", Boolean.FALSE)
            .addResultProperty("text", "a lot of "text"").buildAndWrite();

    assertThat(servletResponse.getContentType()).isEqualTo("text/html;charset=UTF-8");
    String content = servletResponse.getContentAsString();
    assertThat(servletResponse.getContentLength()).isEqualTo(content.getBytes("UTF-8").length);

    assertThat(content).startsWith("<html><body><textarea>");
    assertThat(content).endsWith("</textarea></body></html>");

    String json = content.substring(content.indexOf("{"), content.lastIndexOf("}") + 1);
    assertThat(json).contains("\\&quot;");
    json = json.replace("\\&quot;", "\'");
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> header = mapper.readValue(json, Map.class);

    assertThat(header.get("action")).isEqualTo("action");
    assertThat(header.get("method")).isEqualTo("method");
    assertThat(header.get("type")).isEqualTo("type");
    assertThat(header.get("tid")).isEqualTo(1);

    @SuppressWarnings("unchecked")
    Map<String, Object> result = (Map<String, Object>) header.get("result");
    assertThat(result).hasSize(3);/*from w ww.j  a v a2s .  c o m*/
    assertThat((Boolean) result.get("success")).isTrue();
    assertThat(result.get("text")).isEqualTo("a lot of 'text'");
    assertThat(result.get("additionalProperty")).isEqualTo(Boolean.FALSE);
}

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

/**
 * @see {@link AtomFeedDownloadServlet#doGet(HttpServletRequest,HttpServletResponse)}
 */// w ww.  j  ava  2  s.co m
@Test
@Verifies(value = "should exclude entries before the asOfDate value", method = "doGet(HttpServletRequest,HttpServletResponse)")
public void doGet_shouldExcludeEntriesBeforeTheAsOfDateValue() throws Exception {
    //ensures that at least we have an entry to exclude for testing purposes
    AtomFeedUtil.objectCreated(new Encounter());

    AtomFeedDownloadServlet atomFeedDownloadServlet = new AtomFeedDownloadServlet();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/atomfeed");

    Thread.sleep(1000);//wait for at least a second since the dateFormat precision is to seconds

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date asOfDate = new Date();
    request.setParameter("asOfDate", dateFormat.format(asOfDate));
    MockHttpServletResponse response = new MockHttpServletResponse();

    AtomFeedUtil.objectCreated(new Encounter());
    AtomFeedUtil.objectCreated(new Concept());

    Thread.sleep(2000);//wait for 2 seconds for the feed to get updated      
    atomFeedDownloadServlet.service(request, response);

    //only 2 entries added after the asOfDate should have been returned
    Assert.assertEquals(2, StringUtils.countMatches(response.getContentAsString(), "<entry>"));
}

From source file:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java

protected <T> T getXmlObject(JAXBContext context, String url, int expectedStatus, Class<T> expectedClass)
        throws Exception {
    MockHttpServletRequest request = createRequest(GET, url);
    MockHttpServletResponse response = createResponse();
    dispatch(request, response);/*www. j  a  v  a2s  .co m*/
    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;

}