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:org.kuali.rice.web.health.HealthServletTest.java

@Test
public void testService_No_Details_Ok() throws Exception {
    healthServlet.init();//  ww  w  .j a va2 s.c o m
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost:8080/rice-standalone/health");
    request.setMethod("GET");
    MockHttpServletResponse response = new MockHttpServletResponse();
    healthServlet.service(request, response);
    assertEquals("Response code should be 204", 204, response.getStatus());
    String content = response.getContentAsString();
    assertTrue("Content should be empty", content.isEmpty());
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

@Test
public void testService_No_Details_Failed() throws Exception {
    // set memory usage threshold at 0 to guarantee a failure
    this.config.putProperty("rice.health.memory.total.usageThreshold", "0.0");

    healthServlet.init();/*from   w w  w .  j a  v a  2  s . c om*/
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost:8080/rice-standalone/health");
    request.setMethod("GET");
    MockHttpServletResponse response = new MockHttpServletResponse();
    healthServlet.service(request, response);
    assertEquals("Response code should be 503", 503, response.getStatus());
    String content = response.getContentAsString();
    assertTrue("Content should be empty", content.isEmpty());
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

@Test
public void testService_Details_Ok() throws Exception {
    // we'll use the defaults
    ConfigContext.init(this.config);

    MockHttpServletResponse response = initAndExecuteDetailedCheck(healthServlet);
    assertEquals("Response code should be 200", 200, response.getStatus());
    JsonNode root = parseContent(response.getContentAsString());
    assertEquals("Ok", root.get("Status").asText());
    assertFalse(root.has("Message"));
    Map<String, String> metricMap = loadMetricMap(root);

    // AmazonS3/*from w ww .j a v a  2  s .c  om*/
    assertEquals("true", metricMap.get("amazonS3:connected"));

    // database connections
    assertEquals("true", metricMap.get("database.primary:connected"));
    assertEquals("true", metricMap.get("database.non-transactional:connected"));
    assertEquals("true", metricMap.get("database.server:connected"));

    // database pools
    assertEquals("20", metricMap.get("database.primary:pool.max"));
    assertEquals("20", metricMap.get("database.non-transactional:pool.max"));
    assertEquals("20", metricMap.get("database.server:pool.max"));

    // buffer pool
    //
    // hard to know exactly what these will be in different environments, let's just make sure there is at least one
    // key in the map that starts with "buffer-pool:"
    assertTrue("At least one metric name should start with 'buffer-pool:'",
            containsKeyStartsWith("buffer-pool:", metricMap));

    // classloader
    String classloaderLoadedValue = metricMap.get("classloader:loaded");
    assertNotNull(classloaderLoadedValue);
    assertTrue(Long.parseLong(classloaderLoadedValue) > 0);

    // file descriptor
    String fileDescriptorUsageValue = metricMap.get("file-descriptor:usage");
    assertNotNull(fileDescriptorUsageValue);
    double fileDescriptorUsage = Double.parseDouble(fileDescriptorUsageValue);
    assertTrue(fileDescriptorUsage > 0);
    assertTrue(fileDescriptorUsage < 1);

    // garbage collector
    //
    // hard to know exactly what these will be in different environments, let's just make sure there is at least one
    // key in the map that starts with "garbage-collector"
    assertTrue("At least one metric name should start with 'garbage-collector:'",
            containsKeyStartsWith("garbage-collector:", metricMap));

    // memory
    String totalMemoryUsageValue = metricMap.get("memory:total.usage");
    assertNotNull(totalMemoryUsageValue);
    double totalMemoryUsage = Double.parseDouble(totalMemoryUsageValue);
    assertTrue(totalMemoryUsage > 0);
    assertTrue(totalMemoryUsage < 1);

    // uptime
    String uptimeValue = metricMap.get("runtime:uptime");
    assertNotNull(uptimeValue);
    assertTrue(Long.parseLong(uptimeValue) > 0);

    // threads
    String deadlockCountValue = metricMap.get("thread:deadlock.count");
    assertNotNull(deadlockCountValue);
    assertEquals(0, Integer.parseInt(deadlockCountValue));

}

From source file:org.kuali.rice.web.health.HealthServletTest.java

@Test
public void testService_Details_Failed_HeapMemoryThreshold() throws Exception {
    // configure "rice.health.memory.heap.usageThreshold" to a threshold that we know will fail
    this.config.putProperty(HealthServlet.Config.HEAP_MEMORY_THRESHOLD_PROPERTY, "0");
    ConfigContext.init(this.config);

    MockHttpServletResponse response = initAndExecuteDetailedCheck(healthServlet);
    assertEquals("Response code should be 503", 503, response.getStatus());
    JsonNode root = parseContent(response.getContentAsString());
    assertEquals("Failed", root.get("Status").asText());
    assertTrue(root.has("Message"));
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

@Test
public void testService_Details_Multiple_Failures() throws Exception {
    // configure all of the connection pool health checks so that they fail
    this.config.putProperty(HealthServlet.Config.PRIMARY_POOL_USAGE_THRESHOLD_PROPERTY, "0");
    this.config.putProperty(HealthServlet.Config.NON_TRANSACTIONAL_POOL_USAGE_THRESHOLD_PROPERTY, "0");
    this.config.putProperty(HealthServlet.Config.SERVER_POOL_USAGE_THRESHOLD_PROPERTY, "0");
    ConfigContext.init(this.config);

    MockHttpServletResponse response = initAndExecuteDetailedCheck(healthServlet);
    assertEquals("Response code should be 503", 503, response.getStatus());
    JsonNode root = parseContent(response.getContentAsString());
    assertEquals("Failed", root.get("Status").asText());
    assertTrue(root.has("Message"));
    String message = root.get("Message").asText();
    assertFalse(StringUtils.isBlank(message));

    Pattern pattern = Pattern.compile("\\* database\\.primary:pool\\.usage -> .+");
    Matcher matcher = pattern.matcher(message);
    assertTrue(matcher.find());/* w w  w  . j  a  v  a  2 s  . c o m*/

    pattern = Pattern.compile("\\* database\\.non-transactional:pool\\.usage -> .+");
    matcher = pattern.matcher(message);
    assertTrue(matcher.find());

    pattern = Pattern.compile("\\* database\\.server:pool\\.usage -> .+");
    matcher = pattern.matcher(message);
    assertTrue(matcher.find());

    pattern = Pattern.compile("\\* ");
    matcher = pattern.matcher(message);
    // find should return true three times because there should be three of them
    assertTrue(matcher.find());
    assertTrue(matcher.find());
    assertTrue(matcher.find());
    // we've found all occurrences, should return false on next invocation
    assertFalse(matcher.find());
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

private MockHttpServletResponse initAndExecuteDetailedCheck(HealthServlet healthServlet) throws Exception {
    healthServlet.init();/*from   w  ww.  ja  v a  2 s.c  om*/
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost:8080/rice-standalone/health");
    request.setMethod("GET");
    request.setParameter("detail", "true");
    MockHttpServletResponse response = new MockHttpServletResponse();
    healthServlet.service(request, response);
    String content = response.getContentAsString();
    assertEquals("application/json", response.getContentType());
    assertFalse(content.isEmpty());
    return response;
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

private void assertFailedResponse(HealthServlet healthServlet) throws Exception {
    MockHttpServletResponse response = initAndExecuteDetailedCheck(healthServlet);
    assertEquals("Response code should be 503", 503, response.getStatus());
    JsonNode root = parseContent(response.getContentAsString());
    assertEquals("Failed", root.get("Status").asText());
    assertTrue(root.has("Message"));
    assertFalse(StringUtils.isBlank(root.get("Message").asText()));
}

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

@Test
public void shouldRetrieveResourceValueAsFile() throws Exception {
    // Get the clobData for the resource
    FormResource resource = formService.getFormResourceByUuid(getUuid());
    ClobDatatypeStorage clobData = datatypeService.getClobDatatypeStorageByUuid(resource.getValueReference());

    MockHttpServletResponse response = handle(newGetRequest(getURI() + "/" + getUuid() + "/value"));

    String expected = "attachment;filename=\"" + resource.getName() + "\"";
    Assert.assertTrue(StringUtils.equals((String) response.getHeader("Content-Disposition"), expected));
    Assert.assertEquals(clobData.getValue(), response.getContentAsString());
}

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

protected String stringifyResponse(final MockHttpServletResponse response) {
    final StringBuilder string = new StringBuilder();
    try {/*w  ww  . ja v a  2s .  co  m*/
        string.append("HttpServletResponse[").append("status=").append(response.getStatus()).append(",content=")
                .append(response.getContentAsString()).append(",headers=[");
        boolean first = true;
        for (final Iterator<String> i = response.getHeaderNames().iterator(); i.hasNext(); first = false) {
            if (!first) {
                string.append(",");
            }
            final String name = i.next();
            string.append(name).append("=").append(response.getHeader(name));
        }
        string.append("]").append("]");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("Unable to get response content", e);
    }
    return string.toString();
}

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

protected String sendRequest(MockHttpServletRequest request, int expectedStatus, final String expectedUrlSuffix)
        throws Exception, UnsupportedEncodingException {
    MockHttpServletResponse response = createResponse();
    dispatch(request, response);//from w w  w.ja  v  a2  s  . c  o m
    final String xml = response.getContentAsString();
    if (xml != null && !xml.isEmpty()) {
        try {
            System.err.println(StringUtils.prettyXml(xml));
        } catch (Exception e) {
            System.err.println(xml);
        }
    }
    assertEquals(expectedStatus, response.getStatus());
    if (expectedUrlSuffix != null) {
        final String location = response.getHeader("Location").toString();
        assertTrue("location '" + location + "' should end with '" + expectedUrlSuffix + "'",
                location.endsWith(expectedUrlSuffix));
    }
    Thread.sleep(50);
    return xml;
}