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.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());/* w  w w .  j a v  a 2s. 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());/*  w  w w. j  a  v  a 2s. 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.opennms.web.rest.AbstractSpringJerseyRestTestCase.java

protected String stringifyResponse(final MockHttpServletResponse response) {
    final StringBuilder string = new StringBuilder();
    try {/*from w w w  .  j a  v  a 2s.  c om*/
        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(response.getHeader(name));
        }
        string.append("]").append("]");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("Unable to get response content", e);
    }
    return string.toString();
}

From source file:org.osaf.cosmo.cmp.CmpGetTest.java

public void testGetUserCount() throws Exception {
    MockHttpServletRequest request = createMockRequest("GET", "/users/count");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);// w  w  w.  j  av a  2s.c  om

    String count = response.getContentAsString();
    assertTrue(count + " not equal to 1.", count.equals("1"));

    User u1 = testHelper.makeDummyUser();
    userService.createUser(u1);

    request = createMockRequest("GET", "/users/count");
    response = new MockHttpServletResponse();
    servlet.service(request, response);

    count = response.getContentAsString();
    assertTrue(count + " not equal to 2.", count.equals("2"));

    User u2 = testHelper.makeDummyUser();
    userService.createUser(u2);

    request = createMockRequest("GET", "/users/count");
    response = new MockHttpServletResponse();
    servlet.service(request, response);

    count = response.getContentAsString();
    assertTrue(count + " not equal to 3.", count.equals("3"));

    User u3 = testHelper.makeDummyUser();
    userService.createUser(u3);

    request = createMockRequest("GET", "/users/count");
    response = new MockHttpServletResponse();
    servlet.service(request, response);

    count = response.getContentAsString();
    assertTrue(count + " not equal to 4.", count.equals("4"));
}

From source file:org.osaf.cosmo.cmp.CmpGetTest.java

/**
 *//*from   w ww.  j a v  a 2  s . c  o m*/
public void testGetServerStatus() throws Exception {
    MockHttpServletRequest request = createMockRequest("GET", "/server/status");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);

    assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
    assertEquals("text/plain", response.getContentType());
    assertEquals("UTF-8", response.getCharacterEncoding());

    BufferedReader content = new BufferedReader(new StringReader(response.getContentAsString()));
    String line = content.readLine();
    boolean found = false;
    while (line != null) {
        if (line.startsWith("jvm.memory.max=")) {
            found = true;
            break;
        }
        line = content.readLine();
    }
    assertTrue("did not find jvm.memory.max in status output", found);
}

From source file:org.pentaho.test.platform.web.ui.servlet.MondrianCatalogPublisherTests.java

@Test
public void testNoOverwrite() throws Exception {
    MockHttpServletResponse response = simulateRequest(getDefaultMap());
    assertTrue("status \"" + response.getContentAsString() + "\" not valid",
            isStatusValid(response.getContentAsString()));

    assertTrue(/*www  .j  av a2s . c  o  m*/
            "expected status=" + ISolutionRepository.FILE_ADD_SUCCESSFUL + ", actual status="
                    + response.getContentAsString().trim(),
            ISolutionRepository.FILE_ADD_SUCCESSFUL == Integer.valueOf(response.getContentAsString().trim()));
}

From source file:org.pentaho.test.platform.web.ui.servlet.MondrianCatalogPublisherTests.java

@Test
public void testFileExists() throws Exception {
    Map<String, String> map = getDefaultMap();
    MockHttpServletResponse response = simulateRequest(map);

    assertTrue("status \"" + response.getContentAsString() + "\" not valid",
            isStatusValid(response.getContentAsString()));

    assertTrue(//from  w w  w .  j  a  va2s.co m
            "expected status=" + ISolutionRepository.FILE_ADD_SUCCESSFUL + ", actual status="
                    + response.getContentAsString().trim(),
            ISolutionRepository.FILE_ADD_SUCCESSFUL == Integer.valueOf(response.getContentAsString().trim()));

    // redo the request
    response = simulateRequest(map);

    assertTrue("status \"" + response.getContentAsString() + "\" not valid",
            isStatusValid(response.getContentAsString()));

    assertTrue(
            "expected status=" + ISolutionRepository.FILE_EXISTS + ", actual status="
                    + response.getContentAsString().trim(),
            ISolutionRepository.FILE_EXISTS == Integer.valueOf(response.getContentAsString().trim()));

}

From source file:org.pentaho.test.platform.web.ui.servlet.MondrianCatalogPublisherTests.java

