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.github.woonsan.katharsis.servlet.KatharsisServletTest.java

@Test
public void onSimpleCollectionGetShouldReturnCollectionOfResources() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks/");
    request.setRequestURI("/api/tasks/");
    request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
    request.addHeader("Accept", "*/*");

    MockHttpServletResponse response = new MockHttpServletResponse();

    katharsisServlet.service(request, response);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);//www . j  a  va 2  s  .  c  om

    assertJsonPartEquals("tasks", responseContent, "data[0].type");
    assertJsonPartEquals("\"1\"", responseContent, "data[0].id");
    assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data[0].attributes");
    assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data[0].relationships.project.links");
    assertJsonPartEquals("[]", responseContent, "included");
}

From source file:com.github.woonsan.katharsis.servlet.KatharsisServletTest.java

@Test
public void onSimpleResourceGetShouldReturnOneResource() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks/1");
    request.setRequestURI("/api/tasks/1");
    request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
    request.addHeader("Accept", "*/*");
    request.addParameter("filter", "");

    MockHttpServletResponse response = new MockHttpServletResponse();

    katharsisServlet.service(request, response);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);/*  w w w  . j ava2s .co  m*/

    assertJsonPartEquals("tasks", responseContent, "data.type");
    assertJsonPartEquals("\"1\"", responseContent, "data.id");
    assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes");
    assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links");
    assertJsonPartEquals("[]", responseContent, "included");
}

From source file:com.github.woonsan.katharsis.servlet.KatharsisServletTest.java

@Test
public void onCollectionRequestWithParamsGetShouldReturnCollection() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo("/tasks");
    request.setRequestURI("/api/tasks");
    request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
    request.addHeader("Accept", "*/*");
    request.addParameter("filter", "{\"name\":\"John\"}");

    MockHttpServletResponse response = new MockHttpServletResponse();

    katharsisServlet.service(request, response);

    String responseContent = response.getContentAsString();

    log.debug("responseContent: {}", responseContent);
    assertNotNull(responseContent);//  w  w  w  .  jav  a 2 s  .c o  m

    assertJsonPartEquals("tasks", responseContent, "data[0].type");
    assertJsonPartEquals("\"1\"", responseContent, "data[0].id");
    assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data[0].attributes");
    assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links");
    assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data[0].relationships.project.links");
    assertJsonPartEquals("[]", responseContent, "included");
}

From source file:org.openmrs.module.clinicalsummary.web.service.PatientSearchControllerTest.java

/**
 * @verifies should return empty list when no patient match search term
 * @see org.openmrs.module.clinicalsummary.web.controller.service.PatientSearchController#searchPatient(String, String, String, javax.servlet.http.HttpServletResponse)
 *//*  w  w w.j av a2s . c  o m*/
@Test
public void searchPatient_shouldReturnEmptyListWhenNoPatientMatchSearchTerm() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/module/clinicalsummary/service/patient/search");
    request.setParameter("term", "999-3");
    request.setParameter("username", "admin");
    request.setParameter("password", "test");

    MockHttpServletResponse response = new MockHttpServletResponse();
    HandlerAdapter handlerAdapter = new AnnotationMethodHandlerAdapter();
    handlerAdapter.handle(request, response, controller);

    Assert.assertTrue(StringUtils.isNotEmpty(response.getContentAsString()));
    Assert.assertFalse(StringUtils.contains(response.getContentAsString(), "999-3"));
}

From source file:org.opentestsystem.shared.docs.RequestLoggingInterceptor.java

@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) throws Exception { // NOPMD
    FileOutputStream fileOut = null;
    try {/*from  w  ww. ja v a2  s.  c  om*/
        LOGGER.debug(" ");
        LOGGER.debug(" ");

        LOGGER.debug("Request ");

        int rank = getRankOfApiDoc();
        // if rank is -1 skip it: that's the way to hide a api doc. Also exclude negative security testing
        if (rank >= ZERO && response.getStatus() != HttpStatus.SC_UNAUTHORIZED) {
            // block pmd concurrent hashmap warning
            ApiExample example = new ApiExample();
            example.setApiDocRank(rank);
            example.setRequestMethod(HttpMethod.valueOf(request.getMethod()));
            example.setRequestContentType(request.getContentType());
            example.setRequestUri(request.getRequestURI());
            String reqQueryString = request.getQueryString();
            //grab the parameters off the request instead
            if (StringUtils.isBlank(reqQueryString)) {
                if (request.getParameterMap() != null) {
                    List<String> params = new ArrayList<String>();
                    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                        String temp = entry.getKey() + "=";
                        if (entry.getValue() != null) {
                            temp += Joiner.on(",").join(entry.getValue());
                        }
                        params.add(temp);
                    }
                    reqQueryString = Joiner.on("&").join(params.toArray());
                }
            }
            example.setRequestQueryString(reqQueryString);

            LOGGER.debug(example.toString());

            InputStream instream = request.getInputStream();
            String requestData = "";
            if (instream != null) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                requestData = writer.toString();
            }
            example.setRequestData(requestData);
            LOGGER.debug("request data :" + example.getRequestData());
            LOGGER.debug(" ");

            LOGGER.debug("Response  ");
            MockHttpServletResponse res = (MockHttpServletResponse) response;
            example.setResponseContent(res.getContentAsString());
            example.setResponseCode(res.getStatus());

            LOGGER.debug("Server Response:" + example.getResponseContent());
            LOGGER.debug(" ");
            LOGGER.debug(" ");

            if (API_EXAMPLE_FILE != null) {
                fileOut = new FileOutputStream(API_EXAMPLE_FILE, true);
                ObjectMapper mapper = new ObjectMapper();
                byte[] bytes = mapper.writeValueAsBytes(example);
                fileOut.write(bytes);
                String str = ",";
                fileOut.write(str.getBytes());
                fileOut.close();
            }
        }
    } finally {
        if (fileOut != null) {
            fileOut.close();
        }
    }
}

