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.ideabase.repository.test.webservice.RESTfulControllerTest.java

public void testGetItemInPHPResponse() throws Exception {
    final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setRequestURI("/service/get/" + userId + ".php");
    request.setMethod(METHOD_GET);/*from  w w  w  .  ja  va  2s . c  o m*/

    // fix login state
    final Subject subject = getSubjectFromASuccessfulRequest();
    final MockHttpSession session = new MockHttpSession();
    session.setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    request.setSession(session);

    // execute action
    final ModelAndView modelAndView = mRestfulController.handleRequest(request, response);

    // verify response
    final String responseContent = response.getContentAsString();
    assertNotNull(responseContent);
    LOG.debug("Response content - " + responseContent);
}

From source file:org.wrml.server.WrmlServletTest.java

@Test
public void requestWithBadHostHeader() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, CAPRICA_SIX_ENDPOINT);
    request.setMethod(Method.Get.getProtocolGivenName());
    //request.addHeader(HttpHeaders.ACCEPT, JSON_MEDIA_TYPE);
    request.addHeader(WrmlServlet.WRML_HOST_HEADER_NAME, BAD_HOST_1);

    MockHttpServletResponse response = new MockHttpServletResponse();

    initMockWrmlRequest(request, Method.Get, CAPRICA_SIX_ENDPOINT, CAPRICA_SCHEMA_URI);

    _Servlet.service(request, response);

    // Verify Model Write
    Assert.assertTrue(response.getContentType().contains("text/plain"));
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
    Assert.assertTrue(response.getContentLength() > 0);
    Assert.assertTrue(response.getContentAsString().contains("moose::/squirrel:"));
}

From source file:org.jasig.cas.support.oauth.web.OAuth20MetadataPrincipalControllerTests.java

@Test
public void verifyInvalidAccessToken() throws Exception {
    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(AT_ID, AccessToken.class)).thenThrow(new InvalidTokenException("error"));
    when(centralOAuthService.getPersonalAccessToken(AT_ID)).thenReturn(null);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.PROFILE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, AT_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//w  w w  . ja  v  a  2  s .  c  o m
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.UNAUTHORIZED_REQUEST
            + "\",\"error_description\":\"" + OAuthConstants.INVALID_ACCESS_TOKEN_DESCRIPTION + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenRefreshTokenControllerTests.java

@Test
public void verifyOK() throws Exception {
    final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class);
    when(ticketGrantingTicket.getCreationTime()).thenReturn(new Date().getTime());

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);

    final RefreshToken refreshToken = mock(RefreshToken.class);
    when(refreshToken.getId()).thenReturn(RT_ID);

    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(AT_ID);
    when(accessToken.getTicket()).thenReturn(ticketGrantingTicket);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(RT_ID, RefreshToken.class)).thenReturn(refreshToken);
    when(centralOAuthService.getRegisteredService(CLIENT_ID)).thenReturn(service);
    when(centralOAuthService.grantOfflineAccessToken(refreshToken)).thenReturn(accessToken);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.REFRESH_TOKEN);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, RT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.setTimeout(TIMEOUT);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);/* w w  w  .j  a v a  2s  .c o m*/
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();
    final String expected = "{\"token_type\":\"" + OAuthConstants.BEARER_TOKEN + "\",\"expires_in\":\""
            + TIMEOUT + "\",\"refresh_token\":\"" + RT_ID + "\",\"access_token\":\"" + AT_ID + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("token_type").asText(), receivedObj.get("token_type").asText());
    assertTrue("received expires_at greater or equal to expected",
            expectedObj.get("expires_in").asInt() >= receivedObj.get("expires_in").asInt());
    assertEquals(expectedObj.get("access_token").asText(), receivedObj.get("access_token").asText());
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtilTest.java

/**
 * @see AtomFeedUtil#getAtomFeedStream(java.io.OutputStream, java.util.Date)
 * @verifies download partial stream by given date
 *//* w  w w.  j ava 2  s  . c o  m*/
