Updating exception and explanation for update node leaves
[cps.git] / cps-service / src / main / java / org / onap / cps / spi / model / DataNodeBuilder.java
index 253d4c6..4a9957d 100644 (file)
@@ -29,6 +29,7 @@ import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
 import lombok.extern.slf4j.Slf4j;
+import org.onap.cps.spi.exceptions.DataValidationException;
 import org.onap.cps.utils.YangUtils;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
@@ -119,6 +120,19 @@ public class DataNodeBuilder {
         }
     }
 
+    /**
+     * To build a {@link Collection} of {@link DataNode} objects.
+     *
+     * @return {@link DataNode} {@link Collection}
+     */
+    public Collection<DataNode> buildCollection() {
+        if (normalizedNodeTree != null) {
+            return buildCollectionFromNormalizedNodeTree();
+        } else {
+            return Set.of(buildFromAttributes());
+        }
+    }
+
     private DataNode buildFromAttributes() {
         final var dataNode = new DataNode();
         dataNode.setXpath(xpath);
@@ -128,9 +142,18 @@ public class DataNodeBuilder {
     }
 
     private DataNode buildFromNormalizedNodeTree() {
+        final Collection<DataNode> dataNodeCollection = buildCollectionFromNormalizedNodeTree();
+        if (!dataNodeCollection.iterator().hasNext()) {
+            throw new DataValidationException(
+                "Unsupported xpath: ", "Unsupported xpath as it is referring to one element");
+        }
+        return dataNodeCollection.iterator().next();
+    }
+
+    private Collection<DataNode> buildCollectionFromNormalizedNodeTree() {
         final var parentDataNode = new DataNodeBuilder().withXpath(parentNodeXpath).build();
         addDataNodeFromNormalizedNode(parentDataNode, normalizedNodeTree);
-        return parentDataNode.getChildDataNodes().iterator().next();
+        return parentDataNode.getChildDataNodes();
     }
 
     private static void addDataNodeFromNormalizedNode(final DataNode currentDataNode,