Example usage for org.springframework.mock.web MockHttpSession setAttribute

List of usage examples for org.springframework.mock.web MockHttpSession setAttribute

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpSession setAttribute.

Prototype

@Override
    public void setAttribute(String name, @Nullable Object value) 

Source Link

Usage

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testWelcomeEmailEventForRetail() {
    // Sign up for manual activation account type
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getDefaultSelfRegistrationAccountType();
    BindingResult result = null;/*  w  w w .  j  a  v  a 2  s . c o m*/
    try {
        result = setupRegistration(disposition, registration);
    } catch (Exception e) {
        e.printStackTrace();
    }
    beforeRegisterCall(mockRequest, registration);
    controller.register(registration, result, "abc", "abc", map, null, status, mockRequest);
    // Tenant Activation Event
    // Assert.assertEquals(1, eventListener.getEvents().size());
    // PortalEvent tenantActivationEvent = eventListener.getEvents().get(0);
    // Assert.assertTrue(tenantActivationEvent.getPayload() instanceof TenantActivation);
    eventListener.clear();
    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute("regAuth", auth);
    mockSession.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, mockSession);
    // Since tenant is at activated, we will get Email Verified event
    Assert.assertEquals(1, eventListener.getEvents().size());
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testWelcomeEmailAndActivationEmailEventsForRetail() {
    // Sign up for manual activation account type
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getDefaultSelfRegistrationAccountType();
    BindingResult result = null;// w ww.j  a v  a 2  s .c o  m
    try {
        result = setupRegistration(disposition, registration);
    } catch (Exception e) {
        e.printStackTrace();
    }
    beforeRegisterCall(mockRequest, registration);
    controller.register(registration, result, "abc", "abc", map, null, status, mockRequest);
    // Tenant Activation Event
    // Assert.assertEquals(1, eventListener.getEvents().size());
    // PortalEvent tenantActivationEvent = eventListener.getEvents().get(0);
    // Assert.assertTrue(tenantActivationEvent.getPayload() instanceof TenantActivation);
    eventListener.clear();
    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute("regAuth", auth);
    mockSession.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, mockSession);
    // Since tenant is at activated, we will get only Welcome email and ActivationEmail events
    Assert.assertEquals(1, eventListener.getEvents().size());
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testEmailVerifiedEventForManualActivationAccountType() {
    // Sign up for manual activation account type
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    List<AccountType> accountTypes = accountTypeDAO.getManualRegistrationAccountTypes();
    AccountType disposition = null;/*  www . j a  v  a  2s  .c  o  m*/
    for (AccountType accountType : accountTypes) {
        if (accountType.isManualActivation()) {
            disposition = accountType;
        }
    }
    BindingResult result = null;
    try {
        result = setupRegistration(disposition, registration);
    } catch (Exception e) {
        e.printStackTrace();
    }
    beforeRegisterCall(mockRequest, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, mockRequest);
    Assert.assertEquals("register.registration_success", view);
    Assert.assertTrue(status.isComplete());
    verifyRegistration(disposition, registration.getUser(), registration.getTenant());
    Assert.assertEquals(registration.getTenant().getObject(),
            ((com.citrix.cpbm.access.Tenant) map.get("tenant")).getObject());
    // account activation request event
    Assert.assertEquals(2, eventListener.getEvents().size());
    PortalEvent verifyEmailRequest = eventListener.getEvents().get(0);
    Assert.assertTrue(verifyEmailRequest.getPayload() instanceof VerifyEmailRequest);
    eventListener.clear();
    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute("regAuth", auth);
    mockSession.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, mockSession);
    // Since tenant is not at activated, we will get only Welcome email
    Assert.assertEquals(1, eventListener.getEvents().size());
    PortalEvent event = eventListener.getEvents().get(0);
    Assert.assertTrue(event.getPayload() instanceof EmailVerified);
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testWelcomeEmailAndActivationEmailEventsForCorporate() {
    // Sign up for manual activation account type
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    List<AccountType> accountTypes = accountTypeDAO.getManualRegistrationAccountTypes();
    AccountType disposition = null;/*from  w  w  w  .j  a  v  a2  s.  c  om*/
    for (AccountType accountType : accountTypes) {
        if (accountType.isManualActivation()) {
            disposition = accountType;
        }
    }
    BindingResult result = null;
    try {
        result = setupRegistration(disposition, registration);
    } catch (Exception e) {
        e.printStackTrace();
    }
    beforeRegisterCall(mockRequest, registration);
    controller.register(registration, result, "abc", "abc", map, null, status, mockRequest);
    // Tenant Activation Event
    // Assert.assertEquals(1, eventListener.getEvents().size());
    // PortalEvent accountActivationRequestEvent = eventListener.getEvents().get(0);
    // Assert.assertTrue(accountActivationRequestEvent.getPayload() instanceof AccountActivationRequestEvent);
    eventListener.clear();

    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute("regAuth", auth);
    mockSession.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, mockSession);
    // Since tenant is at activated, we will get EmailVerified Event
    Assert.assertEquals(1, eventListener.getEvents().size());
    eventListener.clear();

    Tenant tennt = tenantService.get(registration.getTenant().getUuid());
    completeBusinessTransactionsForTenant(tennt);
    tenantService.changeState(registration.getTenant().getUuid(), "ACTIVE", null, "Manual");
    PortalEvent tenantActivationEvent = eventListener.getEvents().get(0);
    Assert.assertTrue(tenantActivationEvent.getPayload() instanceof TenantActivation);
    eventListener.clear();
}

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

