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