Search in sources :

Example 16 with BaseScimResource

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

the class ListResponseJsonSerializer method serialize.

@Override
public void serialize(ListResponse listResponse, JsonGenerator jGen, SerializerProvider provider) throws IOException {
    try {
        jGen.writeStartObject();
        jGen.writeArrayFieldStart("schemas");
        for (String schema : listResponse.getSchemas()) jGen.writeString(schema);
        jGen.writeEndArray();
        jGen.writeNumberField("totalResults", listResponse.getTotalResults());
        if (!skipResults) {
            if (listResponse.getItemsPerPage() > 0) {
                // these two bits are "REQUIRED when partial results are returned due to pagination." (section 3.4.2 RFC 7644)
                jGen.writeNumberField("startIndex", listResponse.getStartIndex());
                jGen.writeNumberField("itemsPerPage", listResponse.getItemsPerPage());
            }
            // Section 3.4.2 RFC 7644: Resources [...] REQUIRED if "totalResults" is non-zero
            if (listResponse.getTotalResults() > 0) {
                jGen.writeArrayFieldStart("Resources");
                if (listResponse.getResources().size() > 0)
                    for (BaseScimResource resource : listResponse.getResources()) {
                        JsonNode jsonResource = mapper.readTree(resourceSerializer.serialize(resource, attributes, excludeAttributes));
                        jGen.writeTree(jsonResource);
                    }
                else if (jsonResources != null)
                    for (JsonNode node : jsonResources) jGen.writeTree(node);
                jGen.writeEndArray();
            }
        }
        jGen.writeEndObject();
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : BaseScimResource(org.gluu.oxtrust.model.scim2.BaseScimResource) JsonNode(org.codehaus.jackson.JsonNode) IOException(java.io.IOException) IOException(java.io.IOException)

Example 17 with BaseScimResource

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

the class ScimResourceSerializer method buildIncludeSet.

private void buildIncludeSet(SortedSet<String> include, Class<? extends BaseScimResource> resourceClass, List<String> schemas, String attributes, String exclussions) {
    Set<String> tempSet;
    Set<String> alwaysSet = IntrospectUtil.alwaysCoreAttrs.get(resourceClass).keySet();
    Set<String> neverSet = IntrospectUtil.neverCoreAttrs.get(resourceClass).keySet();
    Set<String> defaultSet = new HashSet<String>();
    // Here we assume all attributes part of extensions have returnability="default"...
    SortedSet<String> extendedSet = new TreeSet<String>();
    for (Extension ext : extService.getResourceExtensions(resourceClass)) {
        extendedSet.add(ext.getUrn());
        extendedSet.addAll(IntrospectUtil.getPathsInExtension(ext));
    }
    defaultSet.addAll(IntrospectUtil.defaultCoreAttrs.get(resourceClass).keySet());
    defaultSet.addAll(extendedSet);
    String defaultSchema = ScimResourceUtil.getDefaultSchemaUrn(resourceClass);
    if (attributes != null) {
        log.info("buildIncludeSet. Processing attributes query param (excludedAttributes ignored)");
        extendedSet.addAll(IntrospectUtil.allAttrs.get(resourceClass));
        tempSet = expandAttributesPaths(attributes, defaultSchema, schemas, extendedSet);
        tempSet.removeAll(neverSet);
        include.addAll(tempSet);
    } else if (exclussions != null) {
        log.info("buildIncludeSet. Processing excludedAttributes query param");
        extendedSet.addAll(IntrospectUtil.allAttrs.get(resourceClass));
        tempSet = defaultSet;
        tempSet.removeAll(expandAttributesPaths(exclussions, defaultSchema, schemas, extendedSet));
        include.addAll(tempSet);
    } else {
        log.info("buildIncludeSet. No attributes neither excludedAttributes query param were passed");
        include.addAll(defaultSet);
    }
    include.addAll(alwaysSet);
}
Also used : Extension(org.gluu.oxtrust.model.scim2.extensions.Extension)

Example 18 with BaseScimResource

use of org.gluu.oxtrust.model.scim2.BaseScimResource 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 19 with BaseScimResource

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

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<String>(resource.getSchemas());
    if (schemaList.size() == 0)
        throw new SCIMException(WRONG_SCHEMAS_ATTR);
    Set<String> allSchemas = new HashSet<String>();
    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(org.gluu.oxtrust.model.scim2.extensions.Extension) SCIMException(org.gluu.oxtrust.model.exception.SCIMException)

Example 20 with BaseScimResource

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

the class ScimResourceUtil method deleteFromResource.

/**
 * Returns a SCIM resource with the same data found in <code>origin</code> object, except for the attribute referenced
 * by <code>path</code> being removed from the output. In other words, this method nullifies an attribute.
 * @param origin The resource having the the original data
 * @param path An attribute path (in dot notation). Examples could be: <code>displayName, emails.type, addresses,
 *             meta.lastModified</code>.
 * @param extensions A list of <code>Extension</code>s associated to <code>origin</code> Object
 * @return The resulting object: data in origin without the attribute referenced by <code>path</code>
 * @throws InvalidAttributeValueException If there is an attempt to remove an attribute annotated as {@link Attribute#isRequired()
 * required} or {@link org.gluu.oxtrust.model.scim2.AttributeDefinition.Mutability#READ_ONLY read-only}
 */
public static BaseScimResource deleteFromResource(BaseScimResource origin, String path, List<Extension> extensions) throws InvalidAttributeValueException {
    Field f = IntrospectUtil.findFieldFromPath(origin.getClass(), path);
    if (f != null) {
        Attribute attrAnnot = f.getAnnotation(Attribute.class);
        if (attrAnnot != null && (attrAnnot.mutability().equals(READ_ONLY) || attrAnnot.isRequired()))
            throw new InvalidAttributeValueException("Cannot remove read-only or required attribute " + path);
    }
    Map<String, Object> map = mapper.convertValue(origin, new TypeReference<Map<String, Object>>() {
    });
    traversalClass tclass = new traversalClass(origin.getClass());
    if (// Extensions stuff
    f == null)
        deleteCustomAttribute(map, path, extensions);
    else
        tclass.traverseDelete(map, path);
    return mapper.convertValue(map, origin.getClass());
}
Also used : ExtensionField(org.gluu.oxtrust.model.scim2.extensions.ExtensionField) Field(java.lang.reflect.Field) Attribute(org.gluu.oxtrust.model.scim2.annotations.Attribute) InvalidAttributeValueException(javax.management.InvalidAttributeValueException)

Aggregations

Extension (org.gluu.oxtrust.model.scim2.extensions.Extension)12 BaseScimResource (org.gluu.oxtrust.model.scim2.BaseScimResource)9 SCIMException (org.gluu.oxtrust.model.exception.SCIMException)7 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)6 ListResponse (org.gluu.oxtrust.model.scim2.ListResponse)6 ExtensionField (org.gluu.oxtrust.model.scim2.extensions.ExtensionField)6 ListViewResponse (org.gluu.persist.model.ListViewResponse)6 Response (javax.ws.rs.core.Response)5 URI (java.net.URI)4 ArrayList (java.util.ArrayList)4 Attribute (org.gluu.oxtrust.model.scim2.annotations.Attribute)4 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)3 DefaultValue (javax.ws.rs.DefaultValue)3 GET (javax.ws.rs.GET)3 HeaderParam (javax.ws.rs.HeaderParam)3 Produces (javax.ws.rs.Produces)3 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)3 Meta (org.gluu.oxtrust.model.scim2.Meta)3 ProtectedApi (org.gluu.oxtrust.service.filter.ProtectedApi)3 RefAdjusted (org.gluu.oxtrust.service.scim2.interceptor.RefAdjusted)3