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.SAML1ArtifactResolutionTest.java

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

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml1/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 . 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("saml1p:RequestDenied"));
}

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

@Test
public void verifyOK() throws Exception {
    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.revokeClientTokens(CLIENT_ID, CLIENT_SECRET)).thenReturn(true);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.REVOKE_URL);
    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.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//w w w .j  av  a 2s. c  o  m
    assertEquals(HttpStatus.SC_NO_CONTENT, mockResponse.getStatus());
    assertNull(mockResponse.getContentType());
    assertEquals("null", mockResponse.getContentAsString());
}

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

@Test
public void verifyHandleInternal() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", URL);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuth20ServiceValidateController oauth20ServiceValidateController = new OAuth20ServiceValidateController();
    final ModelAndView modelAndView = oauth20ServiceValidateController.handleRequestInternal(mockRequest,
            mockResponse);//from   www .j av  a  2s .c om
    assertNull(modelAndView);
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    assertEquals("", mockResponse.getContentAsString());
}

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

@Test
void refreshTokenGrantType_returnsIdToken_toOpenIdClients() throws Exception {
    when(timeService.getCurrentTimeMillis()).thenReturn(1000L);
    client = setUpClients("openidclient", "", "openid", "password,refresh_token", true);
    user = setUpUser("openiduser", "", OriginKeys.UAA, "uaa");
    CompositeToken tokenResponse = getTokensWithPasswordGrant(client.getClientId(), SECRET, user.getUserName(),
            SECRET, "localhost", "jwt");
    String refreshToken = tokenResponse.getRefreshToken().getValue();
    String originalIdTokenJwt = tokenResponse.getIdTokenValue();
    when(timeService.getCurrentTimeMillis()).thenReturn(5000L);

    MockHttpServletResponse refreshResponse = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            "localhost");

    assertEquals(HttpStatus.SC_OK, refreshResponse.getStatus());
    CompositeToken compositeToken = JsonUtils.readValue(refreshResponse.getContentAsString(),
            CompositeToken.class);
    String idTokenJwt = compositeToken.getIdTokenValue();
    assertRefreshIdTokenCorrect(originalIdTokenJwt, idTokenJwt);
}

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

@Test
void refreshTokenGrantType_returnsIdToken_toOpenIdClients_withOpaqueRefreshToken() throws Exception {
    when(timeService.getCurrentTimeMillis()).thenReturn(1000L);
    client = setUpClients("openidclient", "", "openid", "password,refresh_token", true);
    user = setUpUser("openiduser", "", OriginKeys.UAA, "uaa");
    CompositeToken tokenResponse = getTokensWithPasswordGrant(client.getClientId(), SECRET, user.getUserName(),
            SECRET, "localhost", "opaque");
    String refreshToken = tokenResponse.getRefreshToken().getValue();
    String originalIdTokenJwt = tokenResponse.getIdTokenValue();
    when(timeService.getCurrentTimeMillis()).thenReturn(5000L);

    MockHttpServletResponse refreshResponse = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            "localhost");

    assertEquals(HttpStatus.SC_OK, refreshResponse.getStatus());
    CompositeToken compositeToken = JsonUtils.readValue(refreshResponse.getContentAsString(),
            CompositeToken.class);
    String idTokenJwt = compositeToken.getIdTokenValue();
    assertRefreshIdTokenCorrect(originalIdTokenJwt, idTokenJwt);
}

From source file:net.node42.filter.SimpleTimeoutLoadLimitingFilterTest.java

@Test
public void testDestroy() throws Exception {
    final SimpleTimeoutLoadLimitingFilter target = new SimpleTimeoutLoadLimitingFilter();
    final MockFilterConfig filterConfig = new MockFilterConfig(new MockServletContext());
    filterConfig.addInitParameter("request_count_concurrent_max", "0");
    filterConfig.addInitParameter("request_count_check_interval", "200");
    filterConfig.addInitParameter("request_timeout", "10000");

    target.init(filterConfig);//from  w ww .  ja v  a 2 s  .co m
    assertThat(target.maxConcurrentRequests).isEqualTo(0);
    assertThat(target.requestCountCheckInterval).isEqualTo(200L);
    assertThat(target.requestTimeoutMillis).isEqualTo(10000);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    response.setWriterAccessAllowed(true);
    final FilterChain filterChain = mock(FilterChain.class);

    runLoadLimitingFilter(target, request, response, filterChain);
    assertThat(response.getContentLength()).isEqualTo(0); // Verify we haven't written a timeout message

    target.destroy();
    assertThat(target.DESTROY.get()).isEqualTo(true);
    await().atMost(5, TimeUnit.SECONDS).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return !response.getContentAsString().isEmpty();
        }
    });
    assertThat(response.getContentAsString()).isNotEmpty()
            .isEqualTo(SimpleTimeoutLoadLimitingFilter.CONTENT_TIMEOUT_DEFAULT);
}

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

