You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@unomi.apache.org by GitBox <gi...@apache.org> on 2021/10/17 00:32:54 UTC

[GitHub] [unomi] anatol-sialitski commented on a change in pull request #353: UNOMI-486 JSON Schema integration

anatol-sialitski commented on a change in pull request #353:
URL: https://github.com/apache/unomi/pull/353#discussion_r730055297



##########
File path: services/src/main/java/org/apache/unomi/services/impl/schemas/PropertyTypeKeyword.java
##########
@@ -0,0 +1,110 @@
+/*
+ * 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.unomi.services.impl.schemas;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.networknt.schema.*;
+import org.apache.unomi.api.PropertyType;
+import org.apache.unomi.api.services.ProfileService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.text.MessageFormat;
+import java.util.*;
+
+class PropertyTypeKeyword extends AbstractKeyword {
+
+    private static final Logger logger = LoggerFactory.getLogger(PropertyTypeKeyword.class);
+
+    private final ProfileService profileService;
+    private final SchemaRegistryImpl schemaRegistry;
+
+    private static final class PropertyTypeJsonValidator extends AbstractJsonValidator {
+
+        String schemaPath;
+        JsonNode schemaNode;
+        JsonSchema parentSchema;
+        ValidationContext validationContext;
+        ProfileService profileService;
+        SchemaRegistryImpl schemaRegistry;
+
+        public PropertyTypeJsonValidator(String keyword, String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext, ProfileService profileService, SchemaRegistryImpl schemaRegistry) {
+            super(keyword);
+            this.schemaPath = schemaPath;
+            this.schemaNode = schemaNode;
+            this.parentSchema = parentSchema;
+            this.validationContext = validationContext;
+            this.profileService = profileService;
+            this.schemaRegistry = schemaRegistry;
+        }
+
+        @Override
+        public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
+            Set<ValidationMessage> validationMessages = new HashSet<>();
+            Iterator<String> fieldNames = node.fieldNames();
+            while (fieldNames.hasNext()) {
+                String fieldName = fieldNames.next();
+                PropertyType propertyType = getPropertyType(fieldName);
+                if (propertyType == null) {
+                    validationMessages.add(buildValidationMessage(CustomErrorMessageType.of("property-not-found", new MessageFormat("{0} : Couldn''t find property type with id={1}")), at, fieldName));
+                } else {
+                    // @todo further validation, if it can be used in this context (event, profile, session)
+                    String valueTypeId = propertyType.getValueTypeId();
+                    JsonSchema jsonSchema = schemaRegistry.getJsonSchema("https://unomi.apache.org/schemas/json/values/" + valueTypeId + ".json");
+                    if (jsonSchema == null) {
+                        validationMessages.add(buildValidationMessage(CustomErrorMessageType.of("value-schema-not-found", new MessageFormat("{0} : Couldn''t find schema type with id={1}")), at, "https://unomi.apache.org/schemas/json/values/" + valueTypeId + ".json"));

Review comment:
       `Couldn't` instead of `Couldn''t`

##########
File path: services/src/main/java/org/apache/unomi/services/impl/schemas/SchemaRegistryImpl.java
##########
@@ -0,0 +1,224 @@
+/*
+ * 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.unomi.services.impl.schemas;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.networknt.schema.*;
+import com.networknt.schema.uri.URIFetcher;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.SchemaType;
+import org.apache.unomi.api.services.ProfileService;
+import org.apache.unomi.api.services.SchemaRegistry;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.SynchronousBundleListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.URL;
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class SchemaRegistryImpl implements SchemaRegistry, SynchronousBundleListener {
+
+    private static final String URI = "https://json-schema.org/draft/2019-09/schema";
+
+    private static final Logger logger = LoggerFactory.getLogger(SchemaRegistryImpl.class.getName());
+
+    private final Map<Long, List<SchemaType>> schemaTypesByBundle = new HashMap<>();
+    private final Map<String, SchemaType> schemaTypesById = new HashMap<>();
+
+    private final Map<String, JsonSchema> jsonSchemasById = new LinkedHashMap<>();
+
+    private final Map<String, Long> bundleIdBySchemaId = new HashMap<>();
+
+    private BundleContext bundleContext;
+
+    private ProfileService profileService;
+
+    public void bundleChanged(BundleEvent event) {
+        switch (event.getType()) {
+            case BundleEvent.STARTED:
+                processBundleStartup(event.getBundle().getBundleContext());
+                break;
+            case BundleEvent.STOPPING:
+                processBundleStop(event.getBundle().getBundleContext());
+                break;
+        }
+    }
+
+    public void init() {
+        processBundleStartup(bundleContext);
+
+        // process already started bundles
+        for (Bundle bundle : bundleContext.getBundles()) {
+            if (bundle.getBundleContext() != null && bundle.getBundleId() != bundleContext.getBundle().getBundleId()) {
+                processBundleStartup(bundle.getBundleContext());
+            }
+        }
+
+        bundleContext.addBundleListener(this);
+        logger.info("Schema registry initialized.");
+    }
+
+    public void destroy() {
+        bundleContext.removeBundleListener(this);
+        logger.info("Schema registry shutdown.");
+    }
+
+    public void setBundleContext(BundleContext bundleContext) {
+        this.bundleContext = bundleContext;
+    }
+
+    public void setProfileService(ProfileService profileService) {
+        this.profileService = profileService;
+    }
+
+    public boolean isValid(Object object, String schemaId) {
+        JsonSchema jsonSchema = jsonSchemasById.get(schemaId);
+        if (jsonSchema != null) {
+            try {
+                // this is a workaround to get the JsonNode from the object, maybe there is a better way (more efficient) to do this ?
+                StringWriter stringWriter = new StringWriter();
+                CustomObjectMapper.getObjectMapper().writeValue(stringWriter, object);
+                JsonNode jsonNode = CustomObjectMapper.getObjectMapper().readTree(stringWriter.toString());
+                Set<ValidationMessage> validationMessages = jsonSchema.validate(jsonNode);
+                if (validationMessages == null || validationMessages.isEmpty()) {
+                    return true;
+                }
+                for (ValidationMessage validationMessage : validationMessages) {
+                    logger.error("Error validating object against schema {}: {}", schemaId, validationMessage);
+                }
+                return false;
+            } catch (IOException e) {
+                logger.error("Error validating object with schema {}", schemaId, e);
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public List<SchemaType> getTargetSchemas(String target) {
+        return schemaTypesById.values().stream().filter(schemaType -> schemaType.getTarget().equals(target)).collect(Collectors.toList());
+    }
+
+    @Override
+    public SchemaType getSchema(String schemaId) {
+        return schemaTypesById.get(schemaId);
+    }
+
+    private void loadPredefinedSchemas(BundleContext bundleContext) {
+        Enumeration<URL> predefinedSchemas = bundleContext.getBundle().findEntries("META-INF/cxs/schemas", "*.json", true);
+        if (predefinedSchemas == null) {
+            return;
+        }
+
+        ObjectMapper objectMapper = new ObjectMapper();

Review comment:
       instance of the ObjectMapper as property of the class

##########
File path: services/src/main/java/org/apache/unomi/services/impl/schemas/SchemaRegistryImpl.java
##########
@@ -0,0 +1,224 @@
+/*
+ * 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.unomi.services.impl.schemas;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.networknt.schema.*;
+import com.networknt.schema.uri.URIFetcher;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.SchemaType;
+import org.apache.unomi.api.services.ProfileService;
+import org.apache.unomi.api.services.SchemaRegistry;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.SynchronousBundleListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.URL;
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class SchemaRegistryImpl implements SchemaRegistry, SynchronousBundleListener {
+
+    private static final String URI = "https://json-schema.org/draft/2019-09/schema";
+
+    private static final Logger logger = LoggerFactory.getLogger(SchemaRegistryImpl.class.getName());
+
+    private final Map<Long, List<SchemaType>> schemaTypesByBundle = new HashMap<>();
+    private final Map<String, SchemaType> schemaTypesById = new HashMap<>();
+
+    private final Map<String, JsonSchema> jsonSchemasById = new LinkedHashMap<>();
+
+    private final Map<String, Long> bundleIdBySchemaId = new HashMap<>();
+
+    private BundleContext bundleContext;
+
+    private ProfileService profileService;
+
+    public void bundleChanged(BundleEvent event) {
+        switch (event.getType()) {
+            case BundleEvent.STARTED:
+                processBundleStartup(event.getBundle().getBundleContext());
+                break;
+            case BundleEvent.STOPPING:
+                processBundleStop(event.getBundle().getBundleContext());
+                break;
+        }
+    }
+
+    public void init() {
+        processBundleStartup(bundleContext);
+
+        // process already started bundles
+        for (Bundle bundle : bundleContext.getBundles()) {
+            if (bundle.getBundleContext() != null && bundle.getBundleId() != bundleContext.getBundle().getBundleId()) {
+                processBundleStartup(bundle.getBundleContext());
+            }
+        }
+
+        bundleContext.addBundleListener(this);
+        logger.info("Schema registry initialized.");
+    }
+
+    public void destroy() {
+        bundleContext.removeBundleListener(this);
+        logger.info("Schema registry shutdown.");
+    }
+
+    public void setBundleContext(BundleContext bundleContext) {
+        this.bundleContext = bundleContext;
+    }
+
+    public void setProfileService(ProfileService profileService) {
+        this.profileService = profileService;
+    }
+
+    public boolean isValid(Object object, String schemaId) {
+        JsonSchema jsonSchema = jsonSchemasById.get(schemaId);
+        if (jsonSchema != null) {
+            try {
+                // this is a workaround to get the JsonNode from the object, maybe there is a better way (more efficient) to do this ?
+                StringWriter stringWriter = new StringWriter();
+                CustomObjectMapper.getObjectMapper().writeValue(stringWriter, object);
+                JsonNode jsonNode = CustomObjectMapper.getObjectMapper().readTree(stringWriter.toString());
+                Set<ValidationMessage> validationMessages = jsonSchema.validate(jsonNode);
+                if (validationMessages == null || validationMessages.isEmpty()) {
+                    return true;
+                }
+                for (ValidationMessage validationMessage : validationMessages) {
+                    logger.error("Error validating object against schema {}: {}", schemaId, validationMessage);
+                }
+                return false;
+            } catch (IOException e) {
+                logger.error("Error validating object with schema {}", schemaId, e);
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public List<SchemaType> getTargetSchemas(String target) {
+        return schemaTypesById.values().stream().filter(schemaType -> schemaType.getTarget().equals(target)).collect(Collectors.toList());
+    }
+
+    @Override
+    public SchemaType getSchema(String schemaId) {
+        return schemaTypesById.get(schemaId);
+    }
+
+    private void loadPredefinedSchemas(BundleContext bundleContext) {
+        Enumeration<URL> predefinedSchemas = bundleContext.getBundle().findEntries("META-INF/cxs/schemas", "*.json", true);
+        if (predefinedSchemas == null) {
+            return;
+        }
+
+        ObjectMapper objectMapper = new ObjectMapper();
+
+        List<SchemaType> schemaTypes = this.schemaTypesByBundle.get(bundleContext.getBundle().getBundleId());
+
+        while (predefinedSchemas.hasMoreElements()) {
+            URL predefinedSchemaURL = predefinedSchemas.nextElement();
+            logger.debug("Found predefined JSON schema at " + predefinedSchemaURL + ", loading... ");
+
+            try {

Review comment:
       what about `try-with-resources`?

##########
File path: services/src/main/java/org/apache/unomi/services/impl/schemas/SchemaRegistryImpl.java
##########
@@ -0,0 +1,224 @@
+/*
+ * 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.unomi.services.impl.schemas;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.networknt.schema.*;
+import com.networknt.schema.uri.URIFetcher;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.SchemaType;
+import org.apache.unomi.api.services.ProfileService;
+import org.apache.unomi.api.services.SchemaRegistry;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.SynchronousBundleListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.URL;
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class SchemaRegistryImpl implements SchemaRegistry, SynchronousBundleListener {
+
+    private static final String URI = "https://json-schema.org/draft/2019-09/schema";
+
+    private static final Logger logger = LoggerFactory.getLogger(SchemaRegistryImpl.class.getName());
+
+    private final Map<Long, List<SchemaType>> schemaTypesByBundle = new HashMap<>();
+    private final Map<String, SchemaType> schemaTypesById = new HashMap<>();
+
+    private final Map<String, JsonSchema> jsonSchemasById = new LinkedHashMap<>();
+
+    private final Map<String, Long> bundleIdBySchemaId = new HashMap<>();
+
+    private BundleContext bundleContext;
+
+    private ProfileService profileService;
+
+    public void bundleChanged(BundleEvent event) {
+        switch (event.getType()) {
+            case BundleEvent.STARTED:
+                processBundleStartup(event.getBundle().getBundleContext());
+                break;
+            case BundleEvent.STOPPING:
+                processBundleStop(event.getBundle().getBundleContext());
+                break;
+        }
+    }
+
+    public void init() {
+        processBundleStartup(bundleContext);
+
+        // process already started bundles
+        for (Bundle bundle : bundleContext.getBundles()) {
+            if (bundle.getBundleContext() != null && bundle.getBundleId() != bundleContext.getBundle().getBundleId()) {
+                processBundleStartup(bundle.getBundleContext());
+            }
+        }
+
+        bundleContext.addBundleListener(this);
+        logger.info("Schema registry initialized.");
+    }
+
+    public void destroy() {
+        bundleContext.removeBundleListener(this);
+        logger.info("Schema registry shutdown.");
+    }
+
+    public void setBundleContext(BundleContext bundleContext) {
+        this.bundleContext = bundleContext;
+    }
+
+    public void setProfileService(ProfileService profileService) {
+        this.profileService = profileService;
+    }
+
+    public boolean isValid(Object object, String schemaId) {
+        JsonSchema jsonSchema = jsonSchemasById.get(schemaId);
+        if (jsonSchema != null) {
+            try {
+                // this is a workaround to get the JsonNode from the object, maybe there is a better way (more efficient) to do this ?

Review comment:
       May be?
   ```
   JsonNode node = mapper.convertValue(object, JsonNode.class);
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@unomi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org