2 * ============LICENSE_START=======================================================
3 * Copyright (c) 2021 Bell Canada.
4 * Modifications Copyright (C) 2021-2023 Nordix Foundation
5 * Modifications Copyright (C) 2022-2023 TechMahindra Ltd.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.spi.impl
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import org.hibernate.StaleStateException
25 import org.onap.cps.spi.FetchDescendantsOption
26 import org.onap.cps.spi.entities.AnchorEntity
27 import org.onap.cps.spi.entities.DataspaceEntity
28 import org.onap.cps.spi.entities.FragmentEntity
30 import org.onap.cps.spi.exceptions.ConcurrencyException
31 import org.onap.cps.spi.exceptions.DataValidationException
32 import org.onap.cps.spi.model.DataNode
33 import org.onap.cps.spi.model.DataNodeBuilder
34 import org.onap.cps.spi.repository.AnchorRepository
35 import org.onap.cps.spi.repository.DataspaceRepository
36 import org.onap.cps.spi.repository.FragmentRepository
37 import org.onap.cps.spi.utils.SessionManager
38 import org.onap.cps.utils.JsonObjectMapper
39 import org.springframework.dao.DataIntegrityViolationException
40 import spock.lang.Specification
41 import java.util.stream.Collectors
43 class CpsDataPersistenceServiceSpec extends Specification {
45 def mockDataspaceRepository = Mock(DataspaceRepository)
46 def mockAnchorRepository = Mock(AnchorRepository)
47 def mockFragmentRepository = Mock(FragmentRepository)
48 def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
49 def mockSessionManager = Mock(SessionManager)
51 def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
52 mockFragmentRepository, jsonObjectMapper, mockSessionManager))
54 static def anchorEntity = new AnchorEntity(id: 123, dataspace: new DataspaceEntity(id: 1))
57 mockAnchorRepository.getByDataspaceAndName(_, _) >> anchorEntity
58 mockFragmentRepository.prefetchDescendantsOfFragmentEntities(_, _) >> { fetchDescendantsOption, fragmentEntities -> fragmentEntities }
61 def 'Storing data nodes individually when batch operation fails'(){
62 given: 'two data nodes and supporting repository mock behavior'
63 def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
64 def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
65 and: 'the batch store operation will fail'
66 mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
67 when: 'trying to store data nodes'
68 objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
69 then: 'the two data nodes are saved individually'
70 2 * mockFragmentRepository.save(_)
73 def 'Handling of StaleStateException (caused by concurrent updates) during patch operation for data nodes.'() {
74 given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
75 def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
77 '/node2': 'EXCEPTION',
78 '/node3': 'EXCEPTION'])
79 def updatedLeavesPerXPath = dataNodes.stream()
80 .collect(Collectors.toMap(DataNode::getXpath, DataNode::getLeaves))
81 and: 'the batch update will therefore also fail'
82 mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
83 when: 'attempt batch update data nodes'
84 objectUnderTest.batchUpdateDataLeaves('some-dataspace', 'some-anchor', updatedLeavesPerXPath)
85 then: 'concurrency exception is thrown'
86 def thrown = thrown(ConcurrencyException)
87 assert thrown.message == 'Concurrent Transactions'
88 and: 'it does not contain the successful datanode'
89 assert !thrown.details.contains('/node1')
90 and: 'it contains the failed datanodes'
91 assert thrown.details.contains('/node2')
92 assert thrown.details.contains('/node3')
95 def 'Batch update data node leaves and descendants: #scenario'(){
96 given: 'the fragment repository returns fragment entities related to the xpath inputs'
97 mockFragmentRepository.findByAnchorAndXpathIn(_, [] as Set) >> []
98 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath'] as Set) >> [
99 new FragmentEntity(1, '/test/xpath', null, "{\"id\":\"testId\"}", anchorEntity, [] as Set)
101 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
102 new FragmentEntity(1, '/test/xpath1', null, "{\"id\":\"testId1\"}", anchorEntity, [] as Set),
103 new FragmentEntity(2, '/test/xpath2', null, "{\"id\":\"testId2\"}", anchorEntity, [] as Set)
105 when: 'replace data node tree'
106 objectUnderTest.batchUpdateDataLeaves('dataspaceName', 'anchorName',
107 dataNodes.stream().collect(Collectors.toMap(DataNode::getXpath, DataNode::getLeaves)))
108 then: 'call fragment repository save all method'
109 1 * mockFragmentRepository.saveAll({fragmentEntities ->
110 assert fragmentEntities.sort() == expectedFragmentEntities.sort()
111 assert fragmentEntities.size() == expectedSize
113 where: 'the following Data Type is passed'
114 scenario | dataNodes | expectedSize || expectedFragmentEntities
115 'empty data node list' | [] | 0 || []
116 'one data node in list' | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'])] | 1 || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', anchor: anchorEntity)]
117 'multiple data nodes' | [new DataNode(xpath: '/test/xpath1', leaves: ['id': 'newTestId1']), new DataNode(xpath: '/test/xpath2', leaves: ['id': 'newTestId2'])] | 2 || [new FragmentEntity(xpath: '/test/xpath2', attributes: '{"id":"newTestId2"}', anchor: anchorEntity), new FragmentEntity(xpath: '/test/xpath1', attributes: '{"id":"newTestId1"}', anchor: anchorEntity)]
120 def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
121 given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
122 def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
124 '/node2': 'EXCEPTION',
125 '/node3': 'EXCEPTION'])
126 and: 'the batch update will therefore also fail'
127 mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
128 when: 'attempt batch update data nodes'
129 objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
130 then: 'concurrency exception is thrown'
131 def thrown = thrown(ConcurrencyException)
132 assert thrown.message == 'Concurrent Transactions'
133 and: 'it does not contain the successful datanode'
134 assert !thrown.details.contains('/node1')
135 and: 'it contains the failed datanodes'
136 assert thrown.details.contains('/node2')
137 assert thrown.details.contains('/node3')
140 def 'Retrieving a data node with a property JSON value of #scenario'() {
141 given: 'the db has a fragment with an attribute property JSON value of #scenario'
142 mockFragmentWithJson("{\"some attribute\": ${dataString}}")
143 when: 'getting the data node represented by this fragment'
144 def dataNode = objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
145 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
146 then: 'the leaf is of the correct value and data type'
147 def attributeValue = dataNode[0].leaves.get('some attribute')
148 assert attributeValue == expectedValue
149 assert attributeValue.class == expectedDataClass
150 where: 'the following Data Type is passed'
151 scenario | dataString || expectedValue | expectedDataClass
152 'just numbers' | '15174' || 15174 | Integer
153 'number with dot' | '15174.32' || 15174.32 | Double
154 'number with 0 value after dot' | '15174.0' || 15174.0 | Double
155 'number with 0 value before dot' | '0.32' || 0.32 | Double
156 'number higher than max int' | '2147483648' || 2147483648 | Long
157 'just text' | '"Test"' || 'Test' | String
158 'number with exponent' | '1.2345e5' || 1.2345e5 | Double
159 'number higher than max int with dot' | '123456789101112.0' || 123456789101112.0 | Double
160 'text and numbers' | '"String = \'1234\'"' || "String = '1234'" | String
161 'number as String' | '"12345"' || '12345' | String
164 def 'Retrieving a data node with invalid JSON'() {
165 given: 'a fragment with invalid JSON'
166 mockFragmentWithJson('{invalid json')
167 when: 'getting the data node represented by this fragment'
168 objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
169 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
170 then: 'a data validation exception is thrown'
171 thrown(DataValidationException)
174 def 'Retrieving multiple data nodes.'() {
175 given: 'fragment repository returns a collection of fragments'
176 mockFragmentRepository.findByAnchorAndXpathIn(anchorEntity, ['/xpath1', '/xpath2'] as Set) >> [
177 new FragmentEntity(1, '/xpath1', null, null, anchorEntity, [] as Set),
178 new FragmentEntity(2, '/xpath2', null, null, anchorEntity, [] as Set)
180 when: 'getting data nodes for 2 xpaths'
181 def result = objectUnderTest.getDataNodesForMultipleXpaths('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
182 then: '2 data nodes are returned'
183 assert result.size() == 2
186 def 'start session'() {
187 when: 'start session'
188 objectUnderTest.startSession()
189 then: 'the session manager method to start session is invoked'
190 1 * mockSessionManager.startSession()
193 def 'close session'() {
195 def someSessionId = 'someSessionId'
196 when: 'close session method is called with session ID as parameter'
197 objectUnderTest.closeSession(someSessionId)
198 then: 'the session manager method to close session is invoked with parameter'
199 1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
202 def 'Lock anchor.'(){
203 when: 'lock anchor method is called with anchor entity details'
204 objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
205 then: 'the session manager method to lock anchor is invoked with same parameters'
206 1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
209 def 'Replace data node and descendants: #scenario'(){
210 given: 'the fragment repository returns fragment entities related to the xpath inputs'
211 mockFragmentRepository.findByAnchorAndXpathIn(_, [] as Set) >> []
212 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath'] as Set) >> [
213 new FragmentEntity(1, '/test/xpath', null, '{"id":"testId"}', anchorEntity, [] as Set)
215 when: 'replace data node tree'
216 objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
217 then: 'call fragment repository save all method'
218 1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
219 where: 'the following Data Type is passed'
220 scenario | dataNodes || expectedFragmentEntities
221 'empty data node list' | [] || []
222 'one data node in list' | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'], childDataNodes: [])] || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', anchor: anchorEntity, childFragments: [])]
225 def 'Replace data nodes and descendants'() {
226 given: 'the fragment repository returns fragment entities related to the xpath inputs'
227 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
228 new FragmentEntity(1, '/test/xpath1', null, null, anchorEntity, [] as Set),
229 new FragmentEntity(2, '/test/xpath2', null, null, anchorEntity, [] as Set)
231 and: 'some data nodes with descendants'
232 def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
233 def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
234 when: 'the fragment entities are update by the data nodes'
235 objectUnderTest.updateDataNodesAndDescendants('dataspace', 'anchor', [dataNode1, dataNode2])
236 then: 'call fragment repository save all method is called with the updated fragments'
237 1 * mockFragmentRepository.saveAll({fragmentEntities -> {
238 assert fragmentEntities.size() == 2
239 def fragmentEntityPerXpath = fragmentEntities.collectEntries { [it.xpath, it] }
240 assert fragmentEntityPerXpath.get('/test/xpath1').childFragments.first().attributes == '{"id":"childTestId1"}'
241 assert fragmentEntityPerXpath.get('/test/xpath2').childFragments.first().attributes == '{"id":"childTestId2"}'
245 def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
246 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
247 def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
248 mockFragmentRepository.getByAnchorAndXpath(_, xpath) >> fragmentEntity
249 if ('EXCEPTION' == scenario) {
250 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
255 def createDataNodesAndMockRepositoryMethodSupportingThem(Map<String, String> xpathToScenarioMap) {
257 def fragmentEntities = []
259 xpathToScenarioMap.each {
261 def scenario = it.value
262 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
263 dataNodes.add(dataNode)
264 def fragmentEntity = new FragmentEntity(id: fragmentId, anchor: anchorEntity, xpath: xpath, childFragments: [])
265 fragmentEntities.add(fragmentEntity)
266 if ('EXCEPTION' == scenario) {
267 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
271 mockFragmentRepository.findByAnchorAndXpathIn(_, xpathToScenarioMap.keySet()) >> fragmentEntities
275 def mockFragmentWithJson(json) {
276 def fragmentEntity = new FragmentEntity(456, '/parent-01', null, json, anchorEntity, [] as Set)
277 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/parent-01'] as Set) >> [fragmentEntity]