CPS-1401 Implement V2 of GET Data Node API
[cps.git] / cps-ri / src / test / groovy / org / onap / cps / spi / impl / CpsDataPersistenceServiceIntegrationSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2023 Nordix Foundation
4  *  Modifications Copyright (C) 2021 Pantheon.tech
5  *  Modifications Copyright (C) 2021-2022 Bell Canada.
6  *  Modifications Copyright (C) 2022-2023 TechMahindra Ltd.
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.spi.impl
25
26 import com.fasterxml.jackson.databind.ObjectMapper
27 import com.google.common.collect.ImmutableSet
28 import org.onap.cps.cpspath.parser.PathParsingException
29 import org.onap.cps.spi.CpsDataPersistenceService
30 import org.onap.cps.spi.entities.FragmentEntity
31 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch
32 import org.onap.cps.spi.exceptions.AnchorNotFoundException
33 import org.onap.cps.spi.exceptions.CpsAdminException
34 import org.onap.cps.spi.exceptions.CpsPathException
35 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
36 import org.onap.cps.spi.exceptions.DataspaceNotFoundException
37 import org.onap.cps.spi.model.DataNode
38 import org.onap.cps.spi.model.DataNodeBuilder
39 import org.onap.cps.utils.JsonObjectMapper
40 import org.springframework.beans.factory.annotation.Autowired
41 import org.springframework.test.context.jdbc.Sql
42
43 import javax.validation.ConstraintViolationException
44 import java.nio.file.Path
45
46 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
47 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS
48
49 class CpsDataPersistenceServiceIntegrationSpec extends CpsPersistenceSpecBase {
50
51     @Autowired
52     CpsDataPersistenceService objectUnderTest
53
54     static JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
55     static DataNodeBuilder dataNodeBuilder = new DataNodeBuilder()
56
57     static final String SET_DATA = '/data/fragment.sql'
58     static int DATASPACE_1001_ID = 1001L
59     static int ANCHOR_3003_ID = 3003L
60     static long ID_DATA_NODE_WITH_DESCENDANTS = 4001
61     static String XPATH_DATA_NODE_WITH_DESCENDANTS = '/parent-1'
62     static String XPATH_DATA_NODE_WITH_LEAVES = '/parent-207'
63     static long DATA_NODE_202_FRAGMENT_ID = 4202L
64     static long CHILD_OF_DATA_NODE_202_FRAGMENT_ID = 4203L
65     static long LIST_DATA_NODE_PARENT201_FRAGMENT_ID = 4206L
66     static long LIST_DATA_NODE_PARENT203_FRAGMENT_ID = 4214L
67     static long LIST_DATA_NODE_PARENT202_FRAGMENT_ID = 4211L
68     static long PARENT_3_FRAGMENT_ID = 4003L
69
70     static Collection<DataNode> newDataNodes = [new DataNodeBuilder().build()]
71     static Collection<DataNode> existingDataNodes = [createDataNodeTree(XPATH_DATA_NODE_WITH_DESCENDANTS)]
72     static Collection<DataNode> existingChildDataNodes = [createDataNodeTree('/parent-1/child-1')]
73
74     def static deleteTestParentXPath = '/parent-200'
75     def static deleteTestChildXpath = "${deleteTestParentXPath}/child-with-slash[@key='a/b']"
76     def static deleteTestGrandChildXPath = "${deleteTestChildXpath}/grandChild"
77
78     def expectedLeavesByXpathMap = [
79             '/parent-207'                      : ['parent-leaf': 'parent-leaf value'],
80             '/parent-207/child-001'            : ['first-child-leaf': 'first-child-leaf value'],
81             '/parent-207/child-002'            : ['second-child-leaf': 'second-child-leaf value'],
82             '/parent-207/child-002/grand-child': ['grand-child-leaf': 'grand-child-leaf value']
83     ]
84
85     @Sql([CLEAR_DATA, SET_DATA])
86     def 'Get all datanodes with descendants .'() {
87         when: 'data nodes are retrieved by their xpath'
88             def dataNodes = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_NAME1, ['/parent-1'], INCLUDE_ALL_DESCENDANTS)
89         then: 'same data nodes are returned by getDataNodesForMultipleXpaths method'
90             assert objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME1, '/parent-1', INCLUDE_ALL_DESCENDANTS) == dataNodes
91         and: 'the dataNodes have no prefix (to be addressed by CPS-1301)'
92             assert dataNodes[0].moduleNamePrefix == null
93     }
94
95     @Sql([CLEAR_DATA, SET_DATA])
96     def 'Storing and Retrieving a new DataNodes with descendants.'() {
97         when: 'a fragment with descendants is stored'
98             def parentXpath = '/parent-new'
99             def childXpath = '/parent-new/child-new'
100             def grandChildXpath = '/parent-new/child-new/grandchild-new'
101             def dataNodes = [createDataNodeTree(parentXpath, childXpath, grandChildXpath)]
102             objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, dataNodes)
103         then: 'it can be retrieved by its xpath'
104             def dataNode = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, INCLUDE_ALL_DESCENDANTS)
105             assert dataNode[0].xpath == parentXpath
106         and: 'it has the correct child'
107             assert dataNode[0].childDataNodes.size() == 1
108             def childDataNode = dataNode[0].childDataNodes[0]
109             assert childDataNode.xpath == childXpath
110         and: 'and its grandchild'
111             assert childDataNode.childDataNodes.size() == 1
112             def grandChildDataNode = childDataNode.childDataNodes[0]
113             assert grandChildDataNode.xpath == grandChildXpath
114     }
115
116     @Sql([CLEAR_DATA, SET_DATA])
117     def 'Store data node for multiple anchors using the same schema.'() {
118         def xpath = '/parent-new'
119         given: 'a fragment is stored for an anchor'
120             objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME1, [createDataNodeTree(xpath)])
121         when: 'another fragment is stored for an other anchor, using the same schema set'
122             objectUnderTest.storeDataNodes(DATASPACE_NAME, ANCHOR_NAME3, [createDataNodeTree(xpath)])
123         then: 'both fragments can be retrieved by their xpath'
124             def fragment1 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME1, xpath)
125             fragment1.anchor.name == ANCHOR_NAME1
126             fragment1.xpath == xpath
127             def fragment2 = getFragmentByXpath(DATASPACE_NAME, ANCHOR_NAME3, xpath)
128             fragment2.anchor.name == ANCHOR_NAME3
129             fragment2.xpath == xpath
130     }
131
132     @Sql([CLEAR_DATA, SET_DATA])
133     def 'Store datanodes error scenario: #scenario.'() {
134         when: 'attempt to store a data node with #scenario'
135             objectUnderTest.storeDataNodes(dataspaceName, anchorName, dataNodes)
136         then: 'a #expectedException is thrown'
137             thrown(expectedException)
138         where: 'the following data is used'
139             scenario                    | dataspaceName  | anchorName     | dataNodes          || expectedException
140             'dataspace does not exist'  | 'unknown'      | 'not-relevant' | newDataNodes       || DataspaceNotFoundException
141             'schema set does not exist' | DATASPACE_NAME | 'unknown'      | newDataNodes       || AnchorNotFoundException
142             'anchor already exists'     | DATASPACE_NAME | ANCHOR_NAME1   | newDataNodes       || ConstraintViolationException
143             'datanode already exists'   | DATASPACE_NAME | ANCHOR_NAME1   | existingDataNodes  || AlreadyDefinedExceptionBatch
144     }
145
146     @Sql([CLEAR_DATA, SET_DATA])
147     def 'Add children to a Fragment that already has a child.'() {
148         given: 'collection of new child data nodes'
149             def newChild1 = createDataNodeTree('/parent-1/child-2')
150             def newChild2 = createDataNodeTree('/parent-1/child-3')
151             def newChildrenCollection = [newChild1, newChild2]
152         when: 'the child is added to an existing parent with 1 child'
153             objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, newChildrenCollection)
154         then: 'the parent is now has to 3 children'
155             def expectedExistingChildPath = '/parent-1/child-1'
156             def parentFragment = fragmentRepository.findById(ID_DATA_NODE_WITH_DESCENDANTS).orElseThrow()
157             parentFragment.childFragments.size() == 3
158         and: 'it still has the old child'
159             parentFragment.childFragments.find({ it.xpath == expectedExistingChildPath })
160         and: 'it has the new children'
161             parentFragment.childFragments.find({ it.xpath == newChildrenCollection[0].xpath })
162             parentFragment.childFragments.find({ it.xpath == newChildrenCollection[1].xpath })
163     }
164
165     @Sql([CLEAR_DATA, SET_DATA])
166     def 'Add child error scenario: #scenario.'() {
167         when: 'attempt to add a child data node with #scenario'
168             objectUnderTest.addChildDataNodes(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, dataNodes)
169         then: 'a #expectedException is thrown'
170             thrown(expectedException)
171         where: 'the following data is used'
172             scenario                 | parentXpath                      | dataNodes               || expectedException
173             'parent does not exist'  | '/unknown'                       | newDataNodes            || DataNodeNotFoundException
174             'already existing child' | XPATH_DATA_NODE_WITH_DESCENDANTS | existingChildDataNodes  || AlreadyDefinedExceptionBatch
175     }
176
177     @Sql([CLEAR_DATA, SET_DATA])
178     def 'Add collection of multiple new list elements including an element with a child datanode.'() {
179         given: 'two new child list elements for an existing parent'
180             def listElementXpaths = ['/parent-201/child-204[@key="NEW1"]', '/parent-201/child-204[@key="NEW2"]']
181             def listElements = toDataNodes(listElementXpaths)
182         and: 'a (grand)child data node for one of the new list elements'
183             def grandChild = buildDataNode('/parent-201/child-204[@key="NEW1"]/grand-child-204[@key2="NEW1-CHILD"]', [leave:'value'], [])
184             listElements[0].childDataNodes = [grandChild]
185         when: 'the new data node (list elements) are added to an existing parent node'
186             objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_NAME3, '/parent-201', [listElements])
187         then: 'new entries are successfully persisted, parent node now contains 5 children (2 new + 3 existing before)'
188             def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT201_FRAGMENT_ID)
189             def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
190             assert allChildXpaths.size() == 5
191             assert allChildXpaths.containsAll(listElementXpaths)
192         and: 'the (grand)child node of the new list entry is also present'
193             def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
194             def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_NAME3)
195             def grandChildFragmentEntity = fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, grandChild.xpath)
196             assert grandChildFragmentEntity.isPresent()
197     }
198
199     @Sql([CLEAR_DATA, SET_DATA])
200     def 'Add multiple list with a mix of existing and new elements'() {
201         given: 'two new child list elements for an existing parent'
202             def existingDataNode = dataNodeBuilder.withXpath('/parent-207/child-001').withLeaves(['id': '001']).build()
203             def newDataNode1 = dataNodeBuilder.withXpath('/parent-207/child-new1').withLeaves(['id': 'new1']).build()
204             def newDataNode2 = dataNodeBuilder.withXpath('/parent-200/child-new2').withLeaves(['id': 'new2']).build()
205             def dataNodeList1 = [existingDataNode, newDataNode1]
206             def dataNodeList2 = [newDataNode2]
207         when: 'duplicate data node is requested to be added'
208             objectUnderTest.addMultipleLists(DATASPACE_NAME, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT, '/', [dataNodeList1, dataNodeList2])
209         then: 'already defined batch exception is thrown'
210             def thrown = thrown(AlreadyDefinedExceptionBatch)
211         and: 'it only contains the xpath(s) of the duplicated elements'
212             assert thrown.alreadyDefinedXpaths.size() == 1
213             assert thrown.alreadyDefinedXpaths.contains('/parent-207/child-001')
214         and: 'it does NOT contains the xpaths of the new element that were not combined with existing elements'
215             assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
216             assert !thrown.alreadyDefinedXpaths.contains('/parent-207/child-new1')
217         and: 'the new entity is inserted correctly'
218             def dataspaceEntity = dataspaceRepository.getByName(DATASPACE_NAME)
219             def anchorEntity = anchorRepository.getByDataspaceAndName(dataspaceEntity, ANCHOR_HAVING_SINGLE_TOP_LEVEL_FRAGMENT)
220             fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspaceEntity, anchorEntity, '/parent-200/child-new2').isPresent()
221     }
222
223     @Sql([CLEAR_DATA, SET_DATA])
224     def 'Add list element error scenario: #scenario.'() {
225         given: 'list element as a collection of data nodes'
226             def listElements = toDataNodes(listElementXpaths)
227         when: 'attempt to add list elements to parent node'
228             objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME3, parentNodeXpath, listElements)
229         then: 'a #expectedException is thrown'
230             thrown(expectedException)
231         where: 'following parameters were used'
232             scenario                        | parentNodeXpath | listElementXpaths                   || expectedException
233             'parent node does not exist'    | '/unknown'      | ['irrelevant']                      || DataNodeNotFoundException
234             'data fragment already exists'  | '/parent-201'   | ["/parent-201/child-204[@key='A']"] || AlreadyDefinedExceptionBatch
235     }
236
237     @Sql([CLEAR_DATA, SET_DATA])
238     def 'Get all data nodes by single xpath without descendants : #scenario'() {
239         when: 'data nodes are requested'
240             def result = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
241                 [inputXPath], OMIT_DESCENDANTS)
242         then: 'data nodes under root are returned'
243             assert result.childDataNodes.size() == 2
244         and: 'no descendants of parent nodes are returned'
245             result.each {assert it.childDataNodes.size() == 0}
246         and: 'same data nodes are returned when V2 of get Data Nodes API is executed'
247             assert objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
248                 inputXPath, OMIT_DESCENDANTS) == result
249         where: 'the following xpath is used'
250             scenario      | inputXPath
251             'root xpath'  | '/'
252             'empty xpath' | ''
253     }
254
255     @Sql([CLEAR_DATA, SET_DATA])
256     def 'Cps Path query with syntax error throws a CPS Path Exception.'() {
257         when: 'trying to execute a query with a syntax (parsing) error'
258             objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, 'invalid-cps-path/child' , OMIT_DESCENDANTS)
259         then: 'exception is thrown'
260             def exceptionThrown = thrown(PathParsingException)
261             assert exceptionThrown.getMessage().contains('failed to parse at line 1 due to extraneous input \'invalid-cps-path\' expecting \'/\'')
262     }
263
264     @Sql([CLEAR_DATA, SET_DATA])
265     def 'Get all data nodes by single xpath with all descendants : #scenario'() {
266         when: 'data nodes are requested with all descendants'
267             def result = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
268                 [inputXPath], INCLUDE_ALL_DESCENDANTS)
269             def mappedResult = multipleTreesToFlatMapByXpath(new HashMap<>(), result)
270         then: 'data nodes are returned with all the descendants populated'
271             assert mappedResult.size() == 8
272             assert result.childDataNodes.size() == 2
273             assert mappedResult.get('/parent-208/child-001').childDataNodes.size() == 0
274             assert mappedResult.get('/parent-208/child-002').childDataNodes.size() == 1
275             assert mappedResult.get('/parent-209/child-001').childDataNodes.size() == 0
276             assert mappedResult.get('/parent-209/child-002').childDataNodes.size() == 1
277         and: 'same data nodes are returned when V2 of Get Data Nodes API is executed'
278             assert objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_WITH_MULTIPLE_TOP_LEVEL_FRAGMENTS,
279                 inputXPath, INCLUDE_ALL_DESCENDANTS) == result
280         where: 'the following data is used'
281             scenario      | inputXPath
282             'root xpath'  | '/'
283             'empty xpath' | ''
284     }
285
286     @Sql([CLEAR_DATA, SET_DATA])
287     def 'Get data nodes error scenario : #scenario.'() {
288         when: 'attempt to get data nodes with #scenario'
289             objectUnderTest.getDataNodes(dataspaceName, anchorName, xpath, OMIT_DESCENDANTS)
290         then: 'an #expectedException is thrown'
291             thrown(expectedException)
292         where: 'the following data is used'
293             scenario             | dataspaceName  | anchorName                        | xpath           || expectedException
294             'non existing xpath' | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NO-XPATH'     || DataNodeNotFoundException
295             'invalid Xpath'      | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'INVALID XPATH' || PathParsingException
296     }
297
298     @Sql([CLEAR_DATA, SET_DATA])
299     def 'Get data nodes for multiple xpaths.'() {
300         when: 'fetch #scenario.'
301             def results = objectUnderTest.getDataNodesForMultipleXpaths(DATASPACE_NAME, ANCHOR_NAME3, inputXpaths, OMIT_DESCENDANTS)
302         then: 'the expected number of data nodes are returned'
303             assert results.size() == expectedResultSize
304         where: 'following parameters were used'
305             scenario                               | inputXpaths                                     || expectedResultSize
306             '0 nodes'                              | []                                              || 0
307             '1 node'                               | ["/parent-200"]                                 || 1
308             '2 unique nodes'                       | ["/parent-200", "/parent-201"]                  || 2
309             '3 unique nodes'                       | ["/parent-200", "/parent-201", "/parent-202"]   || 3
310             '1 unique node with duplicate xpath'   | ["/parent-200", "/parent-200"]                  || 1
311             '2 unique nodes with duplicate xpath'  | ["/parent-200", "/parent-202", "/parent-200"]   || 2
312             'list element with key (single quote)' | ["/parent-201/child-204[@key='A']"]             || 1
313             'list element with key (double quote)' | ['/parent-201/child-204[@key="A"]']             || 1
314             'non-existing xpath'                   | ["/NO-XPATH"]                                   || 0
315             'existing and non-existing xpaths'     | ["/parent-200", "/NO-XPATH", "/parent-201"]     || 2
316             'invalid xpath'                        | ["INVALID XPATH"]                               || 0
317             'valid and invalid xpaths'             | ["/parent-200", "INVALID XPATH", "/parent-201"] || 2
318             'root xpath'                           | ["/"]                                           || 7
319             'empty (root) xpath'                   | [""]                                            || 7
320             'root and top-level xpaths'            | ["/", "/parent-200", "/parent-201"]             || 7
321             'root and child xpaths'                | ["/", "/parent-200/child-201"]                  || 8
322     }
323
324     @Sql([CLEAR_DATA, SET_DATA])
325     def 'Get data nodes for collection of xpath error scenario : #scenario.'() {
326         when: 'attempt to get data nodes with #scenario'
327             objectUnderTest.getDataNodesForMultipleXpaths(dataspaceName, anchorName, ['/not-relevant'], OMIT_DESCENDANTS)
328         then: 'a #expectedException is thrown'
329             thrown(expectedException)
330         where: 'the following data is used'
331             scenario                 | dataspaceName  | anchorName     || expectedException
332             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant' || DataspaceNotFoundException
333             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'    || AnchorNotFoundException
334     }
335
336     @Sql([CLEAR_DATA, SET_DATA])
337     def 'Update data node leaves.'() {
338         when: 'update is performed for leaves'
339             objectUnderTest.updateDataLeaves(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES,
340                     '/parent-200/child-201', ['leaf-value': 'new'])
341         then: 'leaves are updated for selected data node'
342             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
343             def updatedLeaves = getLeavesMap(updatedFragment)
344             assert updatedLeaves.size() == 1
345             assert updatedLeaves.'leaf-value' == 'new'
346         and: 'existing child entry remains as is'
347             def childFragment = updatedFragment.childFragments.iterator().next()
348             def childLeaves = getLeavesMap(childFragment)
349             assert childFragment.id == CHILD_OF_DATA_NODE_202_FRAGMENT_ID
350             assert childLeaves.'leaf-value' == 'original'
351     }
352
353     @Sql([CLEAR_DATA, SET_DATA])
354     def 'Update data leaves error scenario: #scenario.'() {
355         when: 'attempt to update data node for #scenario'
356             objectUnderTest.updateDataLeaves(dataspaceName, anchorName, xpath, ['leaf-name': 'leaf-value'])
357         then: 'a #expectedException is thrown'
358             thrown(expectedException)
359         where: 'the following data is used'
360             scenario                 | dataspaceName  | anchorName                        | xpath                 || expectedException
361             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | '/not relevant'       || DataspaceNotFoundException
362             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | '/not relevant'       || AnchorNotFoundException
363             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING-XPATH' || DataNodeNotFoundException
364     }
365
366     @Sql([CLEAR_DATA, SET_DATA])
367     def 'Update data node and descendants by removing descendants.'() {
368         given: 'data node object with leaves updated, no children'
369             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [])
370         when: 'update data nodes and descendants is performed'
371             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
372         then: 'leaves have been updated for selected data node'
373             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
374             def updatedLeaves = getLeavesMap(updatedFragment)
375             assert updatedLeaves.size() == 1
376             assert updatedLeaves.'leaf-value' == 'new'
377         and: 'updated entry has no children'
378             updatedFragment.childFragments.isEmpty()
379         and: 'previously attached child entry is removed from database'
380             fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
381     }
382
383     @Sql([CLEAR_DATA, SET_DATA])
384     def 'Update data node and descendants with new descendants'() {
385         given: 'data node object with leaves updated, having child with old content'
386             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
387                   buildDataNode('/parent-200/child-201/grand-child', ['leaf-value': 'original'], [])
388             ])
389         when: 'update is performed including descendants'
390             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
391         then: 'leaves have been updated for selected data node'
392             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
393             def updatedLeaves = getLeavesMap(updatedFragment)
394             assert updatedLeaves.size() == 1
395             assert updatedLeaves.'leaf-value' == 'new'
396         and: 'existing child entry is not updated as content is same'
397             def childFragment = updatedFragment.childFragments.iterator().next()
398             childFragment.xpath == '/parent-200/child-201/grand-child'
399             def childLeaves = getLeavesMap(childFragment)
400             assert childLeaves.'leaf-value' == 'original'
401     }
402
403     @Sql([CLEAR_DATA, SET_DATA])
404     def 'Update data node and descendants with same descendants but changed leaf value.'() {
405         given: 'data node object with leaves updated, having child with old content'
406             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
407                     buildDataNode('/parent-200/child-201/grand-child', ['leaf-value': 'new'], [])
408             ])
409         when: 'update is performed including descendants'
410             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
411         then: 'leaves have been updated for selected data node'
412             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
413             def updatedLeaves = getLeavesMap(updatedFragment)
414             assert updatedLeaves.size() == 1
415             assert updatedLeaves.'leaf-value' == 'new'
416         and: 'existing child entry is updated with the new content'
417             def childFragment = updatedFragment.childFragments.iterator().next()
418             childFragment.xpath == '/parent-200/child-201/grand-child'
419             def childLeaves = getLeavesMap(childFragment)
420             assert childLeaves.'leaf-value' == 'new'
421     }
422
423     @Sql([CLEAR_DATA, SET_DATA])
424     def 'Update data node and descendants with different descendants xpath'() {
425         given: 'data node object with leaves updated, having child with old content'
426             def submittedDataNode = buildDataNode('/parent-200/child-201', ['leaf-value': 'new'], [
427                     buildDataNode('/parent-200/child-201/grand-child-new', ['leaf-value': 'new'], [])
428             ])
429         when: 'update is performed including descendants'
430             objectUnderTest.updateDataNodeAndDescendants(DATASPACE_NAME, ANCHOR_FOR_DATA_NODES_WITH_LEAVES, submittedDataNode)
431         then: 'leaves have been updated for selected data node'
432             def updatedFragment = fragmentRepository.getById(DATA_NODE_202_FRAGMENT_ID)
433             def updatedLeaves = getLeavesMap(updatedFragment)
434             assert updatedLeaves.size() == 1
435             assert updatedLeaves.'leaf-value' == 'new'
436         and: 'previously attached child entry is removed from database'
437             fragmentRepository.findById(CHILD_OF_DATA_NODE_202_FRAGMENT_ID).isEmpty()
438         and: 'new child entry is persisted'
439             def childFragment = updatedFragment.childFragments.iterator().next()
440             childFragment.xpath == '/parent-200/child-201/grand-child-new'
441             def childLeaves = getLeavesMap(childFragment)
442             assert childLeaves.'leaf-value' == 'new'
443     }
444
445     @Sql([CLEAR_DATA, SET_DATA])
446     def 'Update data node and descendants error scenario: #scenario.'() {
447         given: 'data node object'
448             def submittedDataNode = buildDataNode(xpath, ['leaf-name': 'leaf-value'], [])
449         when: 'attempt to update data node for #scenario'
450             objectUnderTest.updateDataNodeAndDescendants(dataspaceName, anchorName, submittedDataNode)
451         then: 'a #expectedException is thrown'
452             thrown(expectedException)
453         where: 'the following data is used'
454             scenario                 | dataspaceName  | anchorName                        | xpath                 || expectedException
455             'non-existing dataspace' | 'NO DATASPACE' | 'not relevant'                    | '/not relevant'       || DataspaceNotFoundException
456             'non-existing anchor'    | DATASPACE_NAME | 'NO ANCHOR'                       | '/not relevant'       || AnchorNotFoundException
457             'non-existing xpath'     | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | '/NON-EXISTING-XPATH' || DataNodeNotFoundException
458             'invalid xpath'          | DATASPACE_NAME | ANCHOR_FOR_DATA_NODES_WITH_LEAVES | 'INVALID XPATH'       || CpsPathException
459     }
460
461     @Sql([CLEAR_DATA, SET_DATA])
462     def 'Update existing list with #scenario.'() {
463         given: 'a parent having a list of data nodes containing: #originalKeys (ech list element has a child too)'
464             def parentXpath = '/parent-3'
465             if (originalKeys.size() > 0) {
466                 def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'original value', originalKeys, true)
467                 objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
468             }
469         and: 'each original list element has one child'
470             def originalParentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
471             originalParentFragment.childFragments.each {assert it.childFragments.size() == 1 }
472         when: 'it is updated with #scenario'
473             def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new value', replacementKeys, false)
474             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
475         then: 'the result list ONLY contains the expected replacement elements'
476             def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
477             def allChildXpaths = parentFragment.childFragments.collect { it.xpath }
478             def expectedListEntriesAfterUpdateAsXpaths = keysToXpaths(parentXpath, replacementKeys)
479             assert allChildXpaths.size() == replacementKeys.size()
480             assert allChildXpaths.containsAll(expectedListEntriesAfterUpdateAsXpaths)
481         and: 'all the list elements have the new values'
482             assert parentFragment.childFragments.stream().allMatch(childFragment -> childFragment.attributes.contains('new value'))
483         and: 'there are no more grandchildren as none of the replacement list entries had a child'
484             parentFragment.childFragments.each {assert it.childFragments.size() == 0 }
485         where: 'the following replacement lists are applied'
486             scenario                                            | originalKeys | replacementKeys
487             'one existing entry only'                           | []           | ['NEW']
488             'multiple new entries'                              | []           | ['NEW1', 'NEW2']
489             'one new entry only (existing entries are deleted)' | ['A', 'B']   | ['NEW1', 'NEW2']
490             'one existing on new entry'                         | ['A', 'B']   | ['A', 'NEW']
491             'one existing entry only'                           | ['A', 'B']   | ['A']
492     }
493
494     @Sql([CLEAR_DATA, SET_DATA])
495     def 'Replacing existing list element with attributes and (grand)child.'() {
496         given: 'a parent with list elements A and B with attribute and grandchild tagged as "org"'
497             def parentXpath = '/parent-3'
498             def originalListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'org', ['A','B'], true)
499             objectUnderTest.addListElements(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, originalListEntriesAsDataNodes)
500         when: 'A is replaced with an entry with attribute and grandchild tagged tagged as "new" (B is not in replacement list)'
501             def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(parentXpath, 'new', ['A'], true)
502             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, parentXpath, replacementListEntriesAsDataNodes)
503         then: 'The updated fragment has a child-list with ONLY element "A"'
504             def parentFragment = fragmentRepository.getById(PARENT_3_FRAGMENT_ID)
505             parentFragment.childFragments.size() == 1
506             def childListElementA = parentFragment.childFragments[0]
507             childListElementA.xpath == "/parent-3/child-list[@key='A']"
508         and: 'element "A" has an attribute with the "new" (tag) value'
509             childListElementA.attributes == '{"attr1": "new"}'
510         and: 'element "A" has a only one (grand)child'
511             childListElementA.childFragments.size() == 1
512         and: 'the grandchild is the new grandchild (tag)'
513             def grandChild = childListElementA.childFragments[0]
514             grandChild.xpath == "/parent-3/child-list[@key='A']/new-grand-child"
515         and: 'the grandchild has an attribute with the "new" (tag) value'
516             grandChild.attributes == '{"attr1": "new"}'
517     }
518
519     @Sql([CLEAR_DATA, SET_DATA])
520     def 'Replace list element for a parent (parent-1) with existing one (non-list) child'() {
521         when: 'a list element is added under the parent'
522             def replacementListEntriesAsDataNodes = createChildListAllHavingAttributeValue(XPATH_DATA_NODE_WITH_DESCENDANTS, 'new', ['A','B'], false)
523             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME1, XPATH_DATA_NODE_WITH_DESCENDANTS, replacementListEntriesAsDataNodes)
524         then: 'the parent will have 3 children after the replacement'
525             def parentFragment = fragmentRepository.getById(ID_DATA_NODE_WITH_DESCENDANTS)
526             parentFragment.childFragments.size() == 3
527             def xpaths = parentFragment.childFragments.collect {it.xpath}
528         and: 'one of the children is the original child fragment'
529             xpaths.contains('/parent-1/child-1')
530         and: 'it has the two new list elements'
531             xpaths.containsAll("/parent-1/child-list[@key='A']", "/parent-1/child-list[@key='B']")
532     }
533
534     @Sql([CLEAR_DATA, SET_DATA])
535     def 'Replace list content using unknown parent'() {
536         given: 'list element as a collection of data nodes'
537             def listElementCollection = toDataNodes(['irrelevant'])
538         when: 'attempt to replace list elements under unknown parent node'
539             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/unknown', listElementCollection)
540         then: 'a datanode not found exception is thrown'
541             thrown(DataNodeNotFoundException)
542     }
543
544     @Sql([CLEAR_DATA, SET_DATA])
545     def 'Replace list content with empty collection is not supported'() {
546         when: 'attempt to replace list elements with empty collection'
547             objectUnderTest.replaceListContent(DATASPACE_NAME, ANCHOR_NAME3, '/parent-203', [])
548         then: 'a CPS admin exception is thrown'
549             def thrown = thrown(CpsAdminException)
550             assert thrown.message == 'Invalid list replacement'
551     }
552
553     @Sql([CLEAR_DATA, SET_DATA])
554     def 'Delete list scenario: #scenario.'() {
555         when: 'deleting list is executed for: #scenario.'
556             objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
557         and: 'remaining children are fetched'
558             def parentFragment = fragmentRepository.getById(parentFragmentId)
559             def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath }
560         then: 'only the expected children remain'
561             assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size()
562             assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths)
563         where: 'following parameters were used'
564             scenario                          | targetXpaths                                                 | parentFragmentId                     || expectedRemainingChildXpaths
565             'list element with key'           | '/parent-203/child-204[@key="A"]'                            | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ["/parent-203/child-203", "/parent-203/child-204[@key='B']"]
566             'list element with combined keys' | '/parent-202/child-205[@key="A" and @key2="B"]'              | LIST_DATA_NODE_PARENT202_FRAGMENT_ID || ["/parent-202/child-206[@key='A']"]
567             'whole list'                      | '/parent-203/child-204'                                      | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ['/parent-203/child-203']
568             'list element under list element' | '/parent-203/child-204[@key="B"]/grand-child-204[@key2="Y"]' | LIST_DATA_NODE_PARENT203_FRAGMENT_ID || ["/parent-203/child-203", "/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
569     }
570
571     @Sql([CLEAR_DATA, SET_DATA])
572     def 'Delete multiple data nodes using scenario: #scenario.'() {
573         when: 'deleting nodes is executed for: #scenario.'
574             objectUnderTest.deleteDataNodes(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
575         and: 'remaining children are fetched'
576             def parentFragment = fragmentRepository.getById(LIST_DATA_NODE_PARENT203_FRAGMENT_ID)
577             def remainingChildXpaths = parentFragment.childFragments.collect { it.xpath }
578         then: 'only the expected children remain'
579             assert remainingChildXpaths.size() == expectedRemainingChildXpaths.size()
580             assert remainingChildXpaths.containsAll(expectedRemainingChildXpaths)
581         where: 'following parameters were used'
582             scenario                          | targetXpaths                                                           || expectedRemainingChildXpaths
583             'delete nothing'                  | []                                                                     || ["/parent-203/child-203", "/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
584             'datanode'                        | ['/parent-203/child-203']                                              || ["/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
585             '1 list element'                  | ['/parent-203/child-204[@key="A"]']                                    || ["/parent-203/child-203", "/parent-203/child-204[@key='B']"]
586             '2 list elements'                 | ['/parent-203/child-204[@key="A"]', '/parent-203/child-204[@key="B"]'] || ["/parent-203/child-203"]
587             'whole list'                      | ['/parent-203/child-204']                                              || ['/parent-203/child-203']
588             'list and element in same list'   | ['/parent-203/child-204', '/parent-203/child-204[@key="A"]']           || ['/parent-203/child-203']
589             'list element under list element' | ['/parent-203/child-204[@key="B"]/grand-child-204[@key2="Y"]']         || ["/parent-203/child-203", "/parent-203/child-204[@key='A']", "/parent-203/child-204[@key='B']"]
590             'valid but non-existing xpath'    | ['/non-existing', '/parent-203/child-204']                             || ['/parent-203/child-203']
591             'invalid xpath'                   | ['INVALID XPATH', '/parent-203/child-204']                             || ['/parent-203/child-203']
592     }
593
594     @Sql([CLEAR_DATA, SET_DATA])
595     def 'Delete data nodes with "/"-token in list key value: #scenario. (CPS-1409)'() {
596         given: 'a data nodes with list-element child with "/" in index value (and grandchild)'
597             def grandChild = new DataNodeBuilder().withXpath(deleteTestGrandChildXPath).build()
598             def child = new DataNodeBuilder().withXpath(deleteTestChildXpath).withChildDataNodes([grandChild]).build()
599             objectUnderTest.addChildDataNode(DATASPACE_NAME, ANCHOR_NAME3, deleteTestParentXPath, child)
600         and: 'number of children before delete is stored'
601             def numberOfChildrenBeforeDelete = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, pathToParentOfDeletedNode, INCLUDE_ALL_DESCENDANTS)[0].childDataNodes.size()
602         when: 'target node is deleted'
603             objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, deleteTarget)
604         then: 'one child has been deleted'
605             def numberOfChildrenAfterDelete = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, pathToParentOfDeletedNode, INCLUDE_ALL_DESCENDANTS)[0].childDataNodes.size()
606             assert numberOfChildrenAfterDelete == numberOfChildrenBeforeDelete - 1
607         where:
608             scenario                | deleteTarget              | pathToParentOfDeletedNode
609             'list element with /'   | deleteTestChildXpath      | deleteTestParentXPath
610             'child of list element' | deleteTestGrandChildXPath | deleteTestChildXpath
611     }
612
613     @Sql([CLEAR_DATA, SET_DATA])
614     def 'Delete list error scenario: #scenario.'() {
615         when: 'attempting to delete scenario: #scenario.'
616             objectUnderTest.deleteListDataNode(DATASPACE_NAME, ANCHOR_NAME3, targetXpaths)
617         then: 'a DataNodeNotFoundException is thrown'
618             thrown(DataNodeNotFoundException)
619         where: 'following parameters were used'
620             scenario                                   | targetXpaths
621             'whole list, parent node does not exist'   | '/unknown/some-child'
622             'list element, parent node does not exist' | '/unknown/child-204[@key="A"]'
623             'whole list does not exist'                | '/parent-200/unknown'
624             'list element, list does not exist'        | '/parent-200/unknown[@key="C"]'
625             'list element, element does not exist'     | '/parent-203/child-204[@key="C"]'
626             'valid datanode but not a list'            | '/parent-200/child-202'
627     }
628
629     @Sql([CLEAR_DATA, SET_DATA])
630     def 'Delete data node by xpath #scenario.'() {
631         given: 'a valid data node'
632             def dataNode
633         and: 'data nodes are deleted'
634             objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion)
635         when: 'verify data nodes are removed'
636             objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, xpathForDeletion, INCLUDE_ALL_DESCENDANTS)
637         then:
638             thrown(DataNodeNotFoundException)
639         and: 'some related object is not deleted'
640             if (xpathSurvivor!=null) {
641                 dataNode = objectUnderTest.getDataNodes(DATASPACE_NAME, ANCHOR_NAME3, xpathSurvivor, INCLUDE_ALL_DESCENDANTS)
642                 assert dataNode[0].xpath == xpathSurvivor
643             }
644         where: 'following parameters were used'
645             scenario                               | xpathForDeletion                                  || xpathSurvivor
646             'child data node, parent still exists' | '/parent-206/child-206'                           || '/parent-206'
647             'list element, sibling still exists'   | '/parent-206/child-206/grand-child-206[@key="A"]' || "/parent-206/child-206/grand-child-206[@key='X']"
648             'container node'                       | '/parent-206'                                     || null
649             'container list node'                  | '/parent-206[@key="A"]'                           || "/parent-206[@key='B']"
650             'root node with xpath /'               | '/'                                               || null
651             'root node with xpath passed as blank' | ''                                                || null
652     }
653
654     @Sql([CLEAR_DATA, SET_DATA])
655     def 'Delete data node error scenario: #scenario.'() {
656         when: 'data node is deleted'
657             objectUnderTest.deleteDataNode(DATASPACE_NAME, ANCHOR_NAME3, datanodeXpath)
658         then: 'a #expectedException is thrown'
659             thrown(expectedException)
660         where: 'the following parameters were used'
661             scenario                                        | datanodeXpath                                    | expectedException
662             'valid data node, non existent child node'      | '/parent-203/child-non-existent'                 | DataNodeNotFoundException
663             'invalid list element'                          | '/parent-206/child-206/grand-child-206@key="A"]' | PathParsingException
664     }
665
666     @Sql([CLEAR_DATA, SET_DATA])
667     def 'Delete data node for an anchor.'() {
668         given: 'a data-node exists for an anchor'
669             assert fragmentsExistInDB(DATASPACE_1001_ID, ANCHOR_3003_ID)
670         when: 'data nodes are deleted '
671             objectUnderTest.deleteDataNodes(DATASPACE_NAME, ANCHOR_NAME3)
672         then: 'all data-nodes are deleted successfully'
673             assert !fragmentsExistInDB(DATASPACE_1001_ID, ANCHOR_3003_ID)
674     }
675
676     def fragmentsExistInDB(dataSpaceId, anchorId) {
677         !fragmentRepository.findRootsByDataspaceAndAnchor(dataSpaceId, anchorId).isEmpty()
678     }
679
680     static Collection<DataNode> toDataNodes(xpaths) {
681         return xpaths.collect { new DataNodeBuilder().withXpath(it).build() }
682     }
683
684
685     static DataNode buildDataNode(xpath, leaves, childDataNodes) {
686         return dataNodeBuilder.withXpath(xpath).withLeaves(leaves).withChildDataNodes(childDataNodes).build()
687     }
688
689     static Map<String, Object> getLeavesMap(FragmentEntity fragmentEntity) {
690         return jsonObjectMapper.convertJsonString(fragmentEntity.attributes, Map<String, Object>.class)
691     }
692
693     def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
694         expectedLeavesMap.forEach((key, value) -> {
695             def actualValue = actualLeavesMap[key]
696             if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
697                 assert value.size() == actualValue.size()
698                 assert value.containsAll(actualValue)
699             } else {
700                 assert value == actualValue
701             }
702         })
703         return true
704     }
705
706     def static treeToFlatMapByXpath(Map<String, DataNode> flatMap, DataNode dataNodeTree) {
707         flatMap.put(dataNodeTree.xpath, dataNodeTree)
708         dataNodeTree.childDataNodes
709                 .forEach(childDataNode -> treeToFlatMapByXpath(flatMap, childDataNode))
710         return flatMap
711     }
712
713     def static multipleTreesToFlatMapByXpath(Map<String, DataNode> flatMap, Collection<DataNode> dataNodeTrees) {
714         for (DataNode dataNodeTree: dataNodeTrees){
715             flatMap.put(dataNodeTree.xpath, dataNodeTree)
716             dataNodeTree.childDataNodes
717                 .forEach(childDataNode -> multipleTreesToFlatMapByXpath(flatMap, [childDataNode]))
718         }
719         return flatMap
720     }
721
722     def keysToXpaths(parent, Collection keys) {
723         return keys.collect { "${parent}/child-list[@key='${it}']".toString() }
724     }
725
726     def static createDataNodeTree(String... xpaths) {
727         def dataNodeBuilder = new DataNodeBuilder().withXpath(xpaths[0])
728         if (xpaths.length > 1) {
729             def xPathsDescendant = Arrays.copyOfRange(xpaths, 1, xpaths.length)
730             def childDataNode = createDataNodeTree(xPathsDescendant)
731             dataNodeBuilder.withChildDataNodes(ImmutableSet.of(childDataNode))
732         }
733         dataNodeBuilder.build()
734     }
735
736     def getFragmentByXpath(dataspaceName, anchorName, xpath) {
737         def dataspace = dataspaceRepository.getByName(dataspaceName)
738         def anchor = anchorRepository.getByDataspaceAndName(dataspace, anchorName)
739         return fragmentRepository.findByDataspaceAndAnchorAndXpath(dataspace, anchor, xpath).orElseThrow()
740     }
741
742
743     def createChildListAllHavingAttributeValue(parentXpath, tag, Collection keys, boolean addGrandChild) {
744         def listElementAsDataNodes = keysToXpaths(parentXpath, keys).collect {
745                 new DataNodeBuilder()
746                     .withXpath(it)
747                     .withLeaves([attr1: tag])
748                     .build()
749         }
750         if (addGrandChild) {
751             listElementAsDataNodes.each {it.childDataNodes = [createGrandChild(it.xpath, tag)]}
752         }
753         return listElementAsDataNodes
754     }
755
756     def createGrandChild(parentXPath, tag) {
757         new DataNodeBuilder()
758             .withXpath("${parentXPath}/${tag}-grand-child")
759             .withLeaves([attr1: tag])
760             .build()
761     }
762
763 }