@Test
public void testOverwrite() throws Exception {
    Map<String, String> map = getDefaultMap();
    MockHttpServletResponse response = simulateRequest(map);

    assertTrue("status \"" + response.getContentAsString() + "\" not valid",
            isStatusValid(response.getContentAsString()));

    assertTrue(//from  w w  w  . jav  a  2 s .c  o  m
            "expected status=" + ISolutionRepository.FILE_ADD_SUCCESSFUL + ", actual status="
                    + response.getContentAsString().trim(),
            ISolutionRepository.FILE_ADD_SUCCESSFUL == Integer.valueOf(response.getContentAsString().trim()));

    // redo the request

    map.put("overwrite", "true");
    response = simulateRequest(map);

    assertTrue("status \"" + response.getContentAsString() + "\" not valid",
            isStatusValid(response.getContentAsString()));

    assertTrue(
            "expected status=" + ISolutionRepository.FILE_ADD_SUCCESSFUL + ", actual status="
                    + response.getContentAsString().trim(),
            ISolutionRepository.FILE_ADD_SUCCESSFUL == Integer.valueOf(response.getContentAsString().trim()));

}

From source file:org.pentaho.test.platform.web.ui.servlet.MondrianCatalogPublisherTests.java

protected MockHttpServletResponse simulateRequest(Map<String, String> map) throws Exception {

    // prepare request
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContentType("multipart/form-data; boundary=---1234"); //$NON-NLS-1$
    request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
    String mondrianSchemaFile = map.get("mondrianSchemaFile");
    if (logger.isDebugEnabled()) {
        logger.debug("uploading mondrian schema file named \"" + mondrianSchemaFile + "\"");
    }/*from  w  w w.j ava2 s . c o m*/
    String content = MessageFormat.format(DEFAULT_CONTENT_TEMPLATE, mondrianSchemaFile, DEFAULT_FILE_CONTENT);
    if (logger.isDebugEnabled()) {
        logger.debug("content=" + content); //$NON-NLS-1$
    }
    request.setContent(content.getBytes("UTF-8")); //$NON-NLS-1$
    request.addParameter("publishPath", map.get("publishPath")); //$NON-NLS-1$ //$NON-NLS-2$
    request.addParameter("publishKey", map.get("publishKey")); //$NON-NLS-1$ //$NON-NLS-2$
    request.addParameter("overwrite", map.get("overwrite")); //$NON-NLS-1$ //$NON-NLS-2$
    request.addParameter("jndiName", map.get("jndiName")); //$NON-NLS-1$ //$NON-NLS-2$

    MockHttpSession httpSession = new MockHttpSession();

    httpSession.setAttribute("pentaho-session", pentahoSession); //$NON-NLS-1$

    request.setSession(httpSession);

    // prepare response
    MockHttpServletResponse response = new MockHttpServletResponse();

    // prepare mondrian catalog service
    MondrianCatalogHelper catService = new MondrianCatalogHelper();
    catService.setDataSourcesConfig("file:" + destFile.getAbsolutePath()); //$NON-NLS-1$
    //    catService.afterPropertiesSet();

    // prepare mondrian catalog publisher
    MondrianCatalogPublisher pub = new MondrianCatalogPublisher();
    pub.setMondrianCatalogService(catService);
    pub.setFullyQualifiedServerURL("http://localhost:8080/pentaho"); //$NON-NLS-1$
    //    pub.afterPropertiesSet();

    // process request
    // TODO We need to figure out how to test this . doGet is a protected method now  
    //pub.doGet(request, response); 

    // assertions
    response.getWriter().flush();
    String responseContent = response.getContentAsString();
    if (logger.isDebugEnabled()) {
        logger.debug("response=" + responseContent); //$NON-NLS-1$
    }
    return response;
}

From source file:org.ppwcode.vernacular.l10n_III.dojo.DojoDjConfigFilterTest.java

private void testDojoDjConfigFilterHelper(String type, String input, String output, String bestLocale)
        throws UnsupportedEncodingException, IOException, ServletException {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
    MockHttpServletResponse response = new MockHttpServletResponse();

    Servlet testServlet = new SimpleServlet(type, input);
    PassThroughFilterChain chain = new PassThroughFilterChain(testServlet);

    HttpSession session = request.getSession();
    session.setAttribute(HttpRequestLocaleFilter.ATTRIBUTE_PREFERRED_LOCALE,
            LocaleHelpers.constructLocaleFromString(bestLocale));

    Filter djConfigFilter = new DojoDjConfigFilter();
    djConfigFilter.doFilter(request, response, chain);

    LOG.debug("input\n" + input);
    LOG.debug("output\n" + response.getContentAsString());

    Assert.assertEquals(output, response.getContentAsString());
    Assert.assertEquals(output.length(), response.getContentLength());
}