Search in sources :

Example 1 with Validations

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

the class GroupWebService method patchGroup.

@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 = GroupResource.class)
public Response patchGroup(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. patchGroup");
        String usersUrl = userWebService.getEndpointUrl();
        GroupResource group = new GroupResource();
        // group is not null (check associated decorator method)
        GluuGroup gluuGroup = groupService.getGroupByInum(id);
        // Fill group instance with all info from gluuGroup
        scim2GroupService.transferAttributesToGroupResource(gluuGroup, group, endpointUrl, usersUrl);
        // Apply patches one by one in sequence
        for (PatchOperation po : request.getOperations()) group = (GroupResource) scim2PatchService.applyPatchOperation(group, po);
        // Throws exception if final representation does not pass overall validation
        log.debug("patchGroup. Revising final resource representation still passes validations");
        executeDefaultValidation(group);
        // Update timestamp
        String now = ISODateTimeFormat.dateTime().withZoneUTC().print(System.currentTimeMillis());
        group.getMeta().setLastModified(now);
        // Replaces the information found in gluuGroup with the contents of group
        scim2GroupService.replaceGroupInfo(gluuGroup, group, endpointUrl, usersUrl);
        String json = resourceSerializer.serialize(group, attrsList, excludedAttrsList);
        response = Response.ok(new URI(group.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 patchGroup 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) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) PatchOperation(org.gluu.oxtrust.model.scim2.patch.PatchOperation) GluuGroup(org.gluu.oxtrust.model.GluuGroup) URI(java.net.URI) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) GroupResource(org.gluu.oxtrust.model.scim2.group.GroupResource) 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 2 with Validations

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

the class Scim2UserService method transferExtendedAttributesToPerson.

/**
 * Takes all extended attributes found in the SCIM resource and copies them to a GluuCustomPerson
 * 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 GluuCustomPerson used as destination
 */
private void transferExtendedAttributesToPerson(BaseScimResource resource, GluuCustomPerson 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);
                    // Ignore if the attribute is unassigned in this resource: destination will not be changed in this regard
                    if (value != null) {
                        // Get properly formatted string representations for the value(s) associated to the attribute
                        List<String> values = extService.getStringAttributeValues(extension.getFields().get(attribute), value);
                        log.debug("transferExtendedAttributesToPerson. Setting attribute '{}' with values {}", attribute, values.toString());
                        person.setAttribute(attribute, values.toArray(new String[] {}));
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
Also used : Extension(org.gluu.oxtrust.model.scim2.extensions.Extension) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 3 with Validations

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

the class ResourceValidator method validateValidableAttributes.

/**
 * Inspects the resource passed in the constructor and applies validations for every attribute annotated with
 * {@link Validator}. Validations are of different nature as seen{@link Validations here}.
 * @throws SCIMException When a validation does not pass (the {@link Validations#apply(Validations, Object) apply}
 * method returns false)
 */
public void validateValidableAttributes() throws SCIMException {
    Map<String, List<Method>> map = IntrospectUtil.validableCoreAttrs.get(resourceClass);
    for (String attributePath : map.keySet()) {
        Field f = IntrospectUtil.findFieldFromPath(resourceClass, attributePath);
        Validations valToApply = f.getAnnotation(Validator.class).value();
        log.debug("Validating value(s) of attribute '{}'", attributePath);
        for (Object val : IntrospectUtil.getAttributeValues(resource, map.get(attributePath))) {
            if (val != null && !Validations.apply(valToApply, val)) {
                log.error("Error validating attribute '{}', wrong value supplied: '{}'", attributePath, val.toString());
                throw new SCIMException(String.format(ATTR_VALIDATION_FAILED, attributePath));
            }
        }
    }
}
Also used : ExtensionField(org.gluu.oxtrust.model.scim2.extensions.ExtensionField) Field(java.lang.reflect.Field) Validations(org.gluu.oxtrust.model.scim2.Validations) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) Validator(org.gluu.oxtrust.model.scim2.annotations.Validator)

Example 4 with Validations

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

the class ResourceValidator method validateExtendedAttributes.

