Example usage for org.springframework.mock.web MockHttpServletResponse getCookies

List of usage examples for org.springframework.mock.web MockHttpServletResponse getCookies

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getCookies.

Prototype

public Cookie[] getCookies() 

Source Link

Usage

From source file:org.jasig.cas.web.flow.SendTicketGrantingTicketActionTests.java

@Test
public void testTgtToSet() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final String TICKET_VALUE = "test";

    WebUtils.putTicketGrantingTicketInRequestScope(this.context, TICKET_VALUE);
    this.context.setExternalContext(
            new ServletExternalContext(new MockServletContext(), new MockHttpServletRequest(), response));

    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(TICKET_VALUE, response.getCookies()[0].getValue());
}

From source file:org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection.java

public WebResponse getResponse(WebRequest webRequest) throws IOException {
    long startTime = System.currentTimeMillis();
    HtmlUnitRequestBuilder requestBuilder = new HtmlUnitRequestBuilder(this.sessions, this.webClient,
            webRequest);/*from  w  w  w .jav  a2  s .  co m*/
    requestBuilder.setContextPath(this.contextPath);

    MockHttpServletResponse httpServletResponse = getResponse(requestBuilder);
    String forwardedUrl = httpServletResponse.getForwardedUrl();
    while (forwardedUrl != null) {
        requestBuilder.setForwardPostProcessor(new ForwardRequestPostProcessor(forwardedUrl));
        httpServletResponse = getResponse(requestBuilder);
        forwardedUrl = httpServletResponse.getForwardedUrl();
    }
    storeCookies(webRequest, httpServletResponse.getCookies());

    return new MockWebResponseBuilder(startTime, webRequest, httpServletResponse).build();
}

From source file:org.jasig.cas.web.flow.SendTicketGrantingTicketActionTests.java

@Test
public void testTgtToSetRemovingOldTgt() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String TICKET_VALUE = "test";
    request.setCookies(new Cookie[] { new Cookie("TGT", "test5") });
    WebUtils.putTicketGrantingTicketInRequestScope(this.context, TICKET_VALUE);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(TICKET_VALUE, response.getCookies()[0].getValue());
}

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

/** Tests second leg of the SSO request where request returns to SSO handler and AuthN statement is generated. */
public void testSecondAuthenticationLeg() throws Exception {
    MockServletContext servletContext = new MockServletContext();
    MockHttpServletRequest servletRequest = buildServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

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

    HttpServletHelper.bindLoginContext(buildLoginContext(), handler.getStorageService(), servletContext,
            servletRequest, servletResponse);
    servletRequest.setCookies(servletResponse.getCookies());

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

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("action=\"https://example.org/mySP\" method=\"post\""));
    assertTrue(response.contains("name=\"TARGET\" value=\"https://example.org/mySP\""));
    assertTrue(response.contains("SAMLResponse"));
}

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

/** Tests second leg of the SSO request where request returns to SSO handler and AuthN statement is generated. */
public void testSecondAuthenticationLeg() throws Exception {
    MockServletContext servletContext = new MockServletContext();
    MockHttpServletRequest servletRequest = buildServletRequest("urn:example.org:sp1");
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    AbstractShibbolethProfileHandler handler = (AbstractShibbolethProfileHandler) handlerManager
            .getProfileHandler(servletRequest);
    assertNotNull(handler);//from w  ww . j a  v  a  2  s .c  o  m

    HttpServletHelper.bindLoginContext(buildLoginContext("urn:example.org:sp1"), handler.getStorageService(),
            servletContext, servletRequest, servletResponse);
    servletRequest.setCookies(servletResponse.getCookies());

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

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("action=\"https://example.org/mySP\" method=\"post\""));
    assertTrue(response.contains("SAMLResponse"));
}

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

