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;
}
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);
}
}
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);
}
}
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()));
}
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;
}
Aggregations