You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@directory.apache.org by bd...@apache.org on 2022/08/30 18:46:14 UTC
[directory-scimple] branch in-memory-filter created (now 5b2f373)
This is an automated email from the ASF dual-hosted git repository.
bdemers pushed a change to branch in-memory-filter
in repository https://gitbox.apache.org/repos/asf/directory-scimple.git
at 5b2f373 Add in memory Filter matcher
This branch includes the following new commits:
new 4537f83 Extract Schema generation logic from RepositoryRegistry
new 5b2f373 Add in memory Filter matcher
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
[directory-scimple] 01/02: Extract Schema generation logic from RepositoryRegistry
Posted by bd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
bdemers pushed a commit to branch in-memory-filter
in repository https://gitbox.apache.org/repos/asf/directory-scimple.git
commit 4537f83260f743e4e6777907b531f91574aab5ff
Author: Brian Demers <bd...@apache.org>
AuthorDate: Tue Aug 30 14:23:00 2022 -0400
Extract Schema generation logic from RepositoryRegistry
---
.../scim/server/repository/RepositoryRegistry.java | 298 +-------------------
.../scim/server/rest/AttributeUtilTest.java | 9 +-
.../apache/directory/scim/spec/schema/Schemas.java | 305 +++++++++++++++++++++
3 files changed, 320 insertions(+), 292 deletions(-)
diff --git a/scim-server/src/main/java/org/apache/directory/scim/server/repository/RepositoryRegistry.java b/scim-server/src/main/java/org/apache/directory/scim/server/repository/RepositoryRegistry.java
index 57248a6..f94ac5b 100644
--- a/scim-server/src/main/java/org/apache/directory/scim/server/repository/RepositoryRegistry.java
+++ b/scim-server/src/main/java/org/apache/directory/scim/server/repository/RepositoryRegistry.java
@@ -19,70 +19,35 @@
package org.apache.directory.scim.server.repository;
-import java.lang.reflect.Field;
-import java.lang.reflect.ParameterizedType;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
-import jakarta.xml.bind.annotation.XmlEnumValue;
-
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
import org.apache.directory.scim.server.ScimConfiguration;
import org.apache.directory.scim.server.exception.InvalidRepositoryException;
import org.apache.directory.scim.server.exception.UnableToRetrieveExtensionsResourceException;
import org.apache.directory.scim.server.schema.SchemaRegistry;
-import org.apache.directory.scim.spec.annotation.ScimAttribute;
import org.apache.directory.scim.spec.annotation.ScimExtensionType;
-import org.apache.directory.scim.spec.annotation.ScimResourceIdReference;
import org.apache.directory.scim.spec.annotation.ScimResourceType;
-import org.apache.directory.scim.spec.annotation.ScimType;
import org.apache.directory.scim.spec.exception.ScimResourceInvalidException;
import org.apache.directory.scim.spec.extension.ScimExtensionRegistry;
-import org.apache.directory.scim.spec.resources.BaseResource;
import org.apache.directory.scim.spec.resources.ScimExtension;
import org.apache.directory.scim.spec.resources.ScimResource;
import org.apache.directory.scim.spec.schema.ResourceType;
-import org.apache.directory.scim.spec.schema.Schema;
-import org.apache.directory.scim.spec.schema.Schema.Attribute;
-import org.apache.directory.scim.spec.schema.Schema.Attribute.AddAction;
-import org.apache.directory.scim.spec.schema.Schema.Attribute.Type;
+import org.apache.directory.scim.spec.schema.Schemas;
-import com.fasterxml.jackson.core.JsonProcessingException;
-
-import lombok.Data;
-import lombok.extern.slf4j.Slf4j;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Data
@Slf4j
@ApplicationScoped
public class RepositoryRegistry implements ScimConfiguration {
- private static final String STRING_TYPE_IDENTIFIER = "class java.lang.String";
- private static final String CHARACTER_ARRAY_TYPE_IDENTIFIER = "class [C";
- private static final String BIG_C_CHARACTER_ARRAY_TYPE_IDENTIFIER = "class [Ljava.lang.Character;";
- private static final String INT_TYPE_IDENTIFIER = "int";
- private static final String INTEGER_TYPE_IDENTIFIER = "class java.lang.Integer";
- private static final String FLOAT_TYPE_IDENTIFIER = "float";
- private static final String BIG_F_FLOAT_TYPE_IDENTIFIER = "class java.lang.Float";
- private static final String DOUBLE_TYPE_IDENTIFIER = "double";
- private static final String BIG_D_DOUBLE_TYPE_IDENTIFIER = "class java.lang.Double";
- private static final String BOOLEAN_TYPE_IDENTIFIER = "boolean";
- private static final String BIG_B_BOOLEAN_TYPE_IDENTIFIER = "class java.lang.Boolean";
- private static final String LOCAL_TIME_TYPE_IDENTIFER = "class java.time.LocalTime";
- private static final String LOCAL_DATE_TYPE_IDENTIFER = "class java.time.LocalDate";
- private static final String LOCAL_DATE_TIME_TYPE_IDENTIFIER = "class java.time.LocalDateTime";
- private static final String DATE_TYPE_IDENTIFIER = "class java.util.Date";
- private static final String BYTE_ARRAY_TYPE_IDENTIFIER = "class [B";
- private static final String RESOURCE_REFERENCE_TYPE_IDENTIFIER = "class org.apache.directory.scim.spec.schema.ResourceReference$ReferenceType";
-
private SchemaRegistry schemaRegistry;
private ScimExtensionRegistry scimExtensionRegistry;
@@ -121,7 +86,7 @@ public class RepositoryRegistry implements ScimConfiguration {
ResourceType resourceType = generateResourceType(clazz, repository);
log.info("Calling addSchema on the base class: {}", clazz);
- schemaRegistry.addSchema(generateBaseSchema(clazz));
+ schemaRegistry.addSchema(Schemas.schemaFor(clazz));
// NOTE generateResourceType() ensures ScimResourceType exists
ScimResourceType scimResourceType = clazz.getAnnotation(ScimResourceType.class);
String schemaUrn = scimResourceType.schema();
@@ -137,7 +102,7 @@ public class RepositoryRegistry implements ScimConfiguration {
scimExtensionRegistry.registerExtension(clazz, scimExtension);
log.info("Calling addSchema on an extension: " + scimExtension);
- schemaRegistry.addSchema(generateExtensionSchema(scimExtension));
+ schemaRegistry.addSchema(Schemas.schemaForExtension(scimExtension));
}
}
@@ -190,247 +155,4 @@ public class RepositoryRegistry implements ScimConfiguration {
return resourceType;
}
-
- public static Schema generateSchema(Class<? extends ScimResource> clazz) throws InvalidRepositoryException {
- return generateBaseSchema(clazz);
- }
-
- private static Schema generateBaseSchema(Class<?> clazz) throws InvalidRepositoryException {
- List<Field> fieldList = ReflectionUtils.getFieldsUpTo(clazz, BaseResource.class);
-
- return generateSchema(clazz, fieldList);
- }
-
- public static Schema generateExtensionSchema(Class<?> clazz) throws InvalidRepositoryException {
- log.debug("----> In generateExtensionSchema");
-
- return generateSchema(clazz, ReflectionUtils.getFieldsUpTo(clazz, Object.class));
- }
-
- private static Schema generateSchema(Class<?> clazz, List<Field> fieldList) throws InvalidRepositoryException {
-
- // Field [] fieldList = clazz.getDeclaredFields();
-
- Schema schema = new Schema();
-
- ScimResourceType srt = clazz.getAnnotation(ScimResourceType.class);
- ScimExtensionType set = clazz.getAnnotation(ScimExtensionType.class);
-
- if (srt == null && set == null) {
- // TODO - throw?
- log.error("Neither a ScimResourceType or ScimExtensionType annotation found");
- }
-
- log.debug("calling set attributes with " + fieldList.size() + " fields");
- String urn = set != null ? set.id() : srt.schema();
- Set<String> invalidAttributes = new HashSet<>();
- List<Attribute> createAttributes = createAttributes(urn, fieldList, invalidAttributes, clazz.getSimpleName());
- schema.setAttributes(createAttributes);
-
- if (!invalidAttributes.isEmpty()) {
- StringBuilder sb = new StringBuilder();
-
- sb.append("Scim attributes cannot be primitive types unless they are required. The following values were found that are primitive and not required\n\n");
-
- for (String s : invalidAttributes) {
- sb.append(s);
- sb.append("\n");
- }
-
- throw new InvalidRepositoryException(sb.toString());
- }
-
- if (srt != null) {
- schema.setId(srt.schema());
- schema.setDescription(srt.description());
- schema.setName(srt.name());
- } else {
- schema.setId(set.id());
- schema.setDescription(set.description());
- schema.setName(set.name());
- }
-
- return schema;
- }
-
- private static List<Attribute> createAttributes(String urn, List<Field> fieldList, Set<String> invalidAttributes, String nameBase) throws InvalidRepositoryException {
- List<Attribute> attributeList = new ArrayList<>();
-
- for (Field f : fieldList) {
- ScimAttribute sa = f.getAnnotation(ScimAttribute.class);
-
- log.debug("++++++++++++++++++++ Processing field " + f.getName());
- if (sa == null) {
- log.debug("Attribute " + f.getName() + " did not have a ScimAttribute annotation");
- continue;
- }
-
- String attributeName;
- f.setAccessible(true);
-
- if (sa.name() == null || sa.name().isEmpty()) {
- attributeName = f.getName();
- } else {
- attributeName = sa.name();
- }
-
- if (f.getType().isPrimitive() && !sa.required()) {
- invalidAttributes.add(nameBase + "." + attributeName);
- continue;
- }
-
- //TODO - Fix this to look for the two types of canonical attributes
- Attribute attribute = new Attribute();
- attribute.setAccessor(Schema.AttributeAccessor.forField(f));
- attribute.setName(attributeName);
- attribute.setUrn(urn);
-
- List<String> canonicalTypes = null;
- Field [] enumFields = sa.canonicalValueEnum().getFields();
- log.debug("Gathered fields of off the enum, there are " + enumFields.length + " " + sa.canonicalValueEnum().getName());
-
- if (enumFields.length != 0) {
-
- //This looks goofy, but there's always at least the default value, so it's not an empty list
- if (sa.canonicalValueList().length != 1 && !sa.canonicalValueList()[0].isEmpty()) {
- throw new InvalidRepositoryException("You cannont set both the canonicalEnumValue and canonicalValueList attributes on the same ScimAttribute");
- }
-
- canonicalTypes = new ArrayList<>();
-
- for (Field field : enumFields) {
- XmlEnumValue [] annotation = field.getAnnotationsByType(XmlEnumValue.class);
-
- if (annotation.length != 0) {
- canonicalTypes.add(annotation[0].value());
- } else {
- canonicalTypes.add(field.getName());
- }
- }
- } else {
- canonicalTypes = Arrays.asList(sa.canonicalValueList());
- }
-
- // If we just have the default single empty string, set to null
- if (canonicalTypes.isEmpty() || (canonicalTypes.size() == 1 && canonicalTypes.get(0).isEmpty())) {
- attribute.setCanonicalValues(null);
- } else {
- attribute.setCanonicalValues(new HashSet<String>(canonicalTypes));
- }
-
- attribute.setCaseExact(sa.caseExact());
- attribute.setDescription(sa.description());
-
- String typeName = null;
- if (Collection.class.isAssignableFrom(f.getType())) {
- log.debug("We have a collection");
- ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
- Class<?> attributeContainedClass = (Class<?>) stringListType.getActualTypeArguments()[0];
- typeName = attributeContainedClass.getTypeName();
- attribute.setMultiValued(true);
- } else if (f.getType().isArray()) {
- log.debug("We have an array");
- Class<?> componentType = f.getType().getComponentType();
- typeName = componentType.getTypeName();
- attribute.setMultiValued(true);
- } else {
- typeName = f.getType().toString();
- attribute.setMultiValued(false);
- }
-
- // attribute.setType(sa.type());
- boolean attributeIsAString = false;
- log.debug("Attempting to set the attribute type, raw value = " + typeName);
- switch (typeName) {
- case STRING_TYPE_IDENTIFIER:
- case CHARACTER_ARRAY_TYPE_IDENTIFIER:
- case BIG_C_CHARACTER_ARRAY_TYPE_IDENTIFIER:
- log.debug("Setting type to String");
- attribute.setType(Type.STRING);
- attributeIsAString = true;
- break;
- case INT_TYPE_IDENTIFIER:
- case INTEGER_TYPE_IDENTIFIER:
- log.debug("Setting type to integer");
- attribute.setType(Type.INTEGER);
- break;
- case FLOAT_TYPE_IDENTIFIER:
- case BIG_F_FLOAT_TYPE_IDENTIFIER:
- case DOUBLE_TYPE_IDENTIFIER:
- case BIG_D_DOUBLE_TYPE_IDENTIFIER:
- log.debug("Setting type to decimal");
- attribute.setType(Type.DECIMAL);
- break;
- case BOOLEAN_TYPE_IDENTIFIER:
- case BIG_B_BOOLEAN_TYPE_IDENTIFIER:
- log.debug("Setting type to boolean");
- attribute.setType(Type.BOOLEAN);
- break;
- case BYTE_ARRAY_TYPE_IDENTIFIER:
- log.debug("Setting type to binary");
- attribute.setType(Type.BINARY);
- break;
- case DATE_TYPE_IDENTIFIER:
- case LOCAL_DATE_TIME_TYPE_IDENTIFIER:
- case LOCAL_TIME_TYPE_IDENTIFER:
- case LOCAL_DATE_TYPE_IDENTIFER:
- log.debug("Setting type to date time");
- attribute.setType(Type.DATE_TIME);
- break;
- case RESOURCE_REFERENCE_TYPE_IDENTIFIER:
- log.debug("Setting type to reference");
- attribute.setType(Type.REFERENCE);
- break;
- default:
- log.debug("Setting type to complex");
- attribute.setType(Type.COMPLEX);
- }
- if (f.getAnnotation(ScimResourceIdReference.class) != null) {
- if (attributeIsAString) {
- attribute.setScimResourceIdReference(true);
- } else {
- log.warn("Field annotated with @ScimResourceIdReference must be a string: {}", f);
- }
- }
- attribute.setMutability(sa.mutability());
-
- List<String> refType = Arrays.asList(sa.referenceTypes());
-
- // If we just have the default single empty string, set to null
- if (refType.isEmpty() || (refType.size() == 1 && refType.get(0).isEmpty())) {
- attribute.setReferenceTypes(null);
- } else {
- attribute.setReferenceTypes(Arrays.asList(sa.referenceTypes()));
- }
-
- attribute.setRequired(sa.required());
- attribute.setReturned(sa.returned());
- attribute.setUniqueness(sa.uniqueness());
-
- //if (sa.type().equals(Type.COMPLEX))
- ScimType st = f.getType().getAnnotation(ScimType.class);
-
- if (attribute.getType() == Type.COMPLEX || st != null) {
- Class<?> componentType;
- if (!attribute.isMultiValued()) {
- componentType = f.getType();
- attribute.setSubAttributes(createAttributes(urn, Arrays.asList(f.getType().getDeclaredFields()), invalidAttributes, nameBase + "." + f.getName()), AddAction.APPEND);
- } else if (f.getType().isArray()) {
- componentType = f.getType().getComponentType();
- } else {
- ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
- componentType = (Class<?>) stringListType.getActualTypeArguments()[0];
- }
-
- List<Field> fl = ReflectionUtils.getFieldsUpTo(componentType, Object.class);
- List<Attribute> la = createAttributes(urn, fl, invalidAttributes, nameBase + "." + f.getName());
-
- attribute.setSubAttributes(la, AddAction.APPEND);
- }
- attributeList.add(attribute);
- }
-
- log.debug("Returning " + attributeList.size() + " attributes");
- return attributeList;
- }
}
diff --git a/scim-server/src/test/java/org/apache/directory/scim/server/rest/AttributeUtilTest.java b/scim-server/src/test/java/org/apache/directory/scim/server/rest/AttributeUtilTest.java
index ad745bc..21b6ce0 100644
--- a/scim-server/src/test/java/org/apache/directory/scim/server/rest/AttributeUtilTest.java
+++ b/scim-server/src/test/java/org/apache/directory/scim/server/rest/AttributeUtilTest.java
@@ -39,6 +39,7 @@ import org.apache.directory.scim.spec.resources.PhoneNumber;
import org.apache.directory.scim.spec.resources.PhoneNumber.LocalPhoneNumberBuilder;
import org.apache.directory.scim.spec.resources.ScimUser;
import org.apache.directory.scim.spec.schema.Schema;
+import org.apache.directory.scim.spec.schema.Schemas;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -65,12 +66,12 @@ public class AttributeUtilTest {
private ObjectMapper objectMapper;
@BeforeEach
- public void setup() throws Exception {
+ public void setup() {
schemaRegistry = Mockito.mock(SchemaRegistry.class);
attributeUtil = new AttributeUtil(schemaRegistry);
- Schema scimUserSchema = RepositoryRegistry.generateSchema(ScimUser.class);
- Schema scimEnterpriseUserSchema = RepositoryRegistry.generateExtensionSchema(EnterpriseExtension.class);
- Schema scimExampleSchema = RepositoryRegistry.generateExtensionSchema(ExampleObjectExtension.class);
+ Schema scimUserSchema = Schemas.schemaFor(ScimUser.class);
+ Schema scimEnterpriseUserSchema = Schemas.schemaForExtension(EnterpriseExtension.class);
+ Schema scimExampleSchema = Schemas.schemaForExtension(ExampleObjectExtension.class);
Mockito.when(schemaRegistry.getBaseSchemaOfResourceType(ScimUser.RESOURCE_NAME)).thenReturn(scimUserSchema);
diff --git a/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Schemas.java b/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Schemas.java
new file mode 100644
index 0000000..bbe5bd4
--- /dev/null
+++ b/scim-spec/scim-spec-schema/src/main/java/org/apache/directory/scim/spec/schema/Schemas.java
@@ -0,0 +1,305 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.directory.scim.spec.schema;
+
+import jakarta.xml.bind.annotation.XmlEnumValue;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.directory.scim.spec.annotation.ScimAttribute;
+import org.apache.directory.scim.spec.annotation.ScimExtensionType;
+import org.apache.directory.scim.spec.annotation.ScimResourceIdReference;
+import org.apache.directory.scim.spec.annotation.ScimResourceType;
+import org.apache.directory.scim.spec.annotation.ScimType;
+import org.apache.directory.scim.spec.exception.ScimResourceInvalidException;
+import org.apache.directory.scim.spec.resources.BaseResource;
+import org.apache.directory.scim.spec.resources.ScimExtension;
+import org.apache.directory.scim.spec.resources.ScimResource;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.ParameterizedType;
+import java.util.*;
+
+@Slf4j
+public final class Schemas {
+
+ private static final String STRING_TYPE_IDENTIFIER = "class java.lang.String";
+ private static final String CHARACTER_ARRAY_TYPE_IDENTIFIER = "class [C";
+ private static final String BIG_C_CHARACTER_ARRAY_TYPE_IDENTIFIER = "class [Ljava.lang.Character;";
+ private static final String INT_TYPE_IDENTIFIER = "int";
+ private static final String INTEGER_TYPE_IDENTIFIER = "class java.lang.Integer";
+ private static final String FLOAT_TYPE_IDENTIFIER = "float";
+ private static final String BIG_F_FLOAT_TYPE_IDENTIFIER = "class java.lang.Float";
+ private static final String DOUBLE_TYPE_IDENTIFIER = "double";
+ private static final String BIG_D_DOUBLE_TYPE_IDENTIFIER = "class java.lang.Double";
+ private static final String BOOLEAN_TYPE_IDENTIFIER = "boolean";
+ private static final String BIG_B_BOOLEAN_TYPE_IDENTIFIER = "class java.lang.Boolean";
+ private static final String LOCAL_TIME_TYPE_IDENTIFER = "class java.time.LocalTime";
+ private static final String LOCAL_DATE_TYPE_IDENTIFER = "class java.time.LocalDate";
+ private static final String LOCAL_DATE_TIME_TYPE_IDENTIFIER = "class java.time.LocalDateTime";
+ private static final String DATE_TYPE_IDENTIFIER = "class java.util.Date";
+ private static final String BYTE_ARRAY_TYPE_IDENTIFIER = "class [B";
+ private static final String RESOURCE_REFERENCE_TYPE_IDENTIFIER = "class org.apache.directory.scim.spec.schema.ResourceReference$ReferenceType";
+
+ private Schemas() {}
+
+ public static Schema schemaFor(Class<? extends ScimResource> clazz) throws ScimResourceInvalidException {
+ return generateSchema(clazz, getFieldsUpTo(clazz, BaseResource.class));
+ }
+
+ public static Schema schemaForExtension(Class<? extends ScimExtension> clazz) throws ScimResourceInvalidException {
+ return generateSchema(clazz, getFieldsUpTo(clazz, Object.class));
+ }
+
+ private static Schema generateSchema(Class<?> clazz, List<Field> fieldList) throws ScimResourceInvalidException {
+
+ Schema schema = new Schema();
+
+ ScimResourceType srt = clazz.getAnnotation(ScimResourceType.class);
+ ScimExtensionType set = clazz.getAnnotation(ScimExtensionType.class);
+
+ if (srt == null && set == null) {
+ // TODO - throw?
+ log.error("Neither a ScimResourceType or ScimExtensionType annotation found");
+ }
+
+ log.debug("calling set attributes with " + fieldList.size() + " fields");
+ String urn = set != null ? set.id() : srt.schema();
+ Set<String> invalidAttributes = new HashSet<>();
+ List<Schema.Attribute> createAttributes = createAttributes(urn, fieldList, invalidAttributes, clazz.getSimpleName());
+ schema.setAttributes(createAttributes);
+
+ if (!invalidAttributes.isEmpty()) {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("Scim attributes cannot be primitive types unless they are required. The following values were found that are primitive and not required\n\n");
+
+ for (String s : invalidAttributes) {
+ sb.append(s);
+ sb.append("\n");
+ }
+
+ throw new ScimResourceInvalidException(sb.toString());
+ }
+
+ if (srt != null) {
+ schema.setId(srt.schema());
+ schema.setDescription(srt.description());
+ schema.setName(srt.name());
+ } else {
+ schema.setId(set.id());
+ schema.setDescription(set.description());
+ schema.setName(set.name());
+ }
+
+ return schema;
+ }
+
+
+ private static List<Schema.Attribute> createAttributes(String urn, List<Field> fieldList, Set<String> invalidAttributes, String nameBase) throws ScimResourceInvalidException {
+ List<Schema.Attribute> attributeList = new ArrayList<>();
+
+ for (Field f : fieldList) {
+ ScimAttribute sa = f.getAnnotation(ScimAttribute.class);
+
+ log.debug("++++++++++++++++++++ Processing field " + f.getName());
+ if (sa == null) {
+ log.debug("Attribute " + f.getName() + " did not have a ScimAttribute annotation");
+ continue;
+ }
+
+ String attributeName;
+ f.setAccessible(true);
+
+ if (sa.name() == null || sa.name().isEmpty()) {
+ attributeName = f.getName();
+ } else {
+ attributeName = sa.name();
+ }
+
+ if (f.getType().isPrimitive() && !sa.required()) {
+ invalidAttributes.add(nameBase + "." + attributeName);
+ continue;
+ }
+
+ //TODO - Fix this to look for the two types of canonical attributes
+ Schema.Attribute attribute = new Schema.Attribute();
+ attribute.setAccessor(Schema.AttributeAccessor.forField(f));
+ attribute.setName(attributeName);
+ attribute.setUrn(urn);
+
+ List<String> canonicalTypes = null;
+ Field [] enumFields = sa.canonicalValueEnum().getFields();
+ log.debug("Gathered fields of off the enum, there are " + enumFields.length + " " + sa.canonicalValueEnum().getName());
+
+ if (enumFields.length != 0) {
+
+ //This looks goofy, but there's always at least the default value, so it's not an empty list
+ if (sa.canonicalValueList().length != 1 && !sa.canonicalValueList()[0].isEmpty()) {
+ throw new ScimResourceInvalidException("You cannot set both the canonicalEnumValue and canonicalValueList attributes on the same ScimAttribute");
+ }
+
+ canonicalTypes = new ArrayList<>();
+
+ for (Field field : enumFields) {
+ XmlEnumValue[] annotation = field.getAnnotationsByType(XmlEnumValue.class);
+
+ if (annotation.length != 0) {
+ canonicalTypes.add(annotation[0].value());
+ } else {
+ canonicalTypes.add(field.getName());
+ }
+ }
+ } else {
+ canonicalTypes = Arrays.asList(sa.canonicalValueList());
+ }
+
+ // If we just have the default single empty string, set to null
+ if (canonicalTypes.isEmpty() || (canonicalTypes.size() == 1 && canonicalTypes.get(0).isEmpty())) {
+ attribute.setCanonicalValues(null);
+ } else {
+ attribute.setCanonicalValues(new HashSet<String>(canonicalTypes));
+ }
+
+ attribute.setCaseExact(sa.caseExact());
+ attribute.setDescription(sa.description());
+
+ String typeName = null;
+ if (Collection.class.isAssignableFrom(f.getType())) {
+ log.debug("We have a collection");
+ ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
+ Class<?> attributeContainedClass = (Class<?>) stringListType.getActualTypeArguments()[0];
+ typeName = attributeContainedClass.getTypeName();
+ attribute.setMultiValued(true);
+ } else if (f.getType().isArray()) {
+ log.debug("We have an array");
+ Class<?> componentType = f.getType().getComponentType();
+ typeName = componentType.getTypeName();
+ attribute.setMultiValued(true);
+ } else {
+ typeName = f.getType().toString();
+ attribute.setMultiValued(false);
+ }
+
+ // attribute.setType(sa.type());
+ boolean attributeIsAString = false;
+ log.debug("Attempting to set the attribute type, raw value = " + typeName);
+ switch (typeName) {
+ case STRING_TYPE_IDENTIFIER:
+ case CHARACTER_ARRAY_TYPE_IDENTIFIER:
+ case BIG_C_CHARACTER_ARRAY_TYPE_IDENTIFIER:
+ log.debug("Setting type to String");
+ attribute.setType(Schema.Attribute.Type.STRING);
+ attributeIsAString = true;
+ break;
+ case INT_TYPE_IDENTIFIER:
+ case INTEGER_TYPE_IDENTIFIER:
+ log.debug("Setting type to integer");
+ attribute.setType(Schema.Attribute.Type.INTEGER);
+ break;
+ case FLOAT_TYPE_IDENTIFIER:
+ case BIG_F_FLOAT_TYPE_IDENTIFIER:
+ case DOUBLE_TYPE_IDENTIFIER:
+ case BIG_D_DOUBLE_TYPE_IDENTIFIER:
+ log.debug("Setting type to decimal");
+ attribute.setType(Schema.Attribute.Type.DECIMAL);
+ break;
+ case BOOLEAN_TYPE_IDENTIFIER:
+ case BIG_B_BOOLEAN_TYPE_IDENTIFIER:
+ log.debug("Setting type to boolean");
+ attribute.setType(Schema.Attribute.Type.BOOLEAN);
+ break;
+ case BYTE_ARRAY_TYPE_IDENTIFIER:
+ log.debug("Setting type to binary");
+ attribute.setType(Schema.Attribute.Type.BINARY);
+ break;
+ case DATE_TYPE_IDENTIFIER:
+ case LOCAL_DATE_TIME_TYPE_IDENTIFIER:
+ case LOCAL_TIME_TYPE_IDENTIFER:
+ case LOCAL_DATE_TYPE_IDENTIFER:
+ log.debug("Setting type to date time");
+ attribute.setType(Schema.Attribute.Type.DATE_TIME);
+ break;
+ case RESOURCE_REFERENCE_TYPE_IDENTIFIER:
+ log.debug("Setting type to reference");
+ attribute.setType(Schema.Attribute.Type.REFERENCE);
+ break;
+ default:
+ log.debug("Setting type to complex");
+ attribute.setType(Schema.Attribute.Type.COMPLEX);
+ }
+ if (f.getAnnotation(ScimResourceIdReference.class) != null) {
+ if (attributeIsAString) {
+ attribute.setScimResourceIdReference(true);
+ } else {
+ log.warn("Field annotated with @ScimResourceIdReference must be a string: {}", f);
+ }
+ }
+ attribute.setMutability(sa.mutability());
+
+ List<String> refType = Arrays.asList(sa.referenceTypes());
+
+ // If we just have the default single empty string, set to null
+ if (refType.isEmpty() || (refType.size() == 1 && refType.get(0).isEmpty())) {
+ attribute.setReferenceTypes(null);
+ } else {
+ attribute.setReferenceTypes(Arrays.asList(sa.referenceTypes()));
+ }
+
+ attribute.setRequired(sa.required());
+ attribute.setReturned(sa.returned());
+ attribute.setUniqueness(sa.uniqueness());
+
+ //if (sa.type().equals(Type.COMPLEX))
+ org.apache.directory.scim.spec.annotation.ScimType st = f.getType().getAnnotation(ScimType.class);
+
+ if (attribute.getType() == Schema.Attribute.Type.COMPLEX || st != null) {
+ Class<?> componentType;
+ if (!attribute.isMultiValued()) {
+ componentType = f.getType();
+ attribute.setSubAttributes(createAttributes(urn, Arrays.asList(f.getType().getDeclaredFields()), invalidAttributes, nameBase + "." + f.getName()), Schema.Attribute.AddAction.APPEND);
+ } else if (f.getType().isArray()) {
+ componentType = f.getType().getComponentType();
+ } else {
+ ParameterizedType stringListType = (ParameterizedType) f.getGenericType();
+ componentType = (Class<?>) stringListType.getActualTypeArguments()[0];
+ }
+
+ List<Field> fl = getFieldsUpTo(componentType, Object.class);
+ List<Schema.Attribute> la = createAttributes(urn, fl, invalidAttributes, nameBase + "." + f.getName());
+
+ attribute.setSubAttributes(la, Schema.Attribute.AddAction.APPEND);
+ }
+ attributeList.add(attribute);
+ }
+
+ log.debug("Returning " + attributeList.size() + " attributes");
+ return attributeList;
+ }
+
+ static List<Field> getFieldsUpTo(Class<?> startClass, Class<?> exclusiveParent) {
+ List<Field> currentClassFields = new ArrayList<>();
+ Collections.addAll(currentClassFields, startClass.getDeclaredFields());
+ Class<?> parentClass = startClass.getSuperclass();
+ if (parentClass != null && (!(parentClass.equals(exclusiveParent)))) {
+ List<Field> parentClassFields = getFieldsUpTo(parentClass, exclusiveParent);
+ currentClassFields.addAll(parentClassFields);
+ }
+ return currentClassFields;
+ }
+}
[directory-scimple] 02/02: Add in memory Filter matcher
Posted by bd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
bdemers pushed a commit to branch in-memory-filter
in repository https://gitbox.apache.org/repos/asf/directory-scimple.git
commit 5b2f373401495a9d1e645a9b2d4a874853d1866a
Author: Brian Demers <bd...@apache.org>
AuthorDate: Tue Aug 30 14:25:59 2022 -0400
Add in memory Filter matcher
This implementation can be used for demo purposes. Actual production implementations will need to translate a FilterExpresion into a query language.
---
.../spec/protocol/filter/FilterExpression.java | 6 +
.../spec/protocol/filter/FilterExpressions.java | 31 +++
.../protocol/filter/InMemoryScimFilterMatcher.java | 300 +++++++++++++++++++++
.../scim/spec/protocol/LuckyNumberExtension.java | 61 +++++
.../filter/InMemoryScimFilterMatcherTest.java | 236 ++++++++++++++++
5 files changed, 634 insertions(+)
diff --git a/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpression.java b/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpression.java
index 0e95ae6..2fd1b2d 100644
--- a/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpression.java
+++ b/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpression.java
@@ -19,6 +19,8 @@
package org.apache.directory.scim.spec.protocol.filter;
+import java.util.function.Function;
+
public interface FilterExpression {
String toFilter();
@@ -26,4 +28,8 @@ public interface FilterExpression {
void setAttributePath(String urn, String parentAttributeName);
String toUnqualifiedFilter();
+
+ default <U> U map(Function<? super FilterExpression, U> mapper) {
+ return mapper.apply(this);
+ }
}
diff --git a/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpressions.java b/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpressions.java
new file mode 100644
index 0000000..3356355
--- /dev/null
+++ b/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/FilterExpressions.java
@@ -0,0 +1,31 @@
+package org.apache.directory.scim.spec.protocol.filter;
+
+import org.apache.directory.scim.spec.protocol.search.Filter;
+import org.apache.directory.scim.spec.resources.ScimResource;
+import org.apache.directory.scim.spec.schema.Schema;
+
+import java.util.function.Predicate;
+
+
+public final class FilterExpressions {
+
+ private FilterExpressions() {}
+
+ /**
+ * Converts a filter into a Predicate used for in-memory evaluation. Production implementations should translate the Filter into
+ * the appropriate query language.
+ * <p>
+ *
+ * <b>This implementation should only be used for demo proposes.</b>
+ */
+ public static Predicate<ScimResource> inMemory(Filter filter, Schema schema) {
+ if (filter == null) {
+ return x -> true;
+ }
+ FilterExpression expression = filter.getExpression();
+ if (expression == null) {
+ return x -> true;
+ }
+ return InMemoryScimFilterMatcher.toPredicate(expression, schema);
+ }
+}
diff --git a/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/InMemoryScimFilterMatcher.java b/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/InMemoryScimFilterMatcher.java
new file mode 100644
index 0000000..5faec26
--- /dev/null
+++ b/scim-spec/scim-spec-protocol/src/main/java/org/apache/directory/scim/spec/protocol/filter/InMemoryScimFilterMatcher.java
@@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.directory.scim.spec.protocol.filter;
+
+import org.apache.directory.scim.spec.exception.ScimResourceInvalidException;
+import org.apache.directory.scim.spec.protocol.attribute.AttributeReference;
+import org.apache.directory.scim.spec.schema.AttributeContainer;
+import org.apache.directory.scim.spec.schema.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.function.Predicate;
+
+final class InMemoryScimFilterMatcher {
+
+ private static final Logger log = LoggerFactory.getLogger(InMemoryScimFilterMatcher.class);
+
+ private InMemoryScimFilterMatcher() {}
+
+ /**
+ * Converts a FilterExpression to a Predicate that can be used to later test a ScimResource (or child attribute).
+ * <p>
+ * The {@code attributeContainer} should be a top level Schema for the initial call, but recursive calls to this method
+ * will pass the AttributeContainer (a child-schema). For example, if given a
+ * {@link org.apache.directory.scim.spec.resources.ScimUser ScimUser} expression of {@code emails.value co "example.org"},
+ * The initial call to this method pass the ScimUser Schema object. When this method is called recursively, the
+ * {@link org.apache.directory.scim.spec.resources.Email Email}'s AttributeContainer will be used.
+ *
+ * @param expression the FilterExpression to build a predicate from.
+ * @param attributeContainer the Schema (or other sub attribute container) to build the predicate from.
+ * @return A Predicate that can be used to later test a ScimResource (or child attribute).
+ */
+ static <R> Predicate<R> toPredicate(FilterExpression expression, AttributeContainer attributeContainer) {
+
+ // attribute EQ "something"
+ if (expression instanceof AttributeComparisonExpression) {
+ return new AttributeComparisonPredicate<>((AttributeComparisonExpression) expression, attributeContainer);
+ }
+ // (attribute EQ "something") AND (otherAttribute EQ "something else")
+ else if (expression instanceof LogicalExpression) {
+ LogicalExpression logicalExpression = (LogicalExpression) expression;
+ Predicate<R> left = toPredicate(logicalExpression.getLeft(), attributeContainer);
+ Predicate<R> right = toPredicate(logicalExpression.getRight(), attributeContainer);
+
+ LogicalOperator op = logicalExpression.getOperator();
+ if (op == LogicalOperator.AND) {
+ return left.and(right);
+ } else {
+ return left.or(right);
+ }
+ }
+ // NOT (attribute EQ "something")
+ else if (expression instanceof GroupExpression) {
+ GroupExpression groupExpression = (GroupExpression) expression;
+ Predicate<R> predicate = toPredicate(groupExpression.getFilterExpression(), attributeContainer);
+ return groupExpression.isNot()
+ ? predicate.negate()
+ : predicate;
+ }
+ // attribute PR
+ else if (expression instanceof AttributePresentExpression) {
+ return new AttributePresentPredicate<>((AttributePresentExpression) expression, attributeContainer);
+ }
+ // addresses[type EQ "work"]
+ else if (expression instanceof ValuePathExpression) {
+ ValuePathExpression valuePathExpression = (ValuePathExpression) expression;
+ Predicate<Object> nestedPredicate = toPredicate(valuePathExpression.getAttributeExpression(), attribute(attributeContainer, valuePathExpression.getAttributePath()));
+ return new ValuePathPredicate<>(valuePathExpression, attributeContainer, nestedPredicate);
+ }
+ log.debug("Unsupported Filter expression of type: " + expression.getClass());
+ return scimResource -> false;
+ }
+
+
+ private static boolean isStringExpression(Schema.Attribute attribute, Object compareValue) {
+ if (attribute.getType() != Schema.Attribute.Type.STRING) {
+ log.debug("Invalid query, non String value for expression : " + attribute.getType());
+ return false;
+ }
+ if (compareValue == null) {
+ log.debug("Invalid query, empty value for expression : " + attribute.getType());
+ return false;
+ }
+ return true;
+ }
+
+ private static Schema.Attribute attribute(AttributeContainer attributeContainer, AttributeReference attributeReference) {
+ String baseAttributeName = attributeReference.getAttributeName();
+
+ Schema.Attribute schemaAttribute = attributeContainer.getAttribute(baseAttributeName);
+ if (schemaAttribute == null) {
+ log.warn("Invalid filter: attribute '" + baseAttributeName + "' is NOT a valid SCIM attribute.");
+ return null;
+ }
+
+ String subAttribute = attributeReference.getSubAttributeName();
+ if (subAttribute != null) {
+ schemaAttribute = schemaAttribute.getAttribute(subAttribute);
+ if (schemaAttribute == null) {
+ log.warn("Invalid filter: attribute '" + attributeReference.getFullyQualifiedAttributeName() + "' is NOT a valid SCIM attribute.");
+ return null;
+ }
+ }
+
+ // filter out fields like passwords that should not be queried against
+ if (schemaAttribute.getReturned() == Schema.Attribute.Returned.NEVER) {
+ log.warn("Invalid filter: attribute '" + attributeReference.getAttributeName() + "' is not filterable.");
+ return null;
+ }
+
+ return schemaAttribute;
+ }
+
+ private static abstract class AbstractAttributePredicate<T extends FilterExpression, R> implements Predicate<R> {
+
+ private static final Logger log = LoggerFactory.getLogger(InMemoryScimFilterMatcher.class);
+
+ final T expression;
+
+ final AttributeContainer attributeContainer;
+
+ final AttributeReference attributeReference;
+
+ private AbstractAttributePredicate(T expression, AttributeContainer attributeContainer, AttributeReference attributeReference) {
+ this.expression = expression;
+ this.attributeContainer = attributeContainer;
+ this.attributeReference = attributeReference;
+ }
+
+ protected abstract boolean test(Schema.Attribute attribute, Object actualValue);
+
+ @Override
+ public boolean test(R actual) {
+
+ try {
+ // get and validate attribute
+ Schema.Attribute resolvedAttribute = attribute(attributeContainer, attributeReference);
+ if (resolvedAttribute != null) {
+
+ // now walk the attribute path again to get the accessor and value
+ Schema.Attribute schemaAttribute = attributeContainer.getAttribute(attributeReference.getAttributeName());
+ actual = schemaAttribute.getAccessor().get(actual);
+
+ // if the attribute has a sub-level, continue on
+ String subAttribute = attributeReference.getSubAttributeName();
+ if (subAttribute != null) {
+ schemaAttribute = schemaAttribute.getAttribute(subAttribute);
+ actual = schemaAttribute.getAccessor().get(actual);
+ }
+ return test(schemaAttribute, actual);
+ }
+ } catch (Exception e) {
+ // The SCIM spec states to ignore the query instead of rejecting it - rfc7644 - 3.4.2
+ log.debug("Invalid SCIM filter received", e);
+ }
+
+ return false;
+ }
+ }
+
+ private static class ValuePathPredicate<R> extends AbstractAttributePredicate<ValuePathExpression, R> {
+
+ final private Predicate<Object> nestedPredicate;
+
+ ValuePathPredicate(ValuePathExpression expression, AttributeContainer attributeContainer, Predicate<Object> nestedPredicate) {
+ super(expression, attributeContainer, expression.getAttributePath());
+ this.nestedPredicate = nestedPredicate;
+ }
+
+ @Override
+ protected boolean test(Schema.Attribute attribute, Object actualValue) {
+ // actualValue must be a Collection
+ if (attribute.isMultiValued()) {
+ return ((Collection<?>) actualValue).stream().anyMatch(nestedPredicate);
+ }
+
+ return false;
+ }
+ }
+
+ private static class AttributeComparisonPredicate<R> extends AbstractAttributePredicate<AttributeComparisonExpression, R> {
+
+ private AttributeComparisonPredicate(AttributeComparisonExpression expression, AttributeContainer attributeContainer) {
+ super(expression, attributeContainer, expression.getAttributePath());
+ }
+
+ @Override
+ protected boolean test(Schema.Attribute attribute, Object actualValue) {
+
+ if (actualValue == null) {
+ return false;
+ }
+
+ if (attribute.isMultiValued()) {
+ log.warn("Invalid expression, target is collection");
+ return false;
+ }
+
+ CompareOperator op = expression.getOperation();
+ Object compareValue = expression.getCompareValue();
+
+ if (op == CompareOperator.EQ) {
+ return compareValue.equals(actualValue);
+ }
+ if (op == CompareOperator.NE) {
+ return !compareValue.equals(actualValue);
+ }
+ if (op == CompareOperator.SW) {
+ return isStringExpression(attribute, compareValue)
+ && actualValue.toString().startsWith(compareValue.toString());
+ }
+ if (op == CompareOperator.EW) {
+ return isStringExpression(attribute, compareValue)
+ && actualValue.toString().endsWith(compareValue.toString());
+ }
+ if (op == CompareOperator.CO) {
+ return isStringExpression(attribute, compareValue)
+ && actualValue.toString().contains(compareValue.toString());
+ }
+
+ if (actualValue instanceof Comparable) {
+ Comparable actual = (Comparable) actualValue;
+ Comparable compare = (Comparable) compareValue;
+ return CompareOperatorPredicate.naturalOrder(op, compare).test(actual);
+ }
+
+ throw new ScimResourceInvalidException("Unsupported operation in filter: " + op.name());
+ }
+ }
+
+ private static class CompareOperatorPredicate<T> implements Predicate<T> {
+ private final CompareOperator op;
+
+ private final Comparator<T> comparator;
+
+ private final T comparedValue;
+
+
+ private CompareOperatorPredicate(CompareOperator op, T comparedValue, Comparator<T> comparator) {
+ this.op = op;
+ this.comparator = comparator;
+ this.comparedValue = comparedValue;
+ }
+
+ @Override
+ public boolean test(T actualValue) {
+
+ int compareResult = comparator.compare(actualValue, comparedValue);
+
+ if (op == CompareOperator.LT) {
+ return compareResult < 0;
+ } else if (op == CompareOperator.GT) {
+ return compareResult > 0;
+ } else if (op == CompareOperator.LE) {
+ return compareResult <= 0;
+ } else if (op == CompareOperator.GE) {
+ return compareResult >= 0;
+ }
+ return false;
+ }
+
+ static <T extends Comparable<T>> CompareOperatorPredicate<T> naturalOrder(CompareOperator op, T comparedValue) {
+ return new CompareOperatorPredicate<>(op, comparedValue, Comparator.naturalOrder());
+ }
+ }
+
+ private static class AttributePresentPredicate<R> extends AbstractAttributePredicate<AttributePresentExpression, R> {
+ private AttributePresentPredicate(AttributePresentExpression expression, AttributeContainer attributeContainer) {
+ super(expression, attributeContainer, expression.getAttributePath());
+ }
+
+ @Override
+ protected boolean test(Schema.Attribute attribute, Object actualValue) {
+ if (attribute.isMultiValued()) {
+ log.debug("Invalid expression, target is collection");
+ return false;
+ }
+ return actualValue != null;
+ }
+ }
+}
diff --git a/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/spec/protocol/LuckyNumberExtension.java b/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/spec/protocol/LuckyNumberExtension.java
new file mode 100644
index 0000000..482cad8
--- /dev/null
+++ b/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/spec/protocol/LuckyNumberExtension.java
@@ -0,0 +1,61 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+
+* http://www.apache.org/licenses/LICENSE-2.0
+
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.directory.scim.spec.protocol;
+
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import lombok.Data;
+import org.apache.directory.scim.spec.annotation.ScimAttribute;
+import org.apache.directory.scim.spec.annotation.ScimExtensionType;
+import org.apache.directory.scim.spec.resources.ScimExtension;
+import org.apache.directory.scim.spec.schema.Schema;
+
+/**
+ * Allows a User's lucky number to be passed as part of the User's entry via
+ * the SCIM protocol.
+ *
+ * @author Chris Harm <crh5255@psu.edu>
+ */
+@XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" )
+@XmlAccessorType(XmlAccessType.NONE)
+@Data
+@ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true)
+public class LuckyNumberExtension implements ScimExtension {
+
+ public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension";
+
+ @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true)
+ @XmlElement
+ private long luckyNumber;
+
+ /**
+ * Provides the URN associated with this extension which, as defined by the
+ * SCIM specification is the extension's unique identifier.
+ *
+ * @return The extension's URN.
+ */
+ @Override
+ public String getUrn() {
+ return SCHEMA_URN;
+ }
+
+}
diff --git a/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/spec/protocol/filter/InMemoryScimFilterMatcherTest.java b/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/spec/protocol/filter/InMemoryScimFilterMatcherTest.java
new file mode 100644
index 0000000..87b7681
--- /dev/null
+++ b/scim-spec/scim-spec-protocol/src/test/java/org/apache/directory/scim/spec/protocol/filter/InMemoryScimFilterMatcherTest.java
@@ -0,0 +1,236 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+
+ * http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.directory.scim.spec.protocol.filter;
+
+import org.apache.directory.scim.spec.protocol.LuckyNumberExtension;
+import org.apache.directory.scim.spec.protocol.search.Filter;
+import org.apache.directory.scim.spec.resources.*;
+import org.apache.directory.scim.spec.schema.Meta;
+import org.apache.directory.scim.spec.schema.Schemas;
+import org.assertj.core.api.AbstractAssert;
+import org.junit.jupiter.api.Test;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+public class InMemoryScimFilterMatcherTest {
+
+ private final static ScimUser USER1 = user("user1", "User", "One")
+ .setNickName("one")
+ .setAddresses(List.of(
+ new Address()
+ .setType("home")
+ .setPrimary(true)
+ .setStreetAddress("742 Evergreen Terrace")
+ .setRegion("Springfield")
+ .setLocality("Unknown")
+ .setPostalCode("012345")
+ .setCountry("USA"),
+ new Address()
+ .setType("work")
+ .setPrimary(true)
+ .setStreetAddress("101 Reactor Way")
+ .setRegion("Springfield")
+ .setLocality("Unknown")
+ .setPostalCode("012345")
+ .setCountry("USA")
+ )); static {
+ USER1.addExtension(new LuckyNumberExtension().setLuckyNumber(111));
+ }
+
+ private final static ScimUser USER2 = user("user2", "User", "Two")
+ .setAddresses(List.of(
+ new Address()
+ .setType("home")
+ .setPrimary(true)
+ .setStreetAddress("11234 Slumvillage Pass")
+ .setRegion("Burfork")
+ .setLocality("CA")
+ .setPostalCode("221134")
+ .setCountry("USA")
+ )); static {
+ USER2.addExtension(new LuckyNumberExtension().setLuckyNumber(8));
+ }
+
+ @Test
+ public void userNameMatch() {
+ FilterAssert.assertThat(FilterBuilder.create().equalTo("userName", "user1"))
+ .matches(USER1)
+ .notMatches(USER2);
+ }
+
+ @Test
+ public void familyNameMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().equalTo("name.familyName", "Two"))
+ .matches(USER2)
+ .notMatches(USER1);
+ }
+
+ @Test
+ public void startsWithMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().startsWith("name.familyName", "Tw"))
+ .matches(USER2)
+ .notMatches(USER1);
+ }
+
+ @Test
+ public void endsWithMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().endsWith("name.familyName", "wo"))
+ .matches(USER2)
+ .notMatches(USER1);
+ }
+
+ @Test
+ public void containsMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().contains("name.familyName", "w"))
+ .matches(USER2)
+ .notMatches(USER1);
+ }
+
+ @Test
+ public void givenAndFamilyNameMatches() {
+
+ FilterBuilder filter = FilterBuilder.create()
+ .equalTo("name.givenName", "User")
+ .and(builder -> builder.equalTo("name.familyName", "Two"));
+
+ FilterAssert.assertThat(filter)
+ .matches(USER2)
+ .notMatches(USER1);
+ }
+
+ @Test
+ public void familyNameOrMatches() {
+ FilterBuilder filter = FilterBuilder.create()
+ .equalTo("name.familyName", "One")
+ .or(builder -> builder.equalTo("name.familyName", "Two"));
+
+ FilterAssert.assertThat(filter)
+ .matches(USER2)
+ .matches(USER1);
+ }
+
+ @Test
+ public void noMatchPassword() {
+ FilterAssert.assertThat(FilterBuilder.create().equalTo("password", "super-secret"))
+ .notMatches(USER1);
+ }
+
+ @Test
+ public void invertUserNameMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().not(filter -> filter.equalTo("userName", "user1")))
+ .notMatches(USER1)
+ .matches(USER2);
+ }
+
+ @Test
+ public void presentAttributeMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().present("nickName"))
+ .matches(USER1)
+ .notMatches(USER2);
+ }
+
+ @Test
+ public void valuePathExpressionMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().attributeHas("addresses", filter -> filter.equalTo("type", "work")))
+ .matches(USER1)
+ .notMatches(USER2);
+ }
+
+// @Test
+// public void extensionValueMatches() {
+// assertThat(FilterBuilder.create().equalTo("luckyNumber", 111))
+// .matches(USER1)
+// .notMatches(USER2);
+// }
+
+ @Test
+ public void metaMatches() {
+ FilterAssert.assertThat(FilterBuilder.create().lessThan("meta.lastModified", LocalDateTime.now()))
+ .matches(USER1);
+
+ FilterAssert.assertThat(FilterBuilder.create().greaterThan("meta.lastModified", LocalDateTime.now().minusYears(1)))
+ .matches(USER1);
+
+ FilterAssert.assertThat(FilterBuilder.create().greaterThanOrEquals("meta.lastModified", USER1.getMeta().getLastModified()))
+ .matches(USER1);
+
+ FilterAssert.assertThat(FilterBuilder.create().lessThanOrEquals("meta.lastModified", USER1.getMeta().getLastModified()))
+ .matches(USER1);
+
+ FilterAssert.assertThat(FilterBuilder.create().equalTo("meta.lastModified", USER1.getMeta().getLastModified()))
+ .matches(USER1);
+ }
+
+ static class FilterAssert extends AbstractAssert<FilterAssert, Filter> {
+
+ protected FilterAssert(Filter actual) {
+ super(actual, FilterAssert.class);
+ }
+
+ public FilterAssert matches(ScimUser user) {
+ isNotNull();
+ if (!FilterExpressions.inMemory(actual, Schemas.schemaFor(ScimUser.class)).test(user)) {
+ failWithMessage("Expected filter '%s' to match user '%s'", actual.toString(), user);
+ }
+ return this;
+ }
+
+ public FilterAssert notMatches(ScimUser user) {
+ isNotNull();
+ if (FilterExpressions.inMemory(actual, Schemas.schemaFor(ScimUser.class)).test(user)) {
+ failWithMessage("Expected filter '%s' to NOT match user '%s'", actual.toString(), user);
+ }
+ return this;
+ }
+
+ public static FilterAssert assertThat(Filter actual) {
+ return new FilterAssert(actual);
+ }
+
+ public static FilterAssert assertThat(FilterBuilder actual) {
+ return new FilterAssert(actual.build());
+ }
+ }
+
+ private static ScimUser user(String username, String givenName, String familyName) {
+ ScimUser user = new ScimUser()
+ .setUserName(username)
+ .setPassword("super-secret")
+ .setActive(true)
+ .setName(new Name()
+ .setGivenName(givenName)
+ .setFamilyName(familyName)
+ )
+ .setEmails(List.of(
+ new Email()
+ .setType("work")
+ .setPrimary(true)
+ .setValue(username + "@example.com"),
+ new Email()
+ .setType("personal")
+ .setValue(givenName + "." + familyName + "@example.com")
+ ));
+
+ user.setMeta(new Meta().setLastModified(LocalDateTime.now()));
+
+ return user;
+ }
+}