/** Tests initial leg of the SSO request where request is decoded and sent to the authentication engine. */
public void testFirstAuthenticationLeg() throws Exception {
    MockServletContext servletContext = new MockServletContext();

    MockHttpServletRequest servletRequest = buildServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    AbstractShibbolethProfileHandler handler = (AbstractShibbolethProfileHandler) handlerManager
            .getProfileHandler(servletRequest);
    assertNotNull(handler);//from   w  ww.j ava2 s. c  om

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

    servletRequest.setCookies(servletResponse.getCookies());
    ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) HttpServletHelper
            .getLoginContext(handler.getStorageService(), servletContext, servletRequest);

    assertNotNull(loginContext);
    assertEquals(false, loginContext.getAuthenticationAttempted());
    assertEquals(false, loginContext.isForceAuthRequired());
    assertEquals(false, loginContext.isPassiveAuthRequired());
    assertEquals("/AuthnEngine", loginContext.getAuthenticationEngineURL());
    assertEquals("/shibboleth/SSO", loginContext.getProfileHandlerURL());
    assertEquals("urn:example.org:sp1", loginContext.getRelyingPartyId());
    assertEquals(0, loginContext.getRequestedAuthenticationMethods().size());
    assertEquals("https://example.org/mySP", loginContext.getSpAssertionConsumerService());
    assertEquals("https://example.org/mySP", loginContext.getSpAssertionConsumerService());

    assertTrue(servletResponse.getRedirectedUrl().endsWith("/AuthnEngine"));
}

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

/** Tests initial leg of the SSO request where request is decoded and sent to the authentication engine. */
public void testFirstAuthenticationLeg() throws Exception {
    MockServletContext servletContext = new MockServletContext();

    MockHttpServletRequest servletRequest = buildServletRequest("urn:example.org:sp1");
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    AbstractShibbolethProfileHandler handler = (AbstractShibbolethProfileHandler) handlerManager
            .getProfileHandler(servletRequest);
    assertNotNull(handler);//from w ww.j  ava2 s. co m

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

    servletRequest.setCookies(servletResponse.getCookies());
    Saml2LoginContext loginContext = (Saml2LoginContext) HttpServletHelper
            .getLoginContext(handler.getStorageService(), servletContext, servletRequest);

    assertNotNull(loginContext);
    assertEquals(false, loginContext.getAuthenticationAttempted());
    assertEquals(false, loginContext.isForceAuthRequired());
    assertEquals(false, loginContext.isPassiveAuthRequired());
    assertEquals("/AuthnEngine", loginContext.getAuthenticationEngineURL());
    assertEquals("/saml2/POST/SSO", loginContext.getProfileHandlerURL());
    assertEquals("urn:example.org:sp1", loginContext.getRelyingPartyId());
    assertEquals(0, loginContext.getRequestedAuthenticationMethods().size());

    assertTrue(servletResponse.getRedirectedUrl().endsWith("/AuthnEngine"));
}

From source file:com.nominanuda.web.http.ServletHelperTest.java

@Test
public void shouldAddCookiesOnServletHttpResponseWhenHeaderSetCookie() throws IOException {
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    HttpResponse response = new BasicHttpResponse(new HttpCoreHelper().statusLine(200));
    Header[] headers = new Header[2];
    headers[0] = new BasicHeader("Set-Cookie",
            "etalia=dGltZXN0YW1wPTEzMzE4ODQxxNzE4ODc.dXNlcm5hbWU9bHVjYQ.Y3JlYXRlZF9hdD0xxMzMxxODg0MTcxxODg3.cGFzc3dvcmQ9b0Z2WWtNU0dqcUdBZjRWa0JWMGZ1bmZHdW9F.Y29uZmlybV9hY2s9MDg0ZGM3ZTItM2VlMC00NWNkLWI2NmQtZGVmZTlmM2E5NTRm;Domain=localhost;Path=/;Expires=Mon, 02-Apr-2012 10:30:00 GMT");
    headers[1] = new BasicHeader("Set-Cookie",
            "etalia_hash=4bYEnD7APP19SKPlf1x1IDrPzNY0;Domain=localhost;Path=/;Expires=Mon, 02-Apr-2012 10:30:00 GMT");
    response.setHeaders(headers);// w  ww.  j a va  2 s  .  c  om

    servletHelper.copyResponse(response, servletResponse);

    Cookie[] cookies = servletResponse.getCookies();

    assertEquals(2, cookies.length);

    assertEquals("/", cookies[0].getPath());
    assertEquals("localhost", cookies[0].getDomain());
    assertNotSame(0, cookies[0].getMaxAge());

    assertEquals("/", cookies[1].getPath());
    assertEquals("localhost", cookies[1].getDomain());
    assertNotSame(0, cookies[1].getMaxAge());
}

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

