Search in sources :

Example 31 with Attribute

use of io.jans.scim.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class Scim2PatchService method applyPatchOperation.

public BaseScimResource applyPatchOperation(BaseScimResource resource, PatchOperation operation) throws Exception {
    BaseScimResource result = null;
    Map<String, Object> genericMap = null;
    PatchOperationType opType = operation.getType();
    Class<? extends BaseScimResource> clazz = resource.getClass();
    String path = operation.getPath();
    log.debug("applyPatchOperation of type {}", opType);
    // Determine if operation is with value filter
    if (StringUtils.isNotEmpty(path) && !operation.getType().equals(PatchOperationType.ADD)) {
        Pair<Boolean, String> pair = validateBracketedPath(path);
        if (pair.getFirst()) {
            String valSelFilter = pair.getSecond();
            if (valSelFilter == null)
                throw new SCIMException("Unexpected syntax in value selection filter");
            else {
                int i = path.indexOf("[");
                String attribute = path.substring(0, i);
                i = path.lastIndexOf("].");
                String subAttribute = i == -1 ? "" : path.substring(i + 2);
                // Abort earlier
                return applyPatchOperationWithValueFilter(resource, operation, valSelFilter, attribute, subAttribute);
            }
        }
    }
    if (!opType.equals(PatchOperationType.REMOVE)) {
        Object value = operation.getValue();
        List<String> extensionUrns = extService.getUrnsOfExtensions(clazz);
        if (value instanceof Map)
            genericMap = IntrospectUtil.strObjMap(value);
        else {
            // It's an atomic value or an array
            if (StringUtils.isEmpty(path))
                throw new SCIMException("Value(s) supplied for resource not parseable");
            // Create a simple map and trim the last part of path
            String[] subPaths = ScimResourceUtil.splitPath(path, extensionUrns);
            genericMap = Collections.singletonMap(subPaths[subPaths.length - 1], value);
            if (subPaths.length == 1)
                path = "";
            else
                path = path.substring(0, path.lastIndexOf("."));
        }
        if (StringUtils.isNotEmpty(path)) {
            // Visit backwards creating a composite map
            String[] subPaths = ScimResourceUtil.splitPath(path, extensionUrns);
            for (int i = subPaths.length - 1; i >= 0; i--) {
                // Create a string consisting of all subpaths until the i-th
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j <= i; j++) sb.append(subPaths[j]).append(".");
                Attribute annot = IntrospectUtil.getFieldAnnotation(sb.substring(0, sb.length() - 1), clazz, Attribute.class);
                boolean multivalued = !(annot == null || annot.multiValueClass().equals(NullType.class));
                Map<String, Object> genericBiggerMap = new HashMap<String, Object>();
                genericBiggerMap.put(subPaths[i], multivalued ? Collections.singletonList(genericMap) : genericMap);
                genericMap = genericBiggerMap;
            }
        }
        log.debug("applyPatchOperation. Generating a ScimResource from generic map: {}", genericMap.toString());
    }
    // Try parse genericMap as an instance of the resource
    ObjectMapper mapper = new ObjectMapper();
    BaseScimResource alter = opType.equals(PatchOperationType.REMOVE) ? resource : mapper.convertValue(genericMap, clazz);
    List<Extension> extensions = extService.getResourceExtensions(clazz);
    switch(operation.getType()) {
        case REPLACE:
            result = ScimResourceUtil.transferToResourceReplace(alter, resource, extensions);
            break;
        case ADD:
            result = ScimResourceUtil.transferToResourceAdd(alter, resource, extensions);
            break;
        case REMOVE:
            result = ScimResourceUtil.deleteFromResource(alter, operation.getPath(), extensions);
            break;
    }
    return result;
}
Also used : PatchOperationType(org.gluu.oxtrust.model.scim2.patch.PatchOperationType) Attribute(org.gluu.oxtrust.model.scim2.annotations.Attribute) Extension(org.gluu.oxtrust.model.scim2.extensions.Extension) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) BaseScimResource(org.gluu.oxtrust.model.scim2.BaseScimResource) NullType(javax.lang.model.type.NullType) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 32 with Attribute

