Search in sources :

Example 31 with Attribute

use of org.gluu.oxtrust.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 org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class BaseScimWebService method assignMetaInformation.

protected void assignMetaInformation(BaseScimResource resource) {
    // Generate some meta information (this replaces the info client passed in the request)
    long now = new Date().getTime();
    String val = ISODateTimeFormat.dateTime().withZoneUTC().print(now);
    Meta meta = new Meta();
    meta.setResourceType(ScimResourceUtil.getType(resource.getClass()));
    meta.setCreated(val);
    meta.setLastModified(val);
    // For version attritute: Service provider support for this attribute is optional and subject to the service provider's support for versioning
    // For location attribute: this will be set after current user creation in LDAP
    resource.setMeta(meta);
}
Also used : Meta(org.gluu.oxtrust.model.scim2.Meta) Date(java.util.Date)

Example 33 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class UserWebService method patchUser.

@Path("{id}")
@PATCH
@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
@RefAdjusted
@ApiOperation(value = "PATCH operation", notes = "https://tools.ietf.org/html/rfc7644#section-3.5.2", response = UserResource.class)
public Response patchUser(PatchRequest request, @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. patchUser");
        UserResource user = new UserResource();
        // person is not null (check associated decorator method)
        GluuCustomPerson person = personService.getPersonByInum(id);
        // Fill user instance with all info from person
        scim2UserService.transferAttributesToUserResource(person, user, endpointUrl);
        // Apply patches one by one in sequence
        for (PatchOperation po : request.getOperations()) {
            // Handle special case: https://github.com/GluuFederation/oxTrust/issues/800
            if (po.getType().equals(REMOVE) && po.getPath().equals("pairwiseIdentitifers")) {
                // If this block weren't here, the implementation will throw error because read-only attribute cannot be altered
                // Note the path is intentionally mistyped, see class member in UserResource
                person.setOxPPID(null);
                user.setPairwiseIdentitifers(null);
                scim2UserService.removePPIDsBranch(person.getDn());
            } else
                user = (UserResource) scim2PatchService.applyPatchOperation(user, po);
        }
        // Throws exception if final representation does not pass overall validation
        log.debug("patchUser. Revising final resource representation still passes validations");
        executeDefaultValidation(user);
        ScimResourceUtil.adjustPrimarySubAttributes(user);
        // Update timestamp
        String now = ISODateTimeFormat.dateTime().withZoneUTC().print(System.currentTimeMillis());
        user.getMeta().setLastModified(now);
        // Replaces the information found in person with the contents of user
        scim2UserService.replacePersonInfo(person, user, endpointUrl);
        String json = resourceSerializer.serialize(user, attrsList, excludedAttrsList);
        response = Response.ok(new URI(user.getMeta().getLocation())).entity(json).build();
    } catch (InvalidAttributeValueException e) {
        log.error(e.getMessage(), e);
        response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.MUTABILITY, e.getMessage());
    } catch (SCIMException e) {
        response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_SYNTAX, e.getMessage());
    } catch (Exception e) {
        log.error("Failure at patchUser method", e);
        response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
    }
    return response;
}
Also used : ListResponse(org.gluu.oxtrust.model.scim2.ListResponse) Response(javax.ws.rs.core.Response) ListViewResponse(org.gluu.persist.model.ListViewResponse) GluuCustomPerson(org.gluu.oxtrust.model.GluuCustomPerson) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) UserResource(org.gluu.oxtrust.model.scim2.user.UserResource) PatchOperation(org.gluu.oxtrust.model.scim2.patch.PatchOperation) URI(java.net.URI) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) Path(javax.ws.rs.Path) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) RefAdjusted(org.gluu.oxtrust.service.scim2.interceptor.RefAdjusted) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ProtectedApi(org.gluu.oxtrust.service.filter.ProtectedApi)

Example 34 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

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
@RefAdjusted
@ApiOperation(value = "Update user", notes = "Update user (https://tools.ietf.org/html/rfc7644#section-3.5.1)", response = UserResource.class)
public Response updateUser(@ApiParam(value = "User", required = true) 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");
        UserResource updatedResource = scim2UserService.updateUser(id, user, endpointUrl);
        String json = resourceSerializer.serialize(updatedResource, attrsList, excludedAttrsList);
        response = Response.ok(new URI(updatedResource.getMeta().getLocation())).entity(json).build();
    } 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 : ListResponse(org.gluu.oxtrust.model.scim2.ListResponse) Response(javax.ws.rs.core.Response) ListViewResponse(org.gluu.persist.model.ListViewResponse) UserResource(org.gluu.oxtrust.model.scim2.user.UserResource) URI(java.net.URI) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) Path(javax.ws.rs.Path) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) RefAdjusted(org.gluu.oxtrust.service.scim2.interceptor.RefAdjusted) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ProtectedApi(org.gluu.oxtrust.service.filter.ProtectedApi) PUT(javax.ws.rs.PUT)

Aggregations

Attribute (org.gluu.oxtrust.model.scim2.annotations.Attribute)11 SCIMException (org.gluu.oxtrust.model.exception.SCIMException)9 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)8 Extension (org.gluu.oxtrust.model.scim2.extensions.Extension)8 ExtensionField (org.gluu.oxtrust.model.scim2.extensions.ExtensionField)8 Field (java.lang.reflect.Field)6 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)6 GluuCustomPerson (org.gluu.oxtrust.model.GluuCustomPerson)6 ArrayList (java.util.ArrayList)5 Date (java.util.Date)5 GluuAttribute (org.xdi.model.GluuAttribute)5 BigDecimal (java.math.BigDecimal)4 Response (javax.ws.rs.core.Response)4 Extension (org.gluu.oxtrust.model.scim2.Extension)4 ListResponse (org.gluu.oxtrust.model.scim2.ListResponse)4 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)3 URI (java.net.URI)3 Consumes (javax.ws.rs.Consumes)3 DefaultValue (javax.ws.rs.DefaultValue)3 HeaderParam (javax.ws.rs.HeaderParam)3