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:net.ljcomputing.sr.controller.StatusReporterControllerTest.java

@Test
public void test100GetAllWbs() {
    try {/*from   ww  w .  j  a v  a  2 s  .  c  o  m*/
        MockHttpServletRequestBuilder requestBuilder = get(expectedResults.getUrl());
        requestBuilder.contentType(MediaType.APPLICATION_JSON);

        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertTrue("failed to get all wbs", response.getStatus() >= 200 && response.getStatus() <= 299);

        logger.debug(response.getContentAsString());
    } catch (Exception e) {
        logger.error("test failed : ", e);
        fail(e.toString());
    }
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Polls the order resource every 2 seconds and uses an {@code If-None-Match} header alongside the {@code ETag} of the
 * first response to avoid sending the representation over and over again.
 * //  www .  j a  v a2 s.c o  m
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse pollUntilOrderHasReceiptLink(MockHttpServletResponse response)
        throws Exception {

    // Grab
    String content = response.getContentAsString();
    LinkDiscoverer discoverer = getDiscovererFor(response);
    Link orderLink = discoverer.findLinkWithRel(ORDER_REL, content);

    // Poll order until receipt link is set
    Link receiptLink = null;
    String etag = null;
    MockHttpServletResponse pollResponse;

    do {

        HttpHeaders headers = new HttpHeaders();
        if (etag != null) {
            headers.setIfNoneMatch(etag);
        }

        log.info("Poll state of order until receipt is ready");

        ResultActions action = mvc.perform(get(orderLink.getHref()).headers(headers));
        pollResponse = action.andReturn().getResponse();

        int status = pollResponse.getStatus();
        etag = pollResponse.getHeader("ETag");

        log.info(String.format("Received %s with ETag of %s", status, etag));

        if (status == HttpStatus.OK.value()) {

            action.andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
                    andExpect(linkWithRelIsNotPresent(UPDATE_REL)). //
                    andExpect(linkWithRelIsNotPresent(CANCEL_REL));

            receiptLink = discoverer.findLinkWithRel(RECEIPT_REL, pollResponse.getContentAsString());

        } else if (status == HttpStatus.NO_CONTENT.value()) {
            action.andExpect(content().string(isEmptyOrNullString()));
        }

        if (receiptLink == null) {
            Thread.sleep(2000);
        }

    } while (receiptLink == null);

    return pollResponse;
}

From source file:net.ljcomputing.sr.controller.StatusReporterControllerTest.java

/**
 * Get all the work breakdown structures.
 *//*from w  ww  . jav  a 2 s  . c o m*/
@Test
public void test080GetAllWbs() {
    try {
        MockHttpServletRequestBuilder requestBuilder = get(expectedResults.getUrl());
        requestBuilder.contentType(MediaType.APPLICATION_JSON);

        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertTrue("failed to get all wbs", response.getStatus() >= 200 && response.getStatus() <= 299);

        logger.debug(response.getContentAsString());
    } catch (Exception e) {
        logger.error("test failed : ", e);
        fail(e.toString());
    }
}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Concludes the {@link Order} by looking up the {@code receipt} link from the response and follows it. Triggers a
 * {@code DELETE} request susequently./*  w w  w .  j  a  va 2s.c  o m*/
 * 
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse takeReceipt(MockHttpServletResponse response) throws Exception {

    Link receiptLink = getDiscovererFor(response).findLinkWithRel(RECEIPT_REL, response.getContentAsString());

    MockHttpServletResponse receiptResponse = mvc.perform(get(receiptLink.getHref())). //
            andExpect(status().isOk()). //
            andReturn().getResponse();

    LOG.info("Accessing receipt, got:" + receiptResponse.getContentAsString());
    LOG.info("Taking receipt");

    return mvc.perform( //
            delete(receiptLink.getHref()).//
                    accept(MediaTypes.HAL_JSON))
            . //
            andExpect(status().isOk()). //
            andReturn().getResponse();
}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Polls the order resource every 2 seconds and uses an {@code If-None-Match} header alongside the {@code ETag} of the
 * first response to avoid sending the representation over and over again.
 * //from  www. j  a  va  2s . c  o  m
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse pollUntilOrderHasReceiptLink(MockHttpServletResponse response)
        throws Exception {

    // Grab
    String content = response.getContentAsString();
    LinkDiscoverer discoverer = getDiscovererFor(response);
    Link orderLink = discoverer.findLinkWithRel(ORDER_REL, content);

    // Poll order until receipt link is set
    Link receiptLink = null;
    String etag = null;
    MockHttpServletResponse pollResponse;

    do {

        HttpHeaders headers = new HttpHeaders();
        if (etag != null) {
            headers.setIfNoneMatch(etag);
        }

        LOG.info("Poll state of order until receipt is ready");

        ResultActions action = mvc.perform(get(orderLink.expand().getHref()).headers(headers));
        pollResponse = action.andReturn().getResponse();

        int status = pollResponse.getStatus();
        etag = pollResponse.getHeader("ETag");

        LOG.info(String.format("Received %s with ETag of %s", status, etag));

        if (status == HttpStatus.OK.value()) {

            action.andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
                    andExpect(linkWithRelIsNotPresent(UPDATE_REL)). //
                    andExpect(linkWithRelIsNotPresent(CANCEL_REL));

            receiptLink = discoverer.findLinkWithRel(RECEIPT_REL, pollResponse.getContentAsString());

        } else if (status == HttpStatus.NO_CONTENT.value()) {
            action.andExpect(content().string(isEmptyOrNullString()));
        }

        if (receiptLink == null) {
            Thread.sleep(2000);
        }

    } while (receiptLink == null);

    return pollResponse;
}

From source file:net.ljcomputing.sr.controller.StatusReporterControllerTest.java

@Test
public void test000CreateWbs() {
    try {/*from  w w w  .j ava  2 s  . c o m*/
        MockHttpServletRequestBuilder requestBuilder = post(expectedResults.getUrl());
        requestBuilder.contentType(MediaType.APPLICATION_JSON);
        requestBuilder.content(expectedResults.getJsonPayload());

        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertTrue("failed to create wbs", response.getStatus() >= 200 && response.getStatus() <= 299);

        String jsonResponse = response.getContentAsString();

        expectedResults.updatePostedRequestBody(jsonResponse);
    } catch (Exception e) {
        logger.error("test failed : ", e);
        fail(e.toString());
    }
}

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

@Test
public void testSingleRangeByte() throws Exception {
    MockHttpServletResponse mockHttpServletResponse = testRange("bytes=10-10");

    Assert.assertEquals("1", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));
    Assert.assertEquals("bytes 10-10/80", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_RANGE));
    Assert.assertEquals("B", mockHttpServletResponse.getContentAsString());
}

