Updating exception and explanation for update node leaves
[cps.git] / cps-service / src / main / java / org / onap / cps / spi / model / DataNodeBuilder.java
index cf79ad7..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,8 +120,21 @@ 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 DataNode dataNode = new DataNode();
+        final var dataNode = new DataNode();
         dataNode.setXpath(xpath);
         dataNode.setLeaves(leaves);
         dataNode.setChildDataNodes(childDataNodes);
@@ -128,9 +142,18 @@ public class DataNodeBuilder {
     }
 
     private DataNode buildFromNormalizedNodeTree() {
-        final DataNode parentDataNode = new DataNodeBuilder().withXpath(parentNodeXpath).build();
+        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,
@@ -187,7 +210,7 @@ public class DataNodeBuilder {
 
     private static DataNode createAndAddChildDataNode(final DataNode parentDataNode, final String childXpath) {
 
-        final DataNode newChildDataNode = new DataNodeBuilder()
+        final var newChildDataNode = new DataNodeBuilder()
             .withXpath(parentDataNode.getXpath() + childXpath)
             .build();
         final Set<DataNode> allChildDataNodes = new ImmutableSet.Builder<DataNode>()