Search in sources :

Example 16 with BaseScimResource

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

the class Scim2UserService method searchUsers.

public PagedResult<BaseScimResource> searchUsers(String filter, String sortBy, SortOrder sortOrder, int startIndex, int count, String url, int maxCount) throws Exception {
    Filter ldapFilter = scimFilterParserService.createFilter(filter, Filter.createPresenceFilter("inum"), UserResource.class);
    log.info("Executing search for users using: ldapfilter '{}', sortBy '{}', sortOrder '{}', startIndex '{}', count '{}'", ldapFilter.toString(), sortBy, sortOrder.getValue(), startIndex, count);
    PagedResult<ScimCustomPerson> list = ldapEntryManager.findPagedEntries(personService.getDnForPerson(null), ScimCustomPerson.class, ldapFilter, null, sortBy, sortOrder, startIndex - 1, count, maxCount);
    List<BaseScimResource> resources = new ArrayList<>();
    if (externalScimService.isEnabled() && !externalScimService.executeScimPostSearchUsersMethods(list)) {
        throw new WebApplicationException("Failed to execute SCIM script successfully", Status.PRECONDITION_FAILED);
    }
    for (ScimCustomPerson person : list.getEntries()) {
        UserResource scimUsr = new UserResource();
        transferAttributesToUserResource(person, scimUsr, url);
        resources.add(scimUsr);
    }
    log.info("Found {} matching entries - returning {}", list.getTotalEntriesCount(), list.getEntries().size());
    PagedResult<BaseScimResource> result = new PagedResult<>();
    result.setEntries(resources);
    result.setTotalEntriesCount(list.getTotalEntriesCount());
    return result;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Filter(io.jans.orm.search.filter.Filter) ScimCustomPerson(io.jans.scim.model.scim.ScimCustomPerson) BaseScimResource(io.jans.scim.model.scim2.BaseScimResource) ArrayList(java.util.ArrayList) UserResource(io.jans.scim.model.scim2.user.UserResource) PagedResult(io.jans.orm.model.PagedResult)

Example 17 with BaseScimResource

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

the class Scim2UserService method transferExtendedAttributesToPerson.

/**
 * Takes all extended attributes found in the SCIM resource and copies them to a
 * ScimCustomPerson This method is called after validations take place (see
 * associated decorator for User Service), so all inputs are OK and can go
 * straight to LDAP with no runtime surprises
 *
 * @param resource
 *            A SCIM resource used as origin of data
 * @param person
 *            a ScimCustomPerson used as destination
 */
private void transferExtendedAttributesToPerson(BaseScimResource resource, ScimCustomPerson person) {
    try {
        // Gets all the extended attributes for this resource
        Map<String, Object> extendedAttrs = resource.getCustomAttributes();
        // Iterates over all extensions this type of resource might have
        for (Extension extension : extService.getResourceExtensions(resource.getClass())) {
            Object val = extendedAttrs.get(extension.getUrn());
            if (val != null) {
                // Obtains the attribute/value(s) pairs in the current extension
                Map<String, Object> attrsMap = IntrospectUtil.strObjMap(val);
                for (String attribute : attrsMap.keySet()) {
                    Object value = attrsMap.get(attribute);
                    if (value == null) {
                        // Attribute was unassigned in this resource: drop it from destination too
                        log.debug("transferExtendedAttributesToPerson. Flushing attribute {}", attribute);
                        person.setAttribute(attribute, (String) null);
                    } else {
                        ExtensionField field = extension.getFields().get(attribute);
                        if (field.isMultiValued()) {
                            person.setCustomAttribute(attribute, extService.getAttributeValues(field, (Collection) value, ldapBackend));
                        } else {
                            person.setCustomAttribute(attribute, extService.getAttributeValue(field, value, ldapBackend));
                        }
                        log.debug("transferExtendedAttributesToPerson. Setting attribute '{}' with values {}", attribute, person.getTypedAttribute(attribute).getDisplayValue());
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
Also used : Extension(io.jans.scim.model.scim2.extensions.Extension) ExtensionField(io.jans.scim.model.scim2.extensions.ExtensionField) Collection(java.util.Collection) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException)

Example 18 with BaseScimResource

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

the class Scim2UserService method transferExtendedAttributesToResource.

private void transferExtendedAttributesToResource(ScimCustomPerson person, BaseScimResource resource) {
    log.debug("transferExtendedAttributesToResource of type {}", ScimResourceUtil.getType(resource.getClass()));
    // Gets the list of extensions associated to the resource passed. In practice,
    // this will be at most a singleton list
    List<Extension> extensions = extService.getResourceExtensions(resource.getClass());
    // resource
    for (Extension extension : extensions) {
        Map<String, ExtensionField> fields = extension.getFields();
        // Create empty map to store the values of the extended attributes found for
        // current extension in object person
        Map<String, Object> map = new HashMap<>();
        log.debug("transferExtendedAttributesToResource. Revising attributes of extension '{}'", extension.getUrn());
        // Iterate over every attribute part of this extension
        for (String attr : fields.keySet()) {
            // Gets the values associated to this attribute that were found in LDAP
            String[] values = person.getAttributes(attr);
            if (values != null) {
                log.debug("transferExtendedAttributesToResource. Copying to resource the value(s) for attribute '{}'", attr);
                ExtensionField field = fields.get(attr);
                List<Object> convertedValues = extService.convertValues(field, values, ldapBackend);
                if (convertedValues.size() > 0) {
                    map.put(attr, field.isMultiValued() ? convertedValues : convertedValues.get(0));
                }
            }
        }
        // Stores all extended attributes (with their values) in the resource object
        if (map.size() > 0) {
            resource.addCustomAttributes(extension.getUrn(), map);
        }
    }
    for (String urn : resource.getCustomAttributes().keySet()) {
        resource.getSchemas().add(urn);
    }
}
Also used : Extension(io.jans.scim.model.scim2.extensions.Extension) ExtensionField(io.jans.scim.model.scim2.extensions.ExtensionField) HashMap(java.util.HashMap)

Example 19 with BaseScimResource

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

the class GroupAssignUserTest method verifyGroupsAttribute.

@Test(dependsOnMethods = "assignToSecondGroup")
public void verifyGroupsAttribute() {
    // Refresh the user instances so getGroups() can be called
    // builds a filter string
    StringBuilder filter = new StringBuilder();
    friends.forEach(buddy -> filter.append(String.format(" or id eq \"%s\"", buddy.getId())));
    // builds a search request
    SearchRequest sr = new SearchRequest();
    sr.setFilter(filter.substring(4));
    // Retrieve only the first 3
    sr.setCount(3);
    // Performs the query
    logger.info("Issuing query with filter: {}", sr.getFilter());
    Response response = client.searchUsersPost(sr);
    assertEquals(response.getStatus(), OK.getStatusCode());
    logger.info("Verifying groups and users consistency...");
    List<BaseScimResource> buddies = response.readEntity(ListResponse.class).getResources();
    assertEquals(buddies.size(), 3);
    // Verify all mad belong to group, and one of them, additionally to group2
    buddies.stream().map(usrClass::cast).forEach(buddy -> {
        Set<String> groupIds = buddy.getGroups().stream().map(Group::getValue).collect(Collectors.toSet());
        assertTrue(groupIds.contains(group.getId()));
    });
    Optional<UserResource> usrOpt = buddies.stream().map(usrClass::cast).filter(buddy -> buddy.getGroups().size() > 1).findFirst();
    assertTrue(usrOpt.isPresent());
    user = usrOpt.get();
    assertTrue(user.getGroups().stream().map(Group::getValue).collect(Collectors.toSet()).contains(group2.getId()));
}
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) 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 20 with BaseScimResource

use of io.jans.scim.model.scim2.BaseScimResource 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)

Aggregations

BaseScimResource (io.jans.scim.model.scim2.BaseScimResource)12 Extension (io.jans.scim.model.scim2.extensions.Extension)12 ArrayList (java.util.ArrayList)12 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)12 Response (javax.ws.rs.core.Response)11 SCIMException (io.jans.scim.model.exception.SCIMException)10 BaseScimResource (org.gluu.oxtrust.model.scim2.BaseScimResource)9 URI (java.net.URI)8 ExtensionField (io.jans.scim.model.scim2.extensions.ExtensionField)7 ListResponse (io.jans.scim.model.scim2.ListResponse)6 URISyntaxException (java.net.URISyntaxException)6 ListViewResponse (org.gluu.persist.model.ListViewResponse)6 SearchRequest (io.jans.scim.model.scim2.SearchRequest)5 UserResource (io.jans.scim.model.scim2.user.UserResource)5 PagedResult (io.jans.orm.model.PagedResult)4 Filter (io.jans.orm.search.filter.Filter)4 Attribute (io.jans.scim.model.scim2.annotations.Attribute)4 DefaultValue (javax.ws.rs.DefaultValue)4 GET (javax.ws.rs.GET)4 HeaderParam (javax.ws.rs.HeaderParam)4