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 }
59 mockFragmentRepository.findListByAnchorAndXpath(_, [] as Set) >> []
62 def 'Storing data nodes individually when batch operation fails'(){
63 given: 'two data nodes and supporting repository mock behavior'
64 def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
65 def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
66 and: 'the batch store operation will fail'
67 mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
68 when: 'trying to store data nodes'
69 objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
70 then: 'the two data nodes are saved individually'
71 2 * mockFragmentRepository.save(_)
74 def 'Handling of StaleStateException (caused by concurrent updates) during patch operation for data nodes.'() {
75 given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
76 def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
78 '/node2': 'EXCEPTION',
79 '/node3': 'EXCEPTION'])
80 def updatedLeavesPerXPath = dataNodes.stream()
81 .collect(Collectors.toMap(DataNode::getXpath, DataNode::getLeaves))
82 and: 'the batch update will therefore also fail'
83 mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
84 when: 'attempt batch update data nodes'
85 objectUnderTest.batchUpdateDataLeaves('some-dataspace', 'some-anchor', updatedLeavesPerXPath)
86 then: 'concurrency exception is thrown'
87 def thrown = thrown(ConcurrencyException)
88 assert thrown.message == 'Concurrent Transactions'
89 and: 'it does not contain the successful datanode'
90 assert !thrown.details.contains('/node1')
91 and: 'it contains the failed datanodes'
92 assert thrown.details.contains('/node2')
93 assert thrown.details.contains('/node3')
96 def 'Batch update data node leaves and descendants: #scenario'(){
97 given: 'the fragment repository returns fragment entities related to the xpath inputs'
98 mockFragmentRepository.findByAnchorAndXpathIn(_, [] as Set) >> []
99 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath'] as Set) >> [
100 new FragmentEntity(1, '/test/xpath', null, "{\"id\":\"testId\"}", anchorEntity, [] as Set)
102 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
103 new FragmentEntity(1, '/test/xpath1', null, "{\"id\":\"testId1\"}", anchorEntity, [] as Set),
104 new FragmentEntity(2, '/test/xpath2', null, "{\"id\":\"testId2\"}", anchorEntity, [] as Set)
106 when: 'replace data node tree'
107 objectUnderTest.batchUpdateDataLeaves('dataspaceName', 'anchorName',
108 dataNodes.stream().collect(Collectors.toMap(DataNode::getXpath, DataNode::getLeaves)))
109 then: 'call fragment repository save all method'
110 1 * mockFragmentRepository.saveAll({fragmentEntities ->
111 assert fragmentEntities.sort() == expectedFragmentEntities.sort()
112 assert fragmentEntities.size() == expectedSize
114 where: 'the following Data Type is passed'
115 scenario | dataNodes | expectedSize || expectedFragmentEntities
116 'empty data node list' | [] | 0 || []
117 'one data node in list' | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'])] | 1 || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', anchor: anchorEntity)]
118 '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)]
121 def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
122 given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
123 def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
125 '/node2': 'EXCEPTION',
126 '/node3': 'EXCEPTION'])
127 and: 'the batch update will therefore also fail'
128 mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
129 when: 'attempt batch update data nodes'
130 objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
131 then: 'concurrency exception is thrown'
132 def thrown = thrown(ConcurrencyException)
133 assert thrown.message == 'Concurrent Transactions'
134 and: 'it does not contain the successful datanode'
135 assert !thrown.details.contains('/node1')
136 and: 'it contains the failed datanodes'
137 assert thrown.details.contains('/node2')
138 assert thrown.details.contains('/node3')
141 def 'Retrieving a data node with a property JSON value of #scenario'() {
142 given: 'the db has a fragment with an attribute property JSON value of #scenario'
143 mockFragmentWithJson("{\"some attribute\": ${dataString}}")
144 when: 'getting the data node represented by this fragment'
145 def dataNode = objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
146 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
147 then: 'the leaf is of the correct value and data type'
148 def attributeValue = dataNode[0].leaves.get('some attribute')
149 assert attributeValue == expectedValue
150 assert attributeValue.class == expectedDataClass
151 where: 'the following Data Type is passed'
152 scenario | dataString || expectedValue | expectedDataClass
153 'just numbers' | '15174' || 15174 | Integer
154 'number with dot' | '15174.32' || 15174.32 | Double
155 'number with 0 value after dot' | '15174.0' || 15174.0 | Double
156 'number with 0 value before dot' | '0.32' || 0.32 | Double
157 'number higher than max int' | '2147483648' || 2147483648 | Long
158 'just text' | '"Test"' || 'Test' | String
159 'number with exponent' | '1.2345e5' || 1.2345e5 | Double
160 'number higher than max int with dot' | '123456789101112.0' || 123456789101112.0 | Double
161 'text and numbers' | '"String = \'1234\'"' || "String = '1234'" | String
162 'number as String' | '"12345"' || '12345' | String
165 def 'Retrieving a data node with invalid JSON'() {
166 given: 'a fragment with invalid JSON'
167 mockFragmentWithJson('{invalid json')
168 when: 'getting the data node represented by this fragment'
169 objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
170 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
171 then: 'a data validation exception is thrown'
172 thrown(DataValidationException)
175 def 'Retrieving multiple data nodes.'() {
176 given: 'fragment repository returns a collection of fragments'
177 mockFragmentRepository.findByAnchorAndXpathIn(anchorEntity, ['/xpath1', '/xpath2'] as Set) >> [
178 new FragmentEntity(1, '/xpath1', null, null, anchorEntity, [] as Set),
179 new FragmentEntity(2, '/xpath2', null, null, anchorEntity, [] as Set)
181 when: 'getting data nodes for 2 xpaths'
182 def result = objectUnderTest.getDataNodesForMultipleXpaths('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
183 then: '2 data nodes are returned'
184 assert result.size() == 2
187 def 'start session'() {
188 when: 'start session'
189 objectUnderTest.startSession()
190 then: 'the session manager method to start session is invoked'
191 1 * mockSessionManager.startSession()
194 def 'close session'() {
196 def someSessionId = 'someSessionId'
197 when: 'close session method is called with session ID as parameter'
198 objectUnderTest.closeSession(someSessionId)
199 then: 'the session manager method to close session is invoked with parameter'
200 1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
203 def 'Lock anchor.'(){
204 when: 'lock anchor method is called with anchor entity details'
205 objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
206 then: 'the session manager method to lock anchor is invoked with same parameters'
207 1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
210 def 'Replace data node and descendants: #scenario'(){
211 given: 'the fragment repository returns fragment entities related to the xpath inputs'
212 mockFragmentRepository.findByAnchorAndXpathIn(_, [] as Set) >> []
213 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath'] as Set) >> [
214 new FragmentEntity(1, '/test/xpath', null, '{"id":"testId"}', anchorEntity, [] as Set)
216 when: 'replace data node tree'
217 objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
218 then: 'call fragment repository save all method'
219 1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
220 where: 'the following Data Type is passed'
221 scenario | dataNodes || expectedFragmentEntities
222 'empty data node list' | [] || []
223 '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: [])]
226 def 'Replace data nodes and descendants'() {
227 given: 'the fragment repository returns fragment entities related to the xpath inputs'
228 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
229 new FragmentEntity(1, '/test/xpath1', null, null, anchorEntity, [] as Set),
230 new FragmentEntity(2, '/test/xpath2', null, null, anchorEntity, [] as Set)
232 and: 'some data nodes with descendants'
233 def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
234 def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
235 when: 'the fragment entities are update by the data nodes'
236 objectUnderTest.updateDataNodesAndDescendants('dataspace', 'anchor', [dataNode1, dataNode2])
237 then: 'call fragment repository save all method is called with the updated fragments'
238 1 * mockFragmentRepository.saveAll({fragmentEntities -> {
239 assert fragmentEntities.size() == 2
240 def fragmentEntityPerXpath = fragmentEntities.collectEntries { [it.xpath, it] }
241 assert fragmentEntityPerXpath.get('/test/xpath1').childFragments.first().attributes == '{"id":"childTestId1"}'
242 assert fragmentEntityPerXpath.get('/test/xpath2').childFragments.first().attributes == '{"id":"childTestId2"}'
246 def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
247 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
248 def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
249 mockFragmentRepository.getByAnchorAndXpath(_, xpath) >> fragmentEntity
250 if ('EXCEPTION' == scenario) {
251 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
256 def createDataNodesAndMockRepositoryMethodSupportingThem(Map<String, String> xpathToScenarioMap) {
258 def fragmentEntities = []
260 xpathToScenarioMap.each {
262 def scenario = it.value
263 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
264 dataNodes.add(dataNode)
265 def fragmentEntity = new FragmentEntity(id: fragmentId, anchor: anchorEntity, xpath: xpath, childFragments: [])
266 fragmentEntities.add(fragmentEntity)
267 if ('EXCEPTION' == scenario) {
268 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
272 mockFragmentRepository.findByAnchorAndXpathIn(_, xpathToScenarioMap.keySet()) >> fragmentEntities
276 def mockFragmentWithJson(json) {
277 def fragmentEntity = new FragmentEntity(456, '/parent-01', null, json, anchorEntity, [] as Set)
278 mockFragmentRepository.findByAnchorAndXpathIn(_, ['/parent-01'] as Set) >> [fragmentEntity]