Search in sources :

Example 16 with Attribute

use of io.jans.scim.model.scim2.annotations.Attribute 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 17 with Attribute

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

the class UserWebService method updateUser.

/**
 * This implementation differs from spec in the following aspects:
 * - Passing a null value for an attribute, does not modify the attribute in the destination, however passing an
 * empty array for a multivalued attribute does clear the attribute. Thus, to clear single-valued attribute, PATCH
 * operation should be used
 */
@Path("{id}")
@PUT
@Consumes({ MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON })
@Produces({ MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT })
@HeaderParam("Accept")
@DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi(scopes = { "https://jans.io/scim/users.write" })
@RefAdjusted
public Response updateUser(UserResource user, @PathParam("id") String id, @QueryParam(QUERY_PARAM_ATTRIBUTES) String attrsList, @QueryParam(QUERY_PARAM_EXCLUDED_ATTRS) String excludedAttrsList) {
    Response response;
    try {
        log.debug("Executing web service method. updateUser");
        // Check if the ids match in case the user coming has one
        if (user.getId() != null && !user.getId().equals(id))
            throw new SCIMException("Parameter id does not match with id attribute of User");
        ScimCustomPerson person = userPersistenceHelper.getPersonByInum(id);
        if (person == null)
            return notFoundResponse(id, userResourceType);
        response = externalConstraintsService.applyEntityCheck(person, user, httpHeaders, uriInfo, HttpMethod.PUT, userResourceType);
        if (response != null)
            return response;
        executeValidation(user, true);
        if (StringUtils.isNotEmpty(user.getUserName())) {
            checkUidExistence(user.getUserName(), id);
        }
        ScimResourceUtil.adjustPrimarySubAttributes(user);
        UserResource updatedResource = scim2UserService.updateUser(person, user, endpointUrl);
        String json = resourceSerializer.serialize(updatedResource, attrsList, excludedAttrsList);
        response = Response.ok(new URI(updatedResource.getMeta().getLocation())).entity(json).build();
    } catch (DuplicateEntryException e) {
        log.error(e.getMessage());
        response = getErrorResponse(Response.Status.CONFLICT, ErrorScimType.UNIQUENESS, e.getMessage());
    } catch (SCIMException e) {
        log.error("Validation check at updateUser returned: {}", e.getMessage());
        response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_VALUE, e.getMessage());
    } catch (InvalidAttributeValueException e) {
        log.error(e.getMessage());
        response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.MUTABILITY, e.getMessage());
    } catch (Exception e) {
        log.error("Failure at updateUser method", e);
        response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) SCIMException(io.jans.scim.model.exception.SCIMException) ScimCustomPerson(io.jans.scim.model.scim.ScimCustomPerson) UserResource(io.jans.scim.model.scim2.user.UserResource) DuplicateEntryException(io.jans.orm.exception.operation.DuplicateEntryException) URI(java.net.URI) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) URISyntaxException(java.net.URISyntaxException) SCIMException(io.jans.scim.model.exception.SCIMException) DuplicateEntryException(io.jans.orm.exception.operation.DuplicateEntryException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) Path(javax.ws.rs.Path) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) RefAdjusted(io.jans.scim.service.scim2.interceptor.RefAdjusted) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ProtectedApi(io.jans.scim.service.filter.ProtectedApi) PUT(javax.ws.rs.PUT)

Example 18 with Attribute

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

the class SimpleSearchUserTest method searchSimpleAttrGet.