use of io.jans.scim.model.scim2.annotations.Attribute in project jans by JanssenProject.

the class GroupAssignUserTest method alterMemberships.

@Test(dependsOnMethods = "modifyGroupFromUser")
public void alterMemberships() {
    // Effectively remove one member and add admin
    Member aMental = group.getMembers().stream().findAny().get();
    Member admin = new Member();
    admin.setValue(getAdminId());
    group.getMembers().remove(aMental);
    group.getMembers().add(admin);
    logger.info("Removing one and adding one member...");
    Response response = client.updateGroup(group, group.getId(), null, null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    group = response.readEntity(GroupResource.class);
    assertFalse(group.getMembers().contains(aMental));
    // Here we don't use contains because equality in Member object inspects all fields (not only value)
    assertTrue(group.getMembers().stream().anyMatch(m -> admin.getValue().equals(m.getValue())));
    logger.info("Group has correct members");
    // Verify groups attribute in users reflected changes
    response = client.getUserById(aMental.getValue(), "groups", null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    UserResource patient = response.readEntity(usrClass);
    assertTrue(patient.getGroups() == null || patient.getGroups().stream().noneMatch(gr -> gr.getValue().equals(group.getId())));
    response = client.getUserById(admin.getValue(), "groups", null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    patient = response.readEntity(usrClass);
    assertTrue(patient.getGroups().stream().anyMatch(gr -> gr.getValue().equals(group.getId())));
    logger.info("Users have correct memberships");
}
Also used : Response(javax.ws.rs.core.Response) ListResponse(io.jans.scim.model.scim2.ListResponse) Member(io.jans.scim.model.scim2.group.Member) UserBaseTest(io.jans.scim2.client.UserBaseTest) java.util(java.util) UserResource(io.jans.scim.model.scim2.user.UserResource) Test(org.testng.annotations.Test) Collectors(java.util.stream.Collectors) GroupResource(io.jans.scim.model.scim2.group.GroupResource) BaseScimResource(io.jans.scim.model.scim2.BaseScimResource) SearchRequest(io.jans.scim.model.scim2.SearchRequest) Group(io.jans.scim.model.scim2.user.Group) Response(javax.ws.rs.core.Response) Assert(org.testng.Assert) ListResponse(io.jans.scim.model.scim2.ListResponse) Status(javax.ws.rs.core.Response.Status) UserResource(io.jans.scim.model.scim2.user.UserResource) Member(io.jans.scim.model.scim2.group.Member) GroupResource(io.jans.scim.model.scim2.group.GroupResource) UserBaseTest(io.jans.scim2.client.UserBaseTest) Test(org.testng.annotations.Test)

Example 33 with Attribute

use of io.jans.scim.model.scim2.annotations.Attribute in project jans by JanssenProject.

the class GroupAssignUserTest method modifyGroupFromUser.

@Test(dependsOnMethods = "verifyGroupsAttribute")
public void modifyGroupFromUser() {
    // Try to modify read-only "groups" attribute of User Resource (must not change)
    user.getGroups().remove(0);
    Response response = client.updateUser(user, user.getId(), null, null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    logger.info("Attempting to modify group membership using /Users endpoint...");
    user = response.readEntity(usrClass);
    Set<String> groupIds = user.getGroups().stream().map(Group::getValue).collect(Collectors.toSet());
    assertTrue(groupIds.contains(group.getId()));
    assertTrue(groupIds.contains(group2.getId()));
}
Also used : Response(javax.ws.rs.core.Response) ListResponse(io.jans.scim.model.scim2.ListResponse) UserBaseTest(io.jans.scim2.client.UserBaseTest) Test(org.testng.annotations.Test)

Example 34 with Attribute

use of io.jans.scim.model.scim2.annotations.Attribute in project jans by JanssenProject.

the class ComplexSearchUserTest method searchNoAttributesParam.

@Test
public void searchNoAttributesParam() {
    final String ims = "Skype";
    logger.debug("Searching users with attribute nickName existent or ims.value={} using POST verb", ims);
    SearchRequest sr = new SearchRequest();
    sr.setFilter("nickName pr or ims.value eq \"" + ims + "\"");
    Response response = client.searchUsersPost(sr);
    assertEquals(response.getStatus(), OK.getStatusCode());
    ListResponse listResponse = response.readEntity(ListResponse.class);
    if (listResponse.getResources() != null) {
        for (BaseScimResource resource : listResponse.getResources()) {
            UserResource other = (UserResource) resource;
            boolean c1 = other.getNickName() != null;
            boolean c2 = true;
            if (other.getIms() != null)
                c2 = other.getIms().stream().anyMatch(im -> im.getValue().toLowerCase().equals(ims.toLowerCase()));
            assertTrue(c1 || c2);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) ListResponse(io.jans.scim.model.scim2.ListResponse) SearchRequest(io.jans.scim.model.scim2.SearchRequest) ListResponse(io.jans.scim.model.scim2.ListResponse) BaseScimResource(io.jans.scim.model.scim2.BaseScimResource) UserResource(io.jans.scim.model.scim2.user.UserResource) UserBaseTest(io.jans.scim2.client.UserBaseTest) Test(org.testng.annotations.Test)

Example 35 with Attribute

use of io.jans.scim.model.scim2.annotations.Attribute in project jans by JanssenProject.

the class UpdatedUsersTest method updatingUsers.

@Test(dependsOnMethods = "creatingUsers")
public void updatingUsers() throws Exception {
    // pick 2 rand inums
    String A = inums.get(randInt(N));
    String B = inums.get(randInt(N));
    UserResource u = new UserResource();
    u.setActive(true);
    // Update active attribute for the chosen users
    Response response = client.updateUser(u, A, "meta.lastModified", null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    String isoDate = response.readEntity(usrClass).getMeta().getLastModified();
    logger.info("User {} updated at '{}'", A, isoDate);
    response = client.updateUser(u, B, "id", null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    logger.info("Querying updated users after '{}'", isoDate);
    response = client.usersChangedAfter(isoDate, 0, N);
    assertEquals(response.getStatus(), OK.getStatusCode());
    String json = response.readEntity(String.class);
    // Convert response into an opaque map
    Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
    });
    Set<String> foundInums = getFoundInums(map);
    assertTrue(foundInums.remove(A));
    assertTrue(A.equals(B) || foundInums.remove(B));
    // Ensure there are no false positives
    assertTrue(foundInums.isEmpty());
}
Also used : Response(javax.ws.rs.core.Response) UserResource(io.jans.scim.model.scim2.user.UserResource) UserBaseTest(io.jans.scim2.client.UserBaseTest) BeforeTest(org.testng.annotations.BeforeTest) Test(org.testng.annotations.Test)

Aggregations

Response (javax.ws.rs.core.Response)19 UserResource (io.jans.scim.model.scim2.user.UserResource)13 ListResponse (io.jans.scim.model.scim2.ListResponse)12 Test (org.testng.annotations.Test)12 SCIMException (io.jans.scim.model.exception.SCIMException)11 Attribute (io.jans.scim.model.scim2.annotations.Attribute)11 Field (java.lang.reflect.Field)11 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)11 Attribute (org.gluu.oxtrust.model.scim2.annotations.Attribute)11 ExtensionField (io.jans.scim.model.scim2.extensions.ExtensionField)10 Extension (io.jans.scim.model.scim2.extensions.Extension)9 UserBaseTest (io.jans.scim2.client.UserBaseTest)7 BaseScimResource (io.jans.scim.model.scim2.BaseScimResource)5 NullType (javax.lang.model.type.NullType)5 Path (javax.ws.rs.Path)5 SearchRequest (io.jans.scim.model.scim2.SearchRequest)4 ProtectedApi (io.jans.scim.service.filter.ProtectedApi)4 RefAdjusted (io.jans.scim.service.scim2.interceptor.RefAdjusted)4 BaseTest (io.jans.scim2.client.BaseTest)4 URI (java.net.URI)4