@SuppressWarnings("unchecked")
private MockMvcResponse performRequest(MockHttpServletRequestBuilder requestBuilder) {
    MockHttpServletResponse response;

    if (interceptor != null) {
        interceptor.intercept(requestBuilder);
    }//from  w  w w.  java 2s  . co m

    if (isSpringSecurityInClasspath()
            && authentication instanceof org.springframework.security.core.Authentication) {
        org.springframework.security.core.context.SecurityContextHolder.getContext()
                .setAuthentication((org.springframework.security.core.Authentication) authentication);
    } else if (authentication instanceof Principal) {
        requestBuilder.principal((Principal) authentication);
    }

    for (RequestPostProcessor requestPostProcessor : requestPostProcessors) {
        requestBuilder.with(requestPostProcessor);
    }

    MockMvcRestAssuredResponseImpl restAssuredResponse;
    try {
        final long start = System.currentTimeMillis();
        ResultActions perform = mockMvc.perform(requestBuilder);
        final long responseTime = System.currentTimeMillis() - start;
        if (!resultHandlers.isEmpty()) {
            for (ResultHandler resultHandler : resultHandlers) {
                perform.andDo(resultHandler);
            }
        }
        MvcResult mvcResult = getMvcResult(perform, isAsyncRequest);
        response = mvcResult.getResponse();
        restAssuredResponse = new MockMvcRestAssuredResponseImpl(perform, logRepository);
        restAssuredResponse.setConfig(ConfigConverter.convertToRestAssuredConfig(config));
        restAssuredResponse.setContent(response.getContentAsByteArray());
        restAssuredResponse.setContentType(response.getContentType());
        restAssuredResponse.setHasExpectations(false);
        restAssuredResponse.setStatusCode(response.getStatus());
        restAssuredResponse.setResponseHeaders(assembleHeaders(response));
        restAssuredResponse.setRpr(getRpr());
        restAssuredResponse.setStatusLine(assembleStatusLine(response, mvcResult.getResolvedException()));
        restAssuredResponse.setFilterContextProperties(new HashMap() {
            {
                put(TimingFilter.RESPONSE_TIME_MILLISECONDS, responseTime);
            }
        });
        restAssuredResponse.setCookies(convertCookies(response.getCookies()));

        if (responseSpecification != null) {
            responseSpecification.validate(ResponseConverter.toStandardResponse(restAssuredResponse));
        }

    } catch (Exception e) {
        return SafeExceptionRethrower.safeRethrow(e);
    } finally {
        if (isSpringSecurityInClasspath()) {
            org.springframework.security.core.context.SecurityContextHolder.clearContext();
        }
    }
    return restAssuredResponse;
}

From source file:org.jasig.portal.portlet.container.services.PortletCookieServiceImplTest.java

/**
 * Control test invocation of {@link PortletCookieServiceImpl#updatePortalCookie(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
 *///from  w ww  .  j ava 2s .c  o  m
@Test
public void testUpdatePortletCookieControl() {
    IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class);

    MockPortalCookie portalCookie = new MockPortalCookie();
    portalCookie.setValue("ABCDEF");
    EasyMock.expect(portletCookieDao.createPortalCookie(PortletCookieServiceImpl.DEFAULT_MAX_AGE))
            .andReturn(portalCookie);
    EasyMock.expect(portletCookieDao.updatePortalCookieExpiration(portalCookie,
            PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie);
    EasyMock.replay(portletCookieDao);

    PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl();
    cookieService.setPortletCookieDao(portletCookieDao);

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    cookieService.updatePortalCookie(request, response);

    Cookie[] cookies = response.getCookies();
    Assert.assertNotNull(cookies);
    Assert.assertEquals(1, cookies.length);
    EasyMock.verify(portletCookieDao);
}