protected ScimUser updateUser(String token, int status, ScimUser user) throws Exception {
    MockHttpServletRequestBuilder put =
        put("/Users/" + user.getId())
            .header("Authorization", "Bearer " + token)
            .header("If-Match", "\"" + user.getVersion() + "\"")
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content(JsonUtils.writeValueAsBytes(user));
    if (status == HttpStatus.OK.value()) {
      String json =
          getMockMvc()
              .perform(put)
              .andExpect(status().isOk())
              .andExpect(header().string("ETag", "\"1\""))
              .andExpect(jsonPath("$.userName").value(user.getUserName()))
              .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
              .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
              .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()))
              .andReturn()
              .getResponse()
              .getContentAsString();

      return JsonUtils.readValue(json, ScimUser.class);
    } else {
      getMockMvc().perform(put).andExpect(status().is(status));
      return null;
    }
  }
 private void assertJoe(ScimUser joe) {
   assertNotNull(joe);
   assertEquals(JOE_ID, joe.getId());
   assertEquals("Joe", joe.getGivenName());
   assertEquals("User", joe.getFamilyName());
   assertEquals("*****@*****.**", joe.getPrimaryEmail());
   assertEquals("joe", joe.getUserName());
   assertEquals("+1-222-1234567", joe.getPhoneNumbers().get(0).getValue());
   assertNull(joe.getGroups());
 }
  @Test
  public void testDeleteUserWithUaaAdminToken() throws Exception {
    ScimUser user = setUpScimUser();

    getMockMvc()
        .perform(
            (delete("/Users/" + user.getId()))
                .header("Authorization", "Bearer " + uaaAdminToken)
                .contentType(APPLICATION_JSON)
                .content(JsonUtils.writeValueAsBytes(user)))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.userName").value(user.getUserName()))
        .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
        .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
        .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()));
  }
  @Test
  public void updateModifiesExpectedData() {
    ScimUser jo = new ScimUser(null, "josephine", "Jo", "NewUser");
    jo.addEmail("*****@*****.**");
    jo.setUserType(UaaAuthority.UAA_ADMIN.getUserType());

    ScimUser joe = db.update(JOE_ID, jo);

    // Can change username
    assertEquals("josephine", joe.getUserName());
    assertEquals("*****@*****.**", joe.getPrimaryEmail());
    assertEquals("Jo", joe.getGivenName());
    assertEquals("NewUser", joe.getFamilyName());
    assertEquals(1, joe.getVersion());
    assertEquals(JOE_ID, joe.getId());
    assertNull(joe.getGroups());
  }
 private ScimUser createUser(ScimUser user, String token, String subdomain, String switchZone)
     throws Exception {
   String password = hasText(user.getPassword()) ? user.getPassword() : "pas5word";
   user.setPassword(password);
   MvcResult result =
       createUserAndReturnResult(user, token, subdomain, switchZone)
           .andExpect(status().isCreated())
           .andExpect(header().string("ETag", "\"0\""))
           .andExpect(jsonPath("$.userName").value(user.getUserName()))
           .andExpect(jsonPath("$.emails[0].value").value(user.getUserName()))
           .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()))
           .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
           .andReturn();
   user = JsonUtils.readValue(result.getResponse().getContentAsString(), ScimUser.class);
   user.setPassword(password);
   return user;
 }
  // TODO: add cases for username no existing external user with username not email
  @Test
  public void accept_invitation_with_external_user_that_does_not_have_email_as_their_username() {
    String userId = "user-id-001";
    String email = "*****@*****.**";
    String actualUsername = "******";
    ScimUser userBeforeAccept = new ScimUser(userId, email, "first", "last");
    userBeforeAccept.setPrimaryEmail(email);
    userBeforeAccept.setOrigin(Origin.SAML);

    when(scimUserProvisioning.verifyUser(eq(userId), anyInt())).thenReturn(userBeforeAccept);
    when(scimUserProvisioning.retrieve(eq(userId))).thenReturn(userBeforeAccept);

    BaseClientDetails clientDetails =
        new BaseClientDetails("client-id", null, null, null, null, "http://example.com/redirect");
    when(clientDetailsService.loadClientByClientId("acmeClientId")).thenReturn(clientDetails);

    Map<String, String> userData = new HashMap<>();
    userData.put(USER_ID, userBeforeAccept.getId());
    userData.put(EMAIL, userBeforeAccept.getPrimaryEmail());
    userData.put(REDIRECT_URI, "http://someother/redirect");
    userData.put(CLIENT_ID, "acmeClientId");
    when(expiringCodeStore.retrieveCode(anyString()))
        .thenReturn(
            new ExpiringCode(
                "code",
                new Timestamp(System.currentTimeMillis()),
                JsonUtils.writeValueAsString(userData)));

    ScimUser userAfterAccept =
        new ScimUser(
            userId,
            actualUsername,
            userBeforeAccept.getGivenName(),
            userBeforeAccept.getFamilyName());
    userAfterAccept.setPrimaryEmail(email);

    when(scimUserProvisioning.verifyUser(eq(userId), anyInt())).thenReturn(userAfterAccept);

    ScimUser acceptedUser = emailInvitationsService.acceptInvitation("code", "password").getUser();
    assertEquals(userAfterAccept.getUserName(), acceptedUser.getUserName());
    assertEquals(userAfterAccept.getName(), acceptedUser.getName());
    assertEquals(userAfterAccept.getPrimaryEmail(), acceptedUser.getPrimaryEmail());

    verify(scimUserProvisioning).verifyUser(eq(userId), anyInt());
  }
  @Test
  public void noOverrideByDefault() throws Exception {
    UaaUser joe = new UaaUser("joe", "password", "*****@*****.**", "Joe", "User");
    joe = joe.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("openid,read"));
    ScimUserBootstrap bootstrap = new ScimUserBootstrap(db, gdb, mdb, Arrays.asList(joe));
    bootstrap.afterPropertiesSet();
    joe = new UaaUser("joe", "password", "*****@*****.**", "Joel", "User");
    bootstrap = new ScimUserBootstrap(db, gdb, mdb, Arrays.asList(joe));
    bootstrap.afterPropertiesSet();
    @SuppressWarnings("unchecked")
    Collection<Map<String, Object>> users =
        (Collection<Map<String, Object>>)
            userEndpoints.findUsers("id", "id pr", "id", "ascending", 1, 100).getResources();
    assertEquals(1, users.size());

    String id = (String) users.iterator().next().get("id");
    ScimUser user = userEndpoints.getUser(id, new MockHttpServletResponse());
    // uaa.user is always added
    assertEquals("Joe", user.getGivenName());
  }
  @Test
  public void testUpdateUserInOtherZoneWithUaaAdminToken() throws Exception {
    IdentityZone identityZone = getIdentityZone();
    ScimUser user = setUpScimUser(identityZone);
    user.setName(new ScimUser.Name("changed", "name"));

    getMockMvc()
        .perform(
            put("/Users/" + user.getId())
                .header("Authorization", "Bearer " + uaaAdminToken)
                .header(IdentityZoneSwitchingFilter.HEADER, identityZone.getId())
                .header("If-Match", "\"" + user.getVersion() + "\"")
                .contentType(APPLICATION_JSON)
                .content(JsonUtils.writeValueAsBytes(user)))
        .andExpect(status().isOk())
        .andExpect(header().string("ETag", "\"1\""))
        .andExpect(jsonPath("$.userName").value(user.getUserName()))
        .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
        .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
        .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()));
  }