/** Tests that the attribute query handler correctly fails out if the profile is not configured. */
public void testAuthenticationWithoutConfiguredQuery() throws Exception {
    AttributeQuery query = buildAttributeQuery("urn:example.org:BogusSP");
    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);/*  w w  w. j a v a  2s.  com*/

    // 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:Responder"));
    assertTrue(response.contains("saml1p:RequestDenied"));
}

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

public void testWithoutConfiguration() throws Exception {
    String relyingPartyId = "urn:example.org:BogusSP";
    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);//from   ww 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("urn:oasis:names:tc:SAML:2.0:status:RequestDenied"));
}

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

/** Tests that the attribute query handler correctly fails out if the profile is not configured. */
public void testAuthenticationWithoutConfiguredQuery() throws Exception {
    AttributeQuery query = buildAttributeQuery("urn:example.org:BogusSP");
    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 ww w .ja va 2 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("urn:oasis:names:tc:SAML:2.0:status:Responder"));
    assertTrue(response.contains("urn:oasis:names:tc:SAML:2.0:status:RequestDenied"));
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testExecGroovy() throws Exception {
    final String formatterName = configureGroovyTestFormatter();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();//w w w.j av  a  2 s  . co m
    request.addParameter("h2IdentInfo", "true");

    final MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
            new ServletWebRequest(request, response));
    final String viewString = response.getContentAsString();
    //        com.google.common.io.Files.write(viewString, new File("e:/tmp/view.html"), Constants.CHARSET);

    final Element view = Xml.loadString(viewString, false);
    assertEquals("html", view.getName());
    assertNotNull("body", view.getChild("body"));

    // Check that the "handlers.add 'gmd:abstract', { el ->" correctly applied
    assertElement(view, "body//p[@class = 'abstract']/span[@class='label']", "Abstract", 1);
    assertElement(view, "body//p[@class = 'abstract']/span[@class='value']", "Abstract {uuid}", 1);

    // Check that the "handlers.add ~/...:title/, { el ->" correctly applied
    assertElement(view, "body//p[@class = 'title']/span[@class='label']", "Title", 1);
    assertElement(view, "body//p[@class = 'title']/span[@class='value']", "Title", 1);

    // Check that the "handlers.withPath ~/[^>]+>gmd:identificationInfo>.*extent/, Iso19139Functions.&handleExtent" correctly applied
    assertElement(view, "body//p[@class = 'formatter']", "fromFormatterGroovy", 1);

    // Check that the "handlers.withPath ~/[^>]+>gmd:identificationInfo>.*extent/, Iso19139Functions.&handleExtent" correctly applied
    assertElement(view, "body//p[@class = 'shared']", "fromSharedFunctions", 1);

    // Check that the "handlers.add ~/...:title/, { el ->" correctly applied
    assertElement(view, "body//p[@class = 'code']/span[@class='label']", "Unique resource identifier", 1);
    assertElement(view, "body//p[@class = 'code']/span[@class='value']", "WGS 1984", 1);

    // Check that the handlers.add 'gmd:CI_OnlineResource', { el -> handler is applied
    assertElement(view, "body//p[@class = 'online-resource']/h3", "OnLine resource", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div/strong", "REPOM", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div[@class='desc']", "", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div[@class='linkage']/span[@class='label']",
            "URL:", 1);
    assertElement(view, "body//p[@class = 'online-resource']/div[@class='linkage']/span[@class='value']",
            "http://services.sandre.eaufrance.fr/geo/ouvrage", 1);

    // Check that the handler:
    //   handlers.add select: {el -> el.name() == 'gmd:identificationInfo' && f.param('h2IdentInfo').toBool()},
    //                processChildren: true, { el, childData ->
    // was applied
    assertElement(view, "*//div[@class = 'identificationInfo']/h2", "Data identification", 1);
    List<Element> identificationElements = (List<Element>) Xml.selectNodes(view,
            "*//div[@class = 'identificationInfo']/p");
    assertEquals(viewString, 4, identificationElements.size());
    assertEquals(viewString, "abstract", identificationElements.get(0).getAttributeValue("class"));
    assertEquals(viewString, "shared", identificationElements.get(1).getAttributeValue("class"));
    assertEquals(viewString, "block", identificationElements.get(2).getAttributeValue("class"));
    assertEquals(viewString, "block", identificationElements.get(3).getAttributeValue("class"));
    assertEquals(viewString, "block", identificationElements.get(3).getAttributeValue("class"));

    // Verify that handler
    // handlers.add name: 'codelist handler', select: isoHandlers.matchers.isCodeListEl, isoHandlers.isoCodeListEl
    // is handled
    assertElement(view, "body//span[@class = 'fileId']", this.uuid, 1);
    assertElement(view, "body//span[@class = 'creatorTranslated']", "Creator", 1);

    assertElement(view, "body//span[@class = 'extents']", "2", 1);

    assertNull(Xml.selectElement(view, "body//h1[text() = 'Reference System Information']"));
}