@Test(dependsOnMethods = "create", groups = "search")
public void searchSimpleAttrGet() {
    String isoDateString = user.getMeta().getCreated();
    String locale = user.getLocale();
    logger.debug("Searching user with attribute locale = {} and created date >= {} using GET verb", locale, isoDateString);
    Response response = client.searchUsers(String.format("locale eq \"%s\" and meta.created ge \"%s\"", locale, isoDateString), null, null, null, null, null, null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    ListResponse listResponse = response.readEntity(ListResponse.class);
    assertTrue(listResponse.getResources().size() > 0);
    // Retrieve first user in results
    UserResource same = listResponse.getResources().stream().map(usrClass::cast).findFirst().get();
    assertEquals(same.getLocale(), locale);
}
Also used : Response(javax.ws.rs.core.Response) ListResponse(io.jans.scim.model.scim2.ListResponse) ListResponse(io.jans.scim.model.scim2.ListResponse) UserResource(io.jans.scim.model.scim2.user.UserResource) UserBaseTest(io.jans.scim2.client.UserBaseTest) Test(org.testng.annotations.Test)

Example 19 with Attribute

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

the class SchemasTest method inspectUserExtensionSchema.

@Test(dependsOnMethods = "checkSchemasExistence")
public void inspectUserExtensionSchema() {
    Optional<SchemaResource> userExtSchemaOpt = listResponse.getResources().stream().map(SchemaResource.class::cast).filter(sr -> sr.getId().contains(USER_EXT_SCHEMA_ID)).findFirst();
    if (userExtSchemaOpt.isPresent()) {
        String name = userExtSchemaOpt.get().getName();
        assertNotNull(name);
        logger.info("Found User Schema Extension: {}", name);
        Boolean[] foundAttr = new Boolean[3];
        for (SchemaAttribute attribute : userExtSchemaOpt.get().getAttributes()) {
            switch(attribute.getName()) {
                case "scimCustomFirst":
                    foundAttr[0] = true;
                    logger.info("scimCustomFirst found");
                    assertEquals(attribute.getType(), "string");
                    assertFalse(attribute.isMultiValued());
                    break;
                case "scimCustomSecond":
                    foundAttr[1] = true;
                    logger.info("scimCustomSecond found");
                    assertEquals(attribute.getType(), "dateTime");
                    assertTrue(attribute.isMultiValued());
                    break;
                case "scimCustomThird":
                    foundAttr[2] = true;
                    logger.info("scimCustomThird found");
                    assertEquals(attribute.getType(), "decimal");
                    assertFalse(attribute.isMultiValued());
                    break;
            }
        }
        Arrays.asList(foundAttr).forEach(org.testng.Assert::assertTrue);
    } else
        logger.warn("There is no Schema Resource associated to User Schema Extension ({})", USER_EXT_SCHEMA_ID);
}
Also used : Arrays(java.util.Arrays) UserResource(io.jans.scim.model.scim2.user.UserResource) USER_EXT_SCHEMA_ID(io.jans.scim.model.scim2.Constants.USER_EXT_SCHEMA_ID) Test(org.testng.annotations.Test) BaseTest(io.jans.scim2.client.BaseTest) SchemaResource(io.jans.scim.model.scim2.provider.schema.SchemaResource) ScimResourceUtil(io.jans.scim.model.scim2.util.ScimResourceUtil) ArrayList(java.util.ArrayList) GroupResource(io.jans.scim.model.scim2.group.GroupResource) BaseScimResource(io.jans.scim.model.scim2.BaseScimResource) BeforeTest(org.testng.annotations.BeforeTest) List(java.util.List) Fido2DeviceResource(io.jans.scim.model.scim2.fido.Fido2DeviceResource) Response(javax.ws.rs.core.Response) Assert(org.testng.Assert) ListResponse(io.jans.scim.model.scim2.ListResponse) Optional(java.util.Optional) SchemaAttribute(io.jans.scim.model.scim2.provider.schema.SchemaAttribute) FidoDeviceResource(io.jans.scim.model.scim2.fido.FidoDeviceResource) Assert(org.testng.Assert) SchemaAttribute(io.jans.scim.model.scim2.provider.schema.SchemaAttribute) SchemaResource(io.jans.scim.model.scim2.provider.schema.SchemaResource) Test(org.testng.annotations.Test) BaseTest(io.jans.scim2.client.BaseTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 20 with Attribute

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

the class IntrospectUtil method findFieldFromPath.

/**
 * Inspects a class to search for a field that corresponds to the path passed using dot notation. Every piece of the
 * path (separated by the a dot '.') is expected to have a field with the same name in the class inspected. When such
 * a field is found, the remainder of the path is processed using the class associated to the field, until the path is
 * fully consumed.
 * <p>This method starts from an initial class and visits ascendingly the class hierarchy with a route determined
 * by the components found in the path parameter.</p>
 * @param initcls Class to start the search from
 * @param path A string denoting a path to a target attribute. Examples of valid paths can be: displayName, name.givenName,
 *            addresses.locality
 * @return A Field that represents the terminal portion of the path, for instance "locality" field for "addresses.locality".
 * If no such field is found (because at some point, there was no route to go), null is returned.
 */
public static Field findFieldFromPath(Class<?> initcls, String path) {
    Class cls = initcls;
    Field f = null;
    for (String prop : path.split("\\.")) {
        f = findField(cls, prop);
        if (f != null) {
            cls = f.getType();
            if (isCollection(cls)) {
                Attribute attrAnnot = f.getAnnotation(Attribute.class);
                if (attrAnnot != null)
                    cls = attrAnnot.multiValueClass();
            }
        } else
            break;
    }
    return f;
}
Also used : Field(java.lang.reflect.Field) Attribute(io.jans.scim.model.scim2.annotations.Attribute)

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