Search in sources :

Example 11 with SCIMException

use of io.jans.scim.model.exception.SCIMException in project jans by JanssenProject.

the class ResourceValidator method validateRequiredAttributes.

/**
 * Inspects the resource passed in the constructor and determines if the attributes annotated as {@link Attribute#isRequired()
 * required} in the <code>Class</code> of the resource were all provided (not null).
 * In lax mode, if an attribute was marked as "required" and is part of a multi-valued complex attribute, no validation takes
 * place if the involved list is null or empty.
 * @param laxRequiredness True denotes lax mode, False normal validation mode (strict)
 * @throws SCIMException When a validation does not pass (there is a missing value in a required attribute)
 */
public void validateRequiredAttributes(boolean laxRequiredness) throws SCIMException {
    Map<String, List<Method>> map = IntrospectUtil.requiredCoreAttrs.get(resourceClass);
    for (String attributePath : map.keySet()) {
        boolean checkValues = !laxRequiredness;
        List<Method> methods = map.get(attributePath);
        if (laxRequiredness) {
            int len = methods.size();
            if (len > 1) {
                Method parentMethod = methods.get(len - 2);
                if (IntrospectUtil.isCollection(parentMethod.getReturnType())) {
                    List<Object> items = IntrospectUtil.getAttributeValues(resource, methods.subList(0, len - 1));
                    checkValues = !items.isEmpty();
                }
            }
        }
        if (checkValues) {
            log.debug("Validating existence of required attribute '{}'", attributePath);
            for (Object val : IntrospectUtil.getAttributeValues(resource, methods)) {
                if (val == null) {
                    log.error("Error getting value of required attribute '{}'", attributePath);
                    throw new SCIMException(String.format(REQUIRED_ATTR_NOTFOUND, attributePath));
                }
            }
        }
    }
}
Also used : SCIMException(io.jans.scim.model.exception.SCIMException) Method(java.lang.reflect.Method)

Example 12 with SCIMException

use of io.jans.scim.model.exception.SCIMException in project jans by JanssenProject.

the class ScimFilterParserService method checkParsingErrors.

private void checkParsingErrors(ScimFilterErrorListener errorListener) throws SCIMException {
    String outputErr = errorListener.getOutput();
    String symbolErr = errorListener.getSymbol();
    if (StringUtils.isNotEmpty(outputErr) || StringUtils.isNotEmpty(symbolErr))
        throw new SCIMException(String.format("Error parsing filter (symbol='%s'; message='%s')", symbolErr, outputErr));
}
Also used : SCIMException(io.jans.scim.model.exception.SCIMException)

Example 13 with SCIMException

use of io.jans.scim.model.exception.SCIMException in project jans by JanssenProject.

the class Scim2PatchService method applyPatchOperation.

public BaseScimResource applyPatchOperation(BaseScimResource resource, PatchOperation operation, Predicate<String> selectionFilterSkipPredicate) 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
                if (selectionFilterSkipPredicate.test(valSelFilter)) {
                    log.info("Patch operation will be skipped");
                    return resource;
                } else {
                    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<>();
                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(io.jans.scim.model.scim2.patch.PatchOperationType) Attribute(io.jans.scim.model.scim2.annotations.Attribute) HashMap(java.util.HashMap) Extension(io.jans.scim.model.scim2.extensions.Extension) SCIMException(io.jans.scim.model.exception.SCIMException) BaseScimResource(io.jans.scim.model.scim2.BaseScimResource) NullType(javax.lang.model.type.NullType) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 14 with SCIMException

use of io.jans.scim.model.exception.SCIMException in project jans by JanssenProject.

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(io.jans.scim.model.scim2.extensions.ExtensionField) Field(java.lang.reflect.Field) Validations(io.jans.scim.model.scim2.Validations) SCIMException(io.jans.scim.model.exception.SCIMException) Validator(io.jans.scim.model.scim2.annotations.Validator)

Example 15 with SCIMException

use of io.jans.scim.model.exception.SCIMException in project jans by JanssenProject.

the class ResourceValidator method validateSchemasAttribute.

/**
 * Inspects the {@link BaseScimResource#getSchemas() schemas} attribute of the resource passed in the constructor and
 * checks the default schema <code>urn</code> associated to the resource type is present in the list. If some of the
 * <code>urn</code>s part of the <code>Extension</code>s passed in the constructor are contained in the list, the validation is also
 * successful.
 * <p>This method should be called after a successful call to {@link #validateRequiredAttributes()}.</p>
 * @throws SCIMException If there is no {@link BaseScimResource#getSchemas() schemas} in this resource or if some of
 * the <code>urn</code>s there are not known.
 */
public void validateSchemasAttribute() throws SCIMException {
    Set<String> schemaList = new HashSet<>(resource.getSchemas());
    if (schemaList.isEmpty())
        throw new SCIMException(WRONG_SCHEMAS_ATTR);
    Set<String> allSchemas = new HashSet<>();
    allSchemas.add(ScimResourceUtil.getDefaultSchemaUrn(resourceClass));
    for (Extension ext : extensions) allSchemas.add(ext.getUrn());
    schemaList.removeAll(allSchemas);
    if (// means that some wrong extension urn is there
    schemaList.size() > 0)
        throw new SCIMException(WRONG_SCHEMAS_ATTR);
}
Also used : Extension(io.jans.scim.model.scim2.extensions.Extension) SCIMException(io.jans.scim.model.exception.SCIMException)

Aggregations

SCIMException (io.jans.scim.model.exception.SCIMException)21 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)13 URI (java.net.URI)12 URISyntaxException (java.net.URISyntaxException)12 Response (javax.ws.rs.core.Response)12 DuplicateEntryException (io.jans.orm.exception.operation.DuplicateEntryException)8 ProtectedApi (io.jans.scim.service.filter.ProtectedApi)8 RefAdjusted (io.jans.scim.service.scim2.interceptor.RefAdjusted)8 Consumes (javax.ws.rs.Consumes)8 DefaultValue (javax.ws.rs.DefaultValue)8 HeaderParam (javax.ws.rs.HeaderParam)8 Produces (javax.ws.rs.Produces)8 Path (javax.ws.rs.Path)6 BaseScimResource (io.jans.scim.model.scim2.BaseScimResource)5 PUT (javax.ws.rs.PUT)5 SearchRequest (io.jans.scim.model.scim2.SearchRequest)4 GluuGroup (io.jans.scim.model.GluuGroup)3 ScimCustomPerson (io.jans.scim.model.scim.ScimCustomPerson)3 Attribute (io.jans.scim.model.scim2.annotations.Attribute)3 Extension (io.jans.scim.model.scim2.extensions.Extension)3