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