@Test
public void getAtomFeedStream_shouldDownloadPartialStreamByGivenDate() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    // if atom feed file exists, just get rid of it 
    File feedFile = AtomFeedUtil.getFeedEntriesFile();
    if (feedFile.exists()) {
        feedFile.delete();
    }
    // write couple of entries to atom feed 
    AtomFeedUtil.writeToFeed("test1", new Encounter());
    AtomFeedUtil.writeToFeed("test2", new Patient());
    // do some sleep to have asOfDate parameter for filtering entries
    Calendar asOfDate = Calendar.getInstance();
    Thread.sleep(1500);
    // add another entries (ones which will be filtered to stream)
    AtomFeedUtil.writeToFeed("test3", new Encounter());
    AtomFeedUtil.writeToFeed("test4", new Patient());

    AtomFeedUtil.getAtomFeedStream(response.getOutputStream(), asOfDate.getTime());

    // get response content to use it when asserting
    String responseContent = response.getContentAsString();

    // test if response contains header file content
    String atomHeader = FileUtils.readFileToString(AtomFeedUtil.getFeedHeaderFile());
    // truncate "</feed>" from the atom header string
    if (StringUtils.isNotBlank(atomHeader)) {
        atomHeader = StringUtils.substringBeforeLast(atomHeader, "</feed>");
    }
    Assert.assertTrue(StringUtils.contains(responseContent, atomHeader));

    // test that response content also contains both entries, added after sleep
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test3</action>"));
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test4</action>"));

    // test that response content also contains both entries, added after sleep
    Assert.assertFalse(StringUtils.contains(responseContent, "<action>test1</action>"));
    Assert.assertFalse(StringUtils.contains(responseContent, "<action>test2</action>"));

    // test that response content also contains closing tag </feed>
    Assert.assertTrue(StringUtils.endsWith(responseContent, "</feed>"));

}

From source file:org.jasig.cas.support.oauth.web.OAuth20ProfileControllerTests.java

@Test
public void verifyOKWithPersonalToken() throws Exception {
    final Map<String, Object> map = new HashMap<>();
    map.put(NAME, VALUE);//from  w  ww.j  av a2 s  .  c  om
    final List<String> list = Arrays.asList(VALUE, VALUE);
    map.put(NAME2, list);

    final Principal principal = mock(Principal.class);
    when(principal.getId()).thenReturn(ID);
    when(principal.getAttributes()).thenReturn(map);

    final Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn(principal);

    final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class);
    when(ticketGrantingTicket.isExpired()).thenReturn(false);
    when(ticketGrantingTicket.getAuthentication()).thenReturn(authentication);

    final Service service = new SimpleWebApplicationServiceImpl("id");

    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(AT_ID);
    when(accessToken.getType()).thenReturn(TokenType.PERSONAL);
    when(accessToken.getService()).thenReturn(service);
    when(accessToken.getTicketGrantingTicket()).thenReturn(ticketGrantingTicket);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(AT_ID, AccessToken.class)).thenReturn(accessToken);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.PROFILE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, AT_ID);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"id\":\"" + ID + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("id").asText(), receivedObj.get("id").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyNoCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);/*from w w w. ja va 2s.  c o m*/
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + new InvalidParameterException(OAuthConstants.CODE).getMessage() + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

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

public void testGetTermTagCloudByQuery() throws Exception {
    // create some dummy data
    TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 5);

    final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan");
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();

    // set http request parameters
    request.setRequestURI("/service/tagcloud/query.xml");
    request.setMethod(METHOD_GET);//from w w w.j  a va 2 s  .  c  om
    request.setParameter("query", "name:fox");
    request.setParameter("max", "50");
    request.setParameter("select", "name");

    // fix login state
    final Subject subject = getSubjectFromASuccessfulRequest();
    final MockHttpSession session = new MockHttpSession();
    session.setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject);
    request.setSession(session);

    final ModelAndView modelAndView = mRestfulController.handleRequest(request, response);

    // verify response
    final String responseContent = response.getContentAsString();
    assertNotNull(responseContent);
    LOG.debug("Response content - " + responseContent);
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyNoClientId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);// ww w. j a va  2 s  .  com
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + new InvalidParameterException(OAuthConstants.CLIENT_ID).getMessage() + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenAuthorizationCodeControllerTests.java

@Test
public void verifyNoRedirectUri() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from  ww  w. java  2  s.  co  m
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("application/json", mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\""
            + new InvalidParameterException(OAuthConstants.REDIRECT_URI).getMessage() + "\"}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());
    assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText());
    assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText());
}