@Test
public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenLenientWhenAppNotApproved() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";
    setUpClients(clientId, scopes, scopes, "authorization_code", false);
    String username = "testuser" + generator.generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    authorizationRequest.setClientId(clientId);
    authorizationRequest.setRedirectUri(TEST_REDIRECT_URI);
    authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid")));
    authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token")));
    authorizationRequest.setState(state);

    session.setAttribute("authorizationRequest", authorizationRequest);

    MvcResult result = getMockMvc()/*w  w w .j av a2 s.  c o  m*/
            .perform(post("/oauth/authorize").session(session).with(cookieCsrf())
                    .param(OAuth2Utils.USER_OAUTH_APPROVAL, "true").param("scope.0", "openid"))
            .andExpect(status().is3xxRedirection()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    assertNotNull(query.get("code"));
    String code = ((List<String>) query.get("code")).get(0);
    assertNotNull(code);
}

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

@Test
public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenStrictWhenAppNotApproved() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";
    setUpClients(clientId, scopes, scopes, "authorization_code", false);
    String username = "testuser" + generator.generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    authorizationRequest.setClientId(clientId);
    authorizationRequest.setRedirectUri(TEST_REDIRECT_URI);
    authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid")));
    authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token")));
    authorizationRequest.setState(state);
    session.setAttribute("authorizationRequest", authorizationRequest);

    MvcResult result = getMockMvc()//from   w  w w.  j  ava2s.co  m
            .perform(post("/oauth/authorize").session(session).param(OAuth2Utils.USER_OAUTH_APPROVAL, "true")
                    .with(cookieCsrf()).param("scope.0", "openid"))
            .andExpect(status().is3xxRedirection()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    assertNotNull(query.get("id_token"));
    assertNotNull(((List) query.get("id_token")).get(0));
    assertNotNull(((List) query.get("code")).get(0));
    assertNull(query.get("token"));
}

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

public void setAuthentication(MockHttpSession session, ScimUser developer) {
    UaaPrincipal p = new UaaPrincipal(developer.getId(), developer.getUserName(), developer.getPrimaryEmail(),
            OriginKeys.UAA, "", IdentityZoneHolder.get().getId());
    UaaAuthentication auth = new UaaAuthentication(p, UaaAuthority.USER_AUTHORITIES,
            new UaaAuthenticationDetails(false, "clientId", OriginKeys.ORIGIN, "sessionId"));
    Assert.assertTrue(auth.isAuthenticated());
    SecurityContextHolder.getContext().setAuthentication(auth);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            new MockSecurityContext(auth));
}

From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static MockHttpSession getSavedRequestSession() {
    MockHttpSession session = new MockHttpSession();
    SavedRequest savedRequest = new MockSavedRequest();
    session.setAttribute(SAVED_REQUEST_SESSION_ATTRIBUTE, savedRequest);
    return session;
}

From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static String getUserOAuthAccessTokenAuthCode(MockMvc mockMvc, String clientId, String clientSecret,
        String userId, String username, String password, String scope) throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(
            org.apache.commons.codec.binary.Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    UaaPrincipal p = new UaaPrincipal(userId, username, "test@test.org", OriginKeys.UAA, "",
            IdentityZoneHolder.get().getId());
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(p, "",
            UaaAuthority.USER_AUTHORITIES);
    Assert.assertTrue(auth.isAuthenticated());

    SecurityContextHolder.getContext().setAuthentication(auth);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            new MockSecurityContext(auth));

    String state = new RandomValueStringGenerator().generate();
    MockHttpServletRequestBuilder authRequest = get("/oauth/authorize")
            .header("Authorization", basicDigestHeaderValue).header("Accept", MediaType.APPLICATION_JSON_VALUE)
            .session(session).param(OAuth2Utils.GRANT_TYPE, "authorization_code")
            .param(OAuth2Utils.RESPONSE_TYPE, "code")
            .param(TokenConstants.REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE).param(OAuth2Utils.STATE, state)
            .param(OAuth2Utils.CLIENT_ID, clientId).param(OAuth2Utils.REDIRECT_URI, "http://localhost/test");
    if (StringUtils.hasText(scope)) {
        authRequest.param(OAuth2Utils.SCOPE, scope);
    }// w  ww.ja v a 2  s  .com

    MvcResult result = mockMvc.perform(authRequest).andExpect(status().is3xxRedirection()).andReturn();
    String location = result.getResponse().getHeader("Location");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(location);
    String code = builder.build().getQueryParams().get("code").get(0);

    authRequest = post("/oauth/token").header("Authorization", basicDigestHeaderValue)
            .header("Accept", MediaType.APPLICATION_JSON_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.RESPONSE_TYPE, "token")
            .param("code", code).param(OAuth2Utils.CLIENT_ID, clientId)
            .param(OAuth2Utils.REDIRECT_URI, "http://localhost/test");
    if (StringUtils.hasText(scope)) {
        authRequest.param(OAuth2Utils.SCOPE, scope);
    }
    result = mockMvc.perform(authRequest).andExpect(status().is2xxSuccessful()).andReturn();
    InjectedMockContextTest.OAuthToken oauthToken = JsonUtils
            .readValue(result.getResponse().getContentAsString(), InjectedMockContextTest.OAuthToken.class);
    return oauthToken.accessToken;

}