From source file:net.ljcomputing.sr.controller.StatusReporterControllerTest.java

@Test
public void test010CreateActivity() {
    try {//  www . ja  v  a2 s.  c  o  m
        String wbsUuid = expectedResults.getPostedRequestBody().getUuid();
        Activity activity = wbs.getActivities().get(0);
        String activityJson = gsonService.toJson(activity);
        String url = expectedResults.getUrl() + "/" + wbsUuid + "/activity";

        MockHttpServletRequestBuilder requestBuilder = post(url);
        requestBuilder.contentType(MediaType.APPLICATION_JSON);
        requestBuilder.content(activityJson);

        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertTrue("failed to create activity", response.getStatus() >= 200 && response.getStatus() <= 299);

        logger.debug(response.getContentAsString());

        url = expectedResults.getUrl() + "/" + wbsUuid;
        requestBuilder = get(url);
        result = mockMvc.perform(requestBuilder);
        mvcResult = result.andReturn();
        response = mvcResult.getResponse();
        String jsonResponse = response.getContentAsString();
        expectedResults.updatePostedRequestBody(jsonResponse);
        logger.debug("expectedResults.getPostedRequestBody() : {}", expectedResults.getPostedRequestBody());
    } catch (Exception e) {
        logger.error("test failed : ", e);
        fail(e.toString());
    }
}

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

@Test
public void testSingleRangeFirst() throws Exception {
    MockHttpServletResponse mockHttpServletResponse = testRange("bytes=0-9");

    Assert.assertEquals("10", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));
    Assert.assertEquals("bytes 0-9/80", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_RANGE));
    Assert.assertEquals("A123456789", mockHttpServletResponse.getContentAsString());
}

From source file:org.springframework.data.rest.webmvc.cassandra.CassandraWebTests.java

/**
 * Verify that creating (POST) and then updating (PATCH) a resource only updates the sub-set of fields.
 *
 * @throws Exception/*from w  w w . j a v a 2 s.c  om*/
 * @see DATAREST-414
 */
@Test
public void createThenPatch() throws Exception {

    Employee employee = new Employee();
    employee.setId("123");
    employee.setFirstName("Frodo");
    employee.setLastName("Baggins");
    employee.setTitle("ring bearer");

    String employeeString = mapper.writeValueAsString(employee);

    Link employeeLink = client.discoverUnique("employees");

    MockHttpServletResponse response1 = postAndGet(employeeLink, employeeString, MediaType.APPLICATION_JSON);

    Link newlyMintedEmployeeLink = client.assertHasLinkWithRel("self", response1);
    Employee newlyMintedEmployee = mapper.readValue(response1.getContentAsString(), Employee.class);

    assertThat(newlyMintedEmployee.getFirstName(), equalTo(employee.getFirstName()));
    assertThat(newlyMintedEmployee.getLastName(), equalTo(employee.getLastName()));
    assertThat(newlyMintedEmployee.getTitle(), equalTo(employee.getTitle()));

    MockHttpServletResponse response2 = patchAndGet(newlyMintedEmployeeLink, "{\"firstName\": \"Bilbo\"}",
            MediaType.APPLICATION_JSON);

    Employee refurbishedEmployee = mapper.readValue(response2.getContentAsString(), Employee.class);

    // That's actually incorrect, isn't it?
    assertThat(refurbishedEmployee.getFirstName(), equalTo("Bilbo"));
    assertThat(refurbishedEmployee.getLastName(), equalTo(employee.getLastName()));
    assertThat(refurbishedEmployee.getTitle(), equalTo(employee.getTitle()));
}