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:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML1AttributeQueryTestCase.java

/** Tests that the attribute query handler correctly handles an incomming query. */
public void testAttributeQuery() throws Exception {
    AttributeQuery query = buildAttributeQuery("urn:example.org:sp1");
    String soapMessage = getSOAPMessage(query);

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml1/SOAP/AttributeQuery");
    servletRequest.setContent(soapMessage.getBytes());

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    ProfileHandler handler = handlerManager.getProfileHandler(servletRequest);
    assertNotNull(handler);/*from w  w w. jav  a2 s . c  o  m*/

    // Process request
    HTTPInTransport profileRequest = new HttpServletRequestAdapter(servletRequest);
    HTTPOutTransport profileResponse = new HttpServletResponseAdapter(servletResponse, false);
    handler.processRequest(profileRequest, profileResponse);

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("saml1p:Success"));
    assertTrue(response.contains("AttributeName=\"urn:mace:dir:attribute-def:eduPersonEntitlement\""));
    assertTrue(response.contains("urn:example.org:entitlement:entitlement1"));
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2AttributeQueryTestCase.java

/** Tests that the attribute query handler correctly handles an incomming query. */
public void testAttributeQuery() throws Exception {
    AttributeQuery query = buildAttributeQuery("urn:example.org:sp1");
    String soapMessage = getSOAPMessage(query);

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml2/SOAP/AttributeQuery");
    servletRequest.setContent(soapMessage.getBytes());

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    ProfileHandler handler = handlerManager.getProfileHandler(servletRequest);
    assertNotNull(handler);/*from w w w  . j  av a  2 s.co  m*/

    // Process request
    HTTPInTransport profileRequest = new HttpServletRequestAdapter(servletRequest);
    HTTPOutTransport profileResponse = new HttpServletResponseAdapter(servletResponse, false);
    handler.processRequest(profileRequest, profileResponse);

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("urn:oasis:names:tc:SAML:2.0:status:Success"));
    assertTrue(response.contains(" Name=\"urn:oid:1.3.6.1.4.1.5923.1.1.1.7\""));
    assertTrue(response.contains("urn:example.org:entitlement:entitlement1"));
}

From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

public void testRegisterUser() throws Exception {
    final User user = new User();
    user.setUser("hasankhan");
    user.setPassword("nhmthk");
    user.setCreatedOn(new Timestamp(System.currentTimeMillis()));
    user.setLastUpdatedOn(new Timestamp(System.currentTimeMillis()));
    user.setRole(User.FIELD_ROLE_ADMIN, true);
    user.setRole(User.FIELD_ROLE_READ, true);
    user.setRole(User.FIELD_ROLE_WRITE, true);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String serviceUri = "/service/register/admin.xml";
    request.setRequestURI(serviceUri);//from  ww  w. jav  a 2s .c  o  m
    final String serializedContent = SerializerFactory.getInstance().serializeObject(SerializerFactory.XML,
            user);
    String requestString = "<" + XmlConstants.ELEMENT_REQUEST + ">";
    requestString += serializedContent;
    requestString += "</" + XmlConstants.ELEMENT_REQUEST + ">";
    request.addParameter("admin", requestString);

    LOG.debug("Request - " + requestString);
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // execute controller
    mRestfulController.handleRequest(request, response);

    final String responseContent = response.getContentAsString();
    assertTrue("No content found", responseContent.length() > 0);
    LOG.debug("content - " + responseContent);
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrantType_withJwtTokens_preservesRefreshTokenExpiryClaim() throws Exception {
    createClientAndUserInRandomZone();/*from w  w w.j av  a  2s.  co  m*/
    when(timeService.getCurrentTimeMillis()).thenReturn(1000L);
    CompositeToken tokenResponse = getTokensWithPasswordGrant(client.getClientId(), SECRET, user.getUserName(),
            SECRET, getZoneHostUrl(zone), "jwt");
    String refreshToken = tokenResponse.getRefreshToken().getValue();
    when(timeService.getCurrentTimeMillis()).thenReturn(5000L);

    MockHttpServletResponse refreshResponse = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            getZoneHostUrl(zone));

    assertEquals(HttpStatus.SC_OK, refreshResponse.getStatus());
    CompositeToken compositeToken = JsonUtils.readValue(refreshResponse.getContentAsString(),
            CompositeToken.class);
    String refreshTokenJwt = compositeToken.getRefreshToken().getValue();
    assertThat(getClaims(refreshTokenJwt).get(EXP), equalTo(getClaims(refreshToken).get(EXP)));

    CompositeToken newTokenResponse = getTokensWithPasswordGrant(client.getClientId(), SECRET,
            user.getUserName(), SECRET, getZoneHostUrl(zone), "jwt");
    String newRefreshToken = newTokenResponse.getRefreshToken().getValue();

    assertThat(getClaims(newRefreshToken).get(EXP), not(nullValue()));
    assertThat(getClaims(newRefreshToken).get(EXP), not(equalTo(getClaims(refreshToken).get(EXP))));
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2ArtifactResolutionTest.java

public void testArtifactResolution() throws Exception {
    String relyingPartyId = "urn:example.org:sp1";
    SAMLArtifactMapEntry artifactEntry = stageArtifact(relyingPartyId);
    String soapMessage = buildRequestMessage(relyingPartyId, artifactEntry.getArtifact());

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml2/SOAP/ArtifactResolution");
    servletRequest.setContent(soapMessage.getBytes());

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    ProfileHandler handler = handlerManager.getProfileHandler(servletRequest);
    assertNotNull(handler);/*w w w. j av a  2  s  . co m*/

    // Process request
    HTTPInTransport profileRequest = new HttpServletRequestAdapter(servletRequest);
    HTTPOutTransport profileResponse = new HttpServletResponseAdapter(servletResponse, false);
    handler.processRequest(profileRequest, profileResponse);

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("saml2p:ArtifactResponse"));
    assertTrue(response.contains("urn:oasis:names:tc:SAML:2.0:status:Success"));
    assertTrue(response.contains("saml2:Assertion"));
}

