2 * ============LICENSE_START=======================================================
3 * Copyright (c) 2021 Bell Canada.
4 * Modifications Copyright (C) 2021-2023 Nordix Foundation
5 * Modifications Copyright (C) 2022 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.FragmentEntity
28 import org.onap.cps.spi.exceptions.ConcurrencyException
29 import org.onap.cps.spi.exceptions.DataValidationException
30 import org.onap.cps.spi.model.DataNode
31 import org.onap.cps.spi.model.DataNodeBuilder
32 import org.onap.cps.spi.repository.AnchorRepository
33 import org.onap.cps.spi.repository.DataspaceRepository
34 import org.onap.cps.spi.repository.FragmentRepository
35 import org.onap.cps.spi.utils.SessionManager
36 import org.onap.cps.utils.JsonObjectMapper
37 import org.springframework.dao.DataIntegrityViolationException
38 import spock.lang.Specification
40 class CpsDataPersistenceServiceSpec extends Specification {
42 def mockDataspaceRepository = Mock(DataspaceRepository)
43 def mockAnchorRepository = Mock(AnchorRepository)
44 def mockFragmentRepository = Mock(FragmentRepository)
45 def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
46 def mockSessionManager = Mock(SessionManager)
48 def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
49 mockFragmentRepository, jsonObjectMapper, mockSessionManager))
51 def 'Storing data nodes individually when batch operation fails'(){
52 given: 'two data nodes and supporting repository mock behavior'
53 def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
54 def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
55 and: 'the batch store operation will fail'
56 mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
57 when: 'trying to store data nodes'
58 objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
59 then: 'the two data nodes are saved individually'
60 2 * mockFragmentRepository.save(_);
63 def 'Store single data node.'() {
65 def dataNode = new DataNode()
66 when: 'storing a single data node'
67 objectUnderTest.storeDataNode('dataspace1', 'anchor1', dataNode)
68 then: 'the call is redirected to storing a collection of data nodes with just the given data node'
69 1 * objectUnderTest.storeDataNodes('dataspace1', 'anchor1', [dataNode])
72 def 'Handling of StaleStateException (caused by concurrent updates) during update data node and descendants.'() {
73 given: 'the fragment repository returns a fragment entity'
74 mockFragmentRepository.getByDataspaceAndAnchorAndXpath(*_) >> {
75 def fragmentEntity = new FragmentEntity()
76 fragmentEntity.setChildFragments([new FragmentEntity()] as Set<FragmentEntity>)
79 and: 'a data node is concurrently updated by another transaction'
80 mockFragmentRepository.save(_) >> { throw new StaleStateException("concurrent updates") }
81 when: 'attempt to update data node with submitted data nodes'
82 objectUnderTest.updateDataNodeAndDescendants('some-dataspace', 'some-anchor', new DataNodeBuilder().withXpath('/some/xpath').build())
83 then: 'concurrency exception is thrown'
84 def concurrencyException = thrown(ConcurrencyException)
85 assert concurrencyException.getDetails().contains('some-dataspace')
86 assert concurrencyException.getDetails().contains('some-anchor')
87 assert concurrencyException.getDetails().contains('/some/xpath')
90 def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
91 given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
92 def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
94 '/node2': 'EXCEPTION',
95 '/node3': 'EXCEPTION'])
96 and: 'db contains an anchor'
97 mockAnchorRepository.getByDataspaceAndName(*_) >> new AnchorEntity(id:123)
98 and: 'the batch update will therefore also fail'
99 mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
100 when: 'attempt batch update data nodes'
101 objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
102 then: 'concurrency exception is thrown'
103 def thrown = thrown(ConcurrencyException)
104 assert thrown.message == 'Concurrent Transactions'
105 and: 'it does not contain the successfull datanode'
106 assert !thrown.details.contains('/node1')
107 and: 'it contains the failed datanodes'
108 assert thrown.details.contains('/node2')
109 assert thrown.details.contains('/node3')
112 def 'Retrieving a data node with a property JSON value of #scenario'() {
113 given: 'the db has a fragment with an attribute property JSON value of #scenario'
114 mockFragmentWithJson("{\"some attribute\": ${dataString}}")
115 when: 'getting the data node represented by this fragment'
116 def dataNode = objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
117 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
118 then: 'the leaf is of the correct value and data type'
119 def attributeValue = dataNode[0].leaves.get('some attribute')
120 assert attributeValue == expectedValue
121 assert attributeValue.class == expectedDataClass
122 where: 'the following Data Type is passed'
123 scenario | dataString || expectedValue | expectedDataClass
124 'just numbers' | '15174' || 15174 | Integer
125 'number with dot' | '15174.32' || 15174.32 | Double
126 'number with 0 value after dot' | '15174.0' || 15174.0 | Double
127 'number with 0 value before dot' | '0.32' || 0.32 | Double
128 'number higher than max int' | '2147483648' || 2147483648 | Long
129 'just text' | '"Test"' || 'Test' | String
130 'number with exponent' | '1.2345e5' || 1.2345e5 | Double
131 'number higher than max int with dot' | '123456789101112.0' || 123456789101112.0 | Double
132 'text and numbers' | '"String = \'1234\'"' || "String = '1234'" | String
133 'number as String' | '"12345"' || '12345' | String
136 def 'Retrieving a data node with invalid JSON'() {
137 given: 'a fragment with invalid JSON'
138 mockFragmentWithJson('{invalid json')
139 when: 'getting the data node represented by this fragment'
140 objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
141 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
142 then: 'a data validation exception is thrown'
143 thrown(DataValidationException)
146 def 'Retrieving multiple data nodes.'() {
147 given: 'db contains an anchor'
148 def anchorEntity = new AnchorEntity(id:123)
149 mockAnchorRepository.getByDataspaceAndName(*_) >> anchorEntity
150 and: 'fragment repository returns a collection of fragments'
151 def fragmentEntity1 = new FragmentEntity(xpath: '/xpath1', childFragments: [])
152 def fragmentEntity2 = new FragmentEntity(xpath: '/xpath2', childFragments: [])
153 mockFragmentRepository.findByAnchorAndMultipleCpsPaths(123, ['/xpath1', '/xpath2'] as Set<String>) >> [fragmentEntity1, fragmentEntity2]
154 when: 'getting data nodes for 2 xpaths'
155 def result = objectUnderTest.getDataNodesForMultipleXpaths('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
156 then: '2 data nodes are returned'
157 assert result.size() == 2
160 def 'start session'() {
161 when: 'start session'
162 objectUnderTest.startSession()
163 then: 'the session manager method to start session is invoked'
164 1 * mockSessionManager.startSession()
167 def 'close session'() {
169 def someSessionId = 'someSessionId'
170 when: 'close session method is called with session ID as parameter'
171 objectUnderTest.closeSession(someSessionId)
172 then: 'the session manager method to close session is invoked with parameter'
173 1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
176 def 'Lock anchor.'(){
177 when: 'lock anchor method is called with anchor entity details'
178 objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
179 then: 'the session manager method to lock anchor is invoked with same parameters'
180 1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
183 def 'update data node leaves: #scenario'(){
184 given: 'A node exists for the given xpath'
185 mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, '/some/xpath') >> new FragmentEntity(xpath: '/some/xpath', attributes: existingAttributes)
186 when: 'the node leaves are updated'
187 objectUnderTest.updateDataLeaves('some-dataspace', 'some-anchor', '/some/xpath', newAttributes as Map<String, Serializable>)
188 then: 'the fragment entity saved has the original and new attributes'
189 1 * mockFragmentRepository.save({fragmentEntity -> {
190 assert fragmentEntity.getXpath() == '/some/xpath'
191 assert fragmentEntity.getAttributes() == mergedAttributes
193 where: 'the following attributes combinations are used'
194 scenario | existingAttributes | newAttributes | mergedAttributes
195 'add new leaf' | '{"existing":"value"}' | ["new":"value"] | '{"existing":"value","new":"value"}'
196 'update existing leaf' | '{"existing":"value"}' | ["existing":"value2"] | '{"existing":"value2"}'
197 'update nothing with nothing' | '' | [] | ''
198 'update with nothing' | '{"existing":"value"}' | [] | '{"existing":"value"}'
199 'update with same value' | '{"existing":"value"}' | ["existing":"value"] | '{"existing":"value"}'
202 def 'update data node and descendants: #scenario'(){
203 given: 'mocked responses'
204 mockAnchorRepository.getByDataspaceAndName(_, _) >> new AnchorEntity(id:123)
205 mockFragmentRepository.findByAnchorAndMultipleCpsPaths(_, [] as Set) >> []
206 mockFragmentRepository.findByAnchorAndMultipleCpsPaths(_, ['/test/xpath'] as Set) >> [new FragmentEntity(xpath: '/test/xpath', childFragments: [])]
207 when: 'replace data node tree'
208 objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
209 then: 'call fragment repository save all method'
210 1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
211 where: 'the following Data Type is passed'
212 scenario | dataNodes || expectedFragmentEntities
213 'empty data node list' | [] || []
214 'one data node in list' | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'], childDataNodes: [])] || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', childFragments: [])]
217 def 'update data nodes and descendants'() {
218 given: 'the fragment repository returns fragment entities related to the xpath inputs'
219 mockFragmentRepository.findByAnchorAndMultipleCpsPaths(_, ['/test/xpath1', '/test/xpath2'] as Set) >> [
220 new FragmentEntity(xpath: '/test/xpath1', childFragments: []),
221 new FragmentEntity(xpath: '/test/xpath2', childFragments: [])]
222 and: 'db contains an anchor'
223 mockAnchorRepository.getByDataspaceAndName(*_) >> new AnchorEntity(id:123)
224 and: 'some data nodes with descendants'
225 def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
226 def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
227 when: 'the fragment entities are update by the data nodes'
228 objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', [dataNode1, dataNode2])
229 then: 'call fragment repository save all method is called with the updated fragments'
230 1 * mockFragmentRepository.saveAll({fragmentEntities -> {
231 fragmentEntities.containsAll([
232 new FragmentEntity(xpath: '/test/xpath1', attributes: '{"id":"testId1"}', childFragments: [new FragmentEntity(xpath: '/test/xpath1/child', attributes: '{"id":"childTestId1"}', childFragments: [])]),
233 new FragmentEntity(xpath: '/test/xpath2', attributes: '{"id":"testId2"}', childFragments: [new FragmentEntity(xpath: '/test/xpath2/child', attributes: '{"id":"childTestId2"}', childFragments: [])])
235 assert fragmentEntities.size() == 2
239 def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
240 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
241 def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
242 mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, xpath) >> fragmentEntity
243 if ('EXCEPTION' == scenario) {
244 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
249 def createDataNodesAndMockRepositoryMethodSupportingThem(Map<String, String> xpathToScenarioMap) {
251 def fragmentEntities = []
252 xpathToScenarioMap.each {
254 def scenario = it.value
255 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
256 dataNodes.add(dataNode)
257 def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
258 fragmentEntities.add(fragmentEntity)
259 mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, xpath) >> fragmentEntity
260 if ('EXCEPTION' == scenario) {
261 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
264 mockFragmentRepository.findByAnchorAndMultipleCpsPaths(_, xpathToScenarioMap.keySet()) >> fragmentEntities
268 def mockFragmentWithJson(json) {
269 def anchorEntity = new AnchorEntity(id:123)
270 mockAnchorRepository.getByDataspaceAndName(*_) >> anchorEntity
271 def fragmentEntity = new FragmentEntity(xpath: '/parent-01', childFragments: [], attributes: json)
272 mockFragmentRepository.findByAnchorAndMultipleCpsPaths(123, ['/parent-01'] as Set<String>) >> [fragmentEntity]