From source file:org.openmrs.module.clinicalsummary.web.service.PatientSearchControllerTest.java

/**
 * @verifies should return patients with name search term
 * @see org.openmrs.module.clinicalsummary.web.controller.service.PatientSearchController#searchPatient(String, String, String, javax.servlet.http.HttpServletResponse)
 */// w w w.java 2s  .  co  m
@Test
public void searchPatient_shouldReturnPatientsWithNameSearchTerm() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/module/clinicalsummary/service/patient/search");
    request.setParameter("term", "Collet");
    request.setParameter("username", "admin");
    request.setParameter("password", "test");

    MockHttpServletResponse response = new MockHttpServletResponse();
    HandlerAdapter handlerAdapter = new AnnotationMethodHandlerAdapter();
    handlerAdapter.handle(request, response, controller);

    Assert.assertTrue(StringUtils.isNotEmpty(response.getContentAsString()));
    Assert.assertTrue(StringUtils.contains(response.getContentAsString(), "Collet Test Chebaskwony"));
    Assert.assertTrue(StringUtils.contains(response.getContentAsString(), "6TS-4"));
}

From source file:org.openmrs.module.clinicalsummary.web.service.PatientSearchControllerTest.java

/**
 * @verifies should return patients with identifier search term
 * @see org.openmrs.module.clinicalsummary.web.controller.service.PatientSearchController#searchPatient(String, String, String, javax.servlet.http.HttpServletResponse)
 *//*from  ww w  .  j a va 2 s.  c o m*/
@Test
public void searchPatient_shouldReturnPatientsWithIdentifierSearchTerm() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/module/clinicalsummary/service/patient/search");
    request.setParameter("term", "6TS-4");
    request.setParameter("username", "admin");
    request.setParameter("password", "test");

    MockHttpServletResponse response = new MockHttpServletResponse();
    HandlerAdapter handlerAdapter = new AnnotationMethodHandlerAdapter();
    handlerAdapter.handle(request, response, controller);

    Assert.assertTrue(StringUtils.isNotEmpty(response.getContentAsString()));
    Assert.assertTrue(StringUtils.contains(response.getContentAsString(), "Collet Test Chebaskwony"));
    Assert.assertTrue(StringUtils.contains(response.getContentAsString(), "6TS-4"));
}

From source file:cc.redpen.server.api.RedPenResourceTest.java

public void testRun() throws Exception {
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD);
    request.setContent("document=Foobar".getBytes());
    MockHttpServletResponse response = invoke(request);
    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
    JSONArray errors = (JSONArray) new JSONObject(response.getContentAsString()).get("errors");
    assertEquals(0, errors.length());/* ww  w.jav  a2 s  .c  o  m*/
}

From source file:net.javacrumbs.smock.http.server.servlet.CommonServletBasedMockWebServiceClient.java

public ResponseActions sendRequestTo(String path, RequestCreator requestCreator) {
    try {//from   w w  w  .  j  a  v a2 s .  c om
        Assert.notNull(requestCreator, "'requestCreator' must not be null");
        WebServiceMessage requestMessage = requestCreator.createRequest(messageFactory);
        final MockHttpServletRequest request = createRequest(path, requestMessage);
        MessageContext messageContext = new DefaultMessageContext(requestMessage, messageFactory);
        interceptingTemplate.interceptRequest(messageContext, new WebServiceMessageReceiver() {
            public void receive(MessageContext messageContext) throws Exception {
                MockHttpServletResponse response = new ExtendedMockHttpServletResponse();
                servlet.service(request, response);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Received response:" + response.getContentAsString());
                }
                messageContext.setResponse(messageFactory
                        .createWebServiceMessage(new ByteArrayInputStream(response.getContentAsByteArray())));
            }
        });
        return new MockWebServiceClientResponseActions(messageContext);
    } catch (Exception e) {
        throw new IllegalStateException("Error when sending request", e);
    }
}

From source file:cc.redpen.server.api.RedPenResourceTest.java

public void testJSValidatorRuns() throws Exception {
    if (new File("redpen-server").exists()) {
        System.setProperty("REDPEN_HOME", "redpen-server/src/test");
    } else {//from   w  w w  . j a  v a 2  s. c o m
        System.setProperty("REDPEN_HOME", "src/test");
    }
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate/json", WILDCARD,
            APPLICATION_JSON);
    request.setContent(String.format(
            "{\"document\":\"Test, this is a test.\",\"format\":\"json2\",\"documentParser\":\"PLAIN\",\"config\":{\"lang\":\"en\",\"validators\":{\"JavaScript\":{\"properties\":{\"script-path\":\"%s\"}}}}}",
            "resources/js").getBytes());
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
    JSONArray errors = new JSONObject(response.getContentAsString()).getJSONArray("errors");
    assertTrue(errors.length() > 0);
    for (int i = 0; i < errors.length(); ++i) {
        JSONObject o = errors.getJSONObject(i).getJSONArray("errors").getJSONObject(0);
        assertEquals("[pass.js] called", o.getString("message"));
    }
}