Update MRI projects for Aluminium
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / get / FilterContentValidator.java
index 459ae7c8a443e8d9daa4547658bbe646df291305..0ec329012ebb72008a192edfe0ee8860ccee168a 100644 (file)
@@ -7,10 +7,8 @@
  */
 package org.opendaylight.netconf.mdsal.connector.ops.get;
 
-import static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
 import static org.opendaylight.yangtools.yang.data.util.ParserStreamUtils.findSchemaNodeByNameAndNamespace;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -21,18 +19,30 @@ import java.util.Deque;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
+import java.util.Optional;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.stream.XMLStreamWriter;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
+import org.opendaylight.netconf.api.xml.XmlElement;
 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
+import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.util.codec.TypeAwareCodec;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
 
 /**
  * Class validates filter content against schema context.
@@ -42,9 +52,6 @@ public class FilterContentValidator {
     private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
     private final CurrentSchemaContext schemaContext;
 
-    /**
-     * @param schemaContext current schema context
-     */
     public FilterContentValidator(final CurrentSchemaContext schemaContext) {
         this.schemaContext = schemaContext;
     }
@@ -52,23 +59,24 @@ public class FilterContentValidator {
     /**
      * Validates filter content against this validator schema context. If the filter is valid,
      * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
+     *
      * @param filterContent filter content
      * @return YangInstanceIdentifier
-     * @throws DocumentedException if filter content is not valid
+     * @throws DocumentedException if filter content validation failed
      */
     public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException {
         try {
             final URI namespace = new URI(filterContent.getNamespace());
-            final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
+            final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next();
             final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
-            final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(),
-                    Type.OTHER, schema));
+            final FilterTree filterTree = validateNode(
+                    filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema));
             return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
-        } catch (final DocumentedException e) {
-            throw e;
-        } catch (final Exception e) {
+        } catch (final URISyntaxException e) {
+            throw new RuntimeException("Wrong namespace in element + " + filterContent.toString(), e);
+        } catch (final ValidationException e) {
             LOG.debug("Filter content isn't valid", e);
-            throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
+            throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e,
                     DocumentedException.ErrorType.APPLICATION,
                     DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
                     DocumentedException.ErrorSeverity.ERROR);