/**
 * Inspects the resource passed in the constructor and for every extended attribute (see {@link BaseScimResource#getCustomAttributes()},
 * the attribute's value is checked to see if it complies with the data type it is supposed to belong to. This
 * information is obtained from the list of <code>Extension</code>s passed in the constructor (every {@link ExtensionField}
 * has an associated {@link ExtensionField#getType() type}.
 * <p>When an attribute is {@link ExtensionField#isMultiValued() multi-valued}, every single item inside the collection
 * is validated.</p>
 * @throws SCIMException When any of the validations do not pass or an attribute seems not to be part of a known schema.
 */
public void validateExtendedAttributes() throws SCIMException {
    // Note: throughout this method, we always ignore presence of nulls
    // Gets all extended attributes (see the @JsonAnySetter annotation in BaseScimResource)
    Map<String, Object> extendedAttributes = resource.getCustomAttributes();
    // Iterate over every extension of the resource object (in practice it will be just one at most)
    for (String schema : extendedAttributes.keySet()) {
        // Validate if the schema referenced in the extended attributes is contained in the valid set of extension
        Extension extension = null;
        for (Extension ext : extensions) if (ext.getUrn().equals(schema)) {
            extension = ext;
            break;
        }
        if (extension != null) {
            log.debug("validateExtendedAttributes. Revising attributes under schema {}", schema);
            try {
                // Obtains a generic map consisting of all name/value(s) pairs associated to this schema
                Map<String, Object> attrsMap = IntrospectUtil.strObjMap(extendedAttributes.get(schema));
                for (String attr : attrsMap.keySet()) {
                    Object value = attrsMap.get(attr);
                    if (value != null) {
                        /*
                             Gets the class associated to the value of current attribute. For extended attributes, we
                             should only see coming: String, Integer, Double, boolean, and Collection.
                             Different things will be rejected
                             */
                        Class cls = value.getClass();
                        boolean isCollection = IntrospectUtil.isCollection(cls);
                        // If the attribute coming is unknown, NPE will be thrown and we are covered
                        log.debug("validateExtendedAttributes. Got value(s) for attribute '{}'", attr);
                        // Check if the multivalued custom attribute is consistent with the nature of the value itself
                        if (isCollection == extension.getFields().get(attr).isMultiValued()) {
                            if (isCollection) {
                                for (Object elem : (Collection) value) if (elem != null)
                                    validateDataTypeExtendedAttr(extension, attr, elem);
                            } else
                                validateDataTypeExtendedAttr(extension, attr, value);
                        } else
                            throw new SCIMException(ERROR_PARSING_EXTENDED);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new SCIMException(ERROR_PARSING_EXTENDED);
            }
        } else
            throw new SCIMException(String.format(UNKNOWN_EXTENSION, schema));
    }
}
Also used : Extension(org.gluu.oxtrust.model.scim2.extensions.Extension) SCIMException(org.gluu.oxtrust.model.exception.SCIMException) SCIMException(org.gluu.oxtrust.model.exception.SCIMException)

Example 5 with Validations

use of org.gluu.oxtrust.model.scim2.Validations in project atlasmap by atlasmap.

the class DefaultAtlasSession method initialize.

protected void initialize() {
    properties = new ConcurrentHashMap<String, Object>();
    validations = new Validations();
    audits = new Audits();
    head.unset();
}
Also used : Validations(io.atlasmap.v2.Validations) Audits(io.atlasmap.v2.Audits)

Aggregations

Validations (io.atlasmap.v2.Validations)15 Test (org.junit.Test)11 AtlasMappingBaseTest (io.atlasmap.validation.AtlasMappingBaseTest)8 Validation (io.atlasmap.v2.Validation)5 SCIMException (org.gluu.oxtrust.model.exception.SCIMException)4 AtlasSession (io.atlasmap.api.AtlasSession)3 Audits (io.atlasmap.v2.Audits)3 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)3 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)2 AtlasContext (io.atlasmap.api.AtlasContext)2 File (java.io.File)2 URI (java.net.URI)2 Consumes (javax.ws.rs.Consumes)2 DefaultValue (javax.ws.rs.DefaultValue)2 HeaderParam (javax.ws.rs.HeaderParam)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 Response (javax.ws.rs.core.Response)2 ListResponse (org.gluu.oxtrust.model.scim2.ListResponse)2 Extension (org.gluu.oxtrust.model.scim2.extensions.Extension)2