From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

public void testListOfRelatedItems() throws Exception {
    // Create dummy user object
    final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");

    // authenticate user.
    final Subject subject = getSubjectFromASuccessfulRequest();

    // create fixed items
    final List<Integer> fixedItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 11);

    // update object relation
    final Integer baseItemId = fixedItems.get(0);

    // attach related items
    final String relationType = "category";
    mRepositoryService.addRelatedItems(relationType, baseItemId, fixedItems.subList(1, fixedItems.size()));

    // send restful request
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(//w ww. ja  v a 2s.  c om
            "/service/find-related-items/" + relationType + "&" + String.valueOf(baseItemId) + ".xml");
    request.setParameter(WebConstants.PARAM_MAX, 4 + "");
    request.setMethod(METHOD_POST);
    request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // execute restful controller
    mRestfulController.handleRequest(request, response);

    final String responseString = response.getContentAsString();
    LOG.debug("Response content - " + responseString);

    assertFalse("No response found", responseString == null || responseString.length() == 0);
    assertFalse("Response state false", responseString.indexOf("false") != -1);
}

From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java

/**
 * @see DATAREST-658//from w w w . j a v  a2  s  .c  o  m
 */
@Test
public void returnsLinkHeadersForHeadRequestToItemResource() throws Exception {

    MockHttpServletResponse response = client.request(client.discoverUnique("people"));
    String personHref = JsonPath.read(response.getContentAsString(), "$._embedded.people[0]._links.self.href");

    response = mvc.perform(head(personHref))//
            .andExpect(status().isNoContent())//
            .andReturn().getResponse();

    Links links = Links.valueOf(response.getHeader("Link"));
    assertThat(links.hasLink("self"), is(true));
    assertThat(links.hasLink("person"), is(true));
}

From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

public void testDeleteOperation() throws Exception {
    final List<Integer> createdItems = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1);
    // create new user object
    final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");
    createdItems.add(userId);/*from   w  w w .j av  a2s .com*/
    try {
        final Subject subject = getSubjectFromASuccessfulRequest();
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRequestURI("/service/delete/" + createdItems.get(0) + ".xml");
        request.setMethod(METHOD_DELETE);
        request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
        final MockHttpServletResponse response = new MockHttpServletResponse();

        // Execute command
        mRestfulController.handleRequest(request, response);

        // Verify impacts
        final String content = response.getContentAsString();
        assertTrue("No response request generated.", content.length() > 0);
        final boolean stateTrue = content.indexOf("true") != -1;
        assertTrue("No response state found", stateTrue);
        assertEquals("Return status 202", RESTfulControllerImpl.STATUS_ACCEPTED_202, 202);
        LOG.debug("Content - " + content);
    } finally {
        TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService);
    }
}

From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java

/**
 * @see DATAREST-423/*ww w  .  j a  va2  s  .  c o  m*/
 */
@Test
public void invokesCustomControllerAndBindsDomainObjectCorrectly() throws Exception {

    MockHttpServletResponse authorsResponse = client.request(client.discoverUnique("authors"));

    String authorUri = JsonPath.read(authorsResponse.getContentAsString(),
            "$._embedded.authors[0]._links.self.href");

    mvc.perform(delete(authorUri)).//
            andExpect(status().isIAmATeapot());
}

From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java

/**
 * Request for storing new object./*from  ww  w.  j a  v  a  2s . co  m*/
 * @throws Exception
 */
public void testSaveOperation() throws Exception {
    // Create dummy user object
    final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");

    // Create fixture data
    final List<Integer> createdItemIdList = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 1);
    // Set dummy user with the deletable list of items
    createdItemIdList.add(dummyUserId);

    try {
        final Subject subject = getSubjectFromASuccessfulRequest();
        // build mock request
        final MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRequestURI("/service/save/item.xml");
        request.setMethod(METHOD_POST);
        request.getSession().setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
        request.addParameter("item", fixContent());

        // Build mock response
        final MockHttpServletResponse response = new MockHttpServletResponse();

        // send request
        mRestfulController.handleRequest(request, response);

        // verify response
        final String content = response.getContentAsString();
        assertFalse("Response Content is empty", content.length() == 0);
        assertTrue("State is false.", content.indexOf("true") != -1);
        LOG.debug("Response - " + content);
    } finally {
        TestCaseRepositoryHelper.fixRemoveItems(mRepositoryService, createdItemIdList);
    }
}