@@ -76,24 +84,24 @@ public class FilterContentValidator {
     }
 
     /**
-     * Returns module's child data node of given name space and name
-     * @param module module
+     * Returns module's child data node of given name space and name.
+     *
+     * @param module    module
      * @param nameSpace name space
-     * @param name name
+     * @param name      name
      * @return child data node schema
      * @throws DocumentedException if child with given name is not present
      */
     private DataSchemaNode getRootDataSchemaNode(final Module module, final URI nameSpace, final String name)
             throws DocumentedException {
-        final Collection<DataSchemaNode> childNodes = module.getChildNodes();
-        for (final DataSchemaNode childNode : childNodes) {
+        for (final DataSchemaNode childNode : module.getChildNodes()) {
             final QName qName = childNode.getQName();
             if (qName.getNamespace().equals(nameSpace) && qName.getLocalName().equals(name)) {
                 return childNode;
             }
         }
-        throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " +
-                schemaContext.getCurrentContext().toString(),
+        throw new DocumentedException("Unable to find node with namespace: " + nameSpace
+                    + "in schema context: " + schemaContext.getCurrentContext().toString(),
                 DocumentedException.ErrorType.APPLICATION,
                 DocumentedException.ErrorTag.UNKNOWN_NAMESPACE,
                 DocumentedException.ErrorSeverity.ERROR);
@@ -101,9 +109,10 @@ public class FilterContentValidator {
 
     /**
      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
-     * @param element element to check
+     *
+     * @param element          element to check
      * @param parentNodeSchema parent node schema
-     * @param tree parent node tree
+     * @param tree             parent node tree
      * @return tree
      * @throws ValidationException if filter content is not valid
      */
@@ -124,7 +133,7 @@ public class FilterContentValidator {
                 final DataSchemaNode childSchema = path.getLast();
                 validateNode(childElement, childSchema, subtree);
             } catch (URISyntaxException | MissingNameSpaceException e) {
-                throw new RuntimeException("Wrong namespace in element + " + childElement.toString());
+                throw new RuntimeException("Wrong namespace in element + " + childElement.toString(), e);
             }
         }
         return tree;
@@ -134,9 +143,10 @@ public class FilterContentValidator {
      * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
      * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
      * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
-     * @param tree QName tree
+     *
+     * @param tree          QName tree
      * @param filterContent filter element
-     * @param builder builder  @return YangInstanceIdentifier
+     * @param builder       builder  @return YangInstanceIdentifier
      */
     private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
                                                      final InstanceIdentifierBuilder builder) {
@@ -164,15 +174,15 @@ public class FilterContentValidator {
                                     final InstanceIdentifierBuilder builder) {
         Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
         final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
-        final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
-        final Map<QName, Object> map = getKeyValues(pathToList, filterContent, keyDefinition);
+
+        final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
         if (!map.isEmpty()) {
             builder.nodeWithKey(tree.getName(), map);
         }
     }
 
     private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
-                                            final List<QName> keyDefinition) {
+                                            final ListSchemaNode listSchemaNode) {
         XmlElement current = filterContent;
         //find list element
         for (final String pathElement : path) {
@@ -184,19 +194,44 @@ public class FilterContentValidator {
             current = childElements.get(0);
         }
         final Map<QName, Object> keys = new HashMap<>();
-        for (final QName qName : keyDefinition) {
-            final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
+        final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
+        for (final QName qualifiedName : keyDefinition) {
+            final Optional<XmlElement> childElements =
+                    current.getOnlyChildElementOptionally(qualifiedName.getLocalName());
             if (!childElements.isPresent()) {
                 return Collections.emptyMap();
             }
             final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
             if (keyValue.isPresent()) {
-                keys.put(qName, keyValue.get());
+                final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qualifiedName);
+                if (listKey instanceof IdentityrefTypeDefinition) {
+                    keys.put(qualifiedName, keyValue.get());
+                } else {
+                    final TypeDefinition<? extends TypeDefinition<?>> keyType = listKey.getType();
+                    if (keyType instanceof IdentityrefTypeDefinition || keyType instanceof LeafrefTypeDefinition) {
+                        final Document document = filterContent.getDomElement().getOwnerDocument();
+                        final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
+                        final XmlCodecFactory xmlCodecFactory =
+                                XmlCodecFactory.create(schemaContext.getCurrentContext());
+                        final TypeAwareCodec<?, NamespaceContext, XMLStreamWriter> typeCodec =
+                                xmlCodecFactory.codecFor(listKey);
+                        final Object deserializedKeyValue = typeCodec.parseValue(nsContext, keyValue.get());
+                        keys.put(qualifiedName, deserializedKeyValue);
+                    } else {
+                        final Object deserializedKey = TypeDefinitionAwareCodec.from(keyType)
+                                .deserialize(keyValue.get());
+                        keys.put(qualifiedName, deserializedKey);
+                    }
+                }
             }
         }
         return keys;
     }
 
+    private enum Type {
+        LIST, CHOICE_CASE, OTHER
+    }
+
     /**
      * Class represents tree of QNames as they are present in the filter.
      */
@@ -215,20 +250,20 @@ public class FilterContentValidator {
         }
 
         FilterTree addChild(final DataSchemaNode data) {
-            final Type type;
-            if (data instanceof ChoiceCaseNode) {
-                type = Type.CHOICE_CASE;
+            final Type childType;
+            if (data instanceof CaseSchemaNode) {
+                childType = Type.CHOICE_CASE;
             } else if (data instanceof ListSchemaNode) {
-                type = Type.LIST;
+                childType = Type.LIST;
             } else {
-                type = Type.OTHER;
+                childType = Type.OTHER;
             }
-            final QName name = data.getQName();
-            FilterTree childTree = children.get(name);
+            final QName childName = data.getQName();
+            FilterTree childTree = children.get(childName);
             if (childTree == null) {
-                childTree = new FilterTree(name, type, data);
+                childTree = new FilterTree(childName, childType, data);
             }
-            children.put(name, childTree);
+            children.put(childName, childTree);
             return childTree;
         }
 
@@ -249,12 +284,10 @@ public class FilterContentValidator {
         }
     }
 
-    private enum Type {
-        LIST, CHOICE_CASE, OTHER
-    }
-
     private static class ValidationException extends Exception {
-        public ValidationException(final XmlElement parent, final XmlElement child) {
+        private static final long serialVersionUID = 1L;
+
+        ValidationException(final XmlElement parent, final XmlElement child) {
             super("Element " + child + " can't be child of " + parent);
         }
     }