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
29 import org.onap.cps.spi.entities.FragmentExtract
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
42 class CpsDataPersistenceServiceSpec extends Specification {
44 def mockDataspaceRepository = Mock(DataspaceRepository)
45 def mockAnchorRepository = Mock(AnchorRepository)
46 def mockFragmentRepository = Mock(FragmentRepository)
47 def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
48 def mockSessionManager = Mock(SessionManager)
50 def objectUnderTest = Spy(new CpsDataPersistenceServiceImpl(mockDataspaceRepository, mockAnchorRepository,
51 mockFragmentRepository, jsonObjectMapper, mockSessionManager))
53 def anchorEntity = new AnchorEntity(id: 123, dataspace: new DataspaceEntity(id: 1))
56 mockAnchorRepository.getByDataspaceAndName(_, _) >> anchorEntity
59 def 'Storing data nodes individually when batch operation fails'(){
60 given: 'two data nodes and supporting repository mock behavior'
61 def dataNode1 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath1','OK')
62 def dataNode2 = createDataNodeAndMockRepositoryMethodSupportingIt('xpath2','OK')
63 and: 'the batch store operation will fail'
64 mockFragmentRepository.saveAll(*_) >> { throw new DataIntegrityViolationException("Exception occurred") }
65 when: 'trying to store data nodes'
66 objectUnderTest.storeDataNodes('dataSpaceName', 'anchorName', [dataNode1, dataNode2])
67 then: 'the two data nodes are saved individually'
68 2 * mockFragmentRepository.save(_)
71 def 'Store single data node.'() {
73 def dataNode = new DataNode()
74 when: 'storing a single data node'
75 objectUnderTest.storeDataNode('dataspace1', 'anchor1', dataNode)
76 then: 'the call is redirected to storing a collection of data nodes with just the given data node'
77 1 * objectUnderTest.storeDataNodes('dataspace1', 'anchor1', [dataNode])
80 def 'Handling of StaleStateException (caused by concurrent updates) during update data nodes and descendants.'() {
81 given: 'the system can update one datanode and has two more datanodes that throw an exception while updating'
82 def dataNodes = createDataNodesAndMockRepositoryMethodSupportingThem([
84 '/node2': 'EXCEPTION',
85 '/node3': 'EXCEPTION'])
86 and: 'the batch update will therefore also fail'
87 mockFragmentRepository.saveAll(*_) >> { throw new StaleStateException("concurrent updates") }
88 when: 'attempt batch update data nodes'
89 objectUnderTest.updateDataNodesAndDescendants('some-dataspace', 'some-anchor', dataNodes)
90 then: 'concurrency exception is thrown'
91 def thrown = thrown(ConcurrencyException)
92 assert thrown.message == 'Concurrent Transactions'
93 and: 'it does not contain the successfull datanode'
94 assert !thrown.details.contains('/node1')
95 and: 'it contains the failed datanodes'
96 assert thrown.details.contains('/node2')
97 assert thrown.details.contains('/node3')
100 def 'Retrieving a data node with a property JSON value of #scenario'() {
101 given: 'the db has a fragment with an attribute property JSON value of #scenario'
102 mockFragmentWithJson("{\"some attribute\": ${dataString}}")
103 when: 'getting the data node represented by this fragment'
104 def dataNode = objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
105 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
106 then: 'the leaf is of the correct value and data type'
107 def attributeValue = dataNode[0].leaves.get('some attribute')
108 assert attributeValue == expectedValue
109 assert attributeValue.class == expectedDataClass
110 where: 'the following Data Type is passed'
111 scenario | dataString || expectedValue | expectedDataClass
112 'just numbers' | '15174' || 15174 | Integer
113 'number with dot' | '15174.32' || 15174.32 | Double
114 'number with 0 value after dot' | '15174.0' || 15174.0 | Double
115 'number with 0 value before dot' | '0.32' || 0.32 | Double
116 'number higher than max int' | '2147483648' || 2147483648 | Long
117 'just text' | '"Test"' || 'Test' | String
118 'number with exponent' | '1.2345e5' || 1.2345e5 | Double
119 'number higher than max int with dot' | '123456789101112.0' || 123456789101112.0 | Double
120 'text and numbers' | '"String = \'1234\'"' || "String = '1234'" | String
121 'number as String' | '"12345"' || '12345' | String
124 def 'Retrieving a data node with invalid JSON'() {
125 given: 'a fragment with invalid JSON'
126 mockFragmentWithJson('{invalid json')
127 when: 'getting the data node represented by this fragment'
128 objectUnderTest.getDataNodes('my-dataspace', 'my-anchor',
129 '/parent-01', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
130 then: 'a data validation exception is thrown'
131 thrown(DataValidationException)
134 def 'Retrieving multiple data nodes.'() {
135 given: 'fragment repository returns a collection of fragments'
136 mockFragmentRepository.findExtractsWithDescendants(123, ['/xpath1', '/xpath2'] as Set, _) >> [
137 mockFragmentExtract(1, null, 123, '/xpath1', null),
138 mockFragmentExtract(2, null, 123, '/xpath2', null)
140 when: 'getting data nodes for 2 xpaths'
141 def result = objectUnderTest.getDataNodesForMultipleXpaths('some-dataspace', 'some-anchor', ['/xpath1', '/xpath2'], FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS)
142 then: '2 data nodes are returned'
143 assert result.size() == 2
146 def 'start session'() {
147 when: 'start session'
148 objectUnderTest.startSession()
149 then: 'the session manager method to start session is invoked'
150 1 * mockSessionManager.startSession()
153 def 'close session'() {
155 def someSessionId = 'someSessionId'
156 when: 'close session method is called with session ID as parameter'
157 objectUnderTest.closeSession(someSessionId)
158 then: 'the session manager method to close session is invoked with parameter'
159 1 * mockSessionManager.closeSession(someSessionId, mockSessionManager.WITH_COMMIT)
162 def 'Lock anchor.'(){
163 when: 'lock anchor method is called with anchor entity details'
164 objectUnderTest.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
165 then: 'the session manager method to lock anchor is invoked with same parameters'
166 1 * mockSessionManager.lockAnchor('mySessionId', 'myDataspaceName', 'myAnchorName', 123L)
169 def 'update data node leaves: #scenario'(){
170 given: 'A node exists for the given xpath'
171 mockFragmentRepository.getByAnchorAndXpath(_, '/some/xpath') >> new FragmentEntity(xpath: '/some/xpath', attributes: existingAttributes)
172 when: 'the node leaves are updated'
173 objectUnderTest.updateDataLeaves('some-dataspace', 'some-anchor', '/some/xpath', newAttributes as Map<String, Serializable>)
174 then: 'the fragment entity saved has the original and new attributes'
175 1 * mockFragmentRepository.save({fragmentEntity -> {
176 assert fragmentEntity.getXpath() == '/some/xpath'
177 assert fragmentEntity.getAttributes() == mergedAttributes
179 where: 'the following attributes combinations are used'
180 scenario | existingAttributes | newAttributes | mergedAttributes
181 'add new leaf' | '{"existing":"value"}' | ["new":"value"] | '{"existing":"value","new":"value"}'
182 'update existing leaf' | '{"existing":"value"}' | ["existing":"value2"] | '{"existing":"value2"}'
183 'update nothing with nothing' | '' | [] | ''
184 'update with nothing' | '{"existing":"value"}' | [] | '{"existing":"value"}'
185 'update with same value' | '{"existing":"value"}' | ["existing":"value"] | '{"existing":"value"}'
188 def 'update data node and descendants: #scenario'(){
189 given: 'the fragment repository returns fragment entities related to the xpath inputs'
190 mockFragmentRepository.findExtractsWithDescendants(_, [] as Set, _) >> []
191 mockFragmentRepository.findExtractsWithDescendants(_, ['/test/xpath'] as Set, _) >> [
192 mockFragmentExtract(1, null, 123, '/test/xpath', null)
194 when: 'replace data node tree'
195 objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', dataNodes)
196 then: 'call fragment repository save all method'
197 1 * mockFragmentRepository.saveAll({fragmentEntities -> assert fragmentEntities as List == expectedFragmentEntities})
198 where: 'the following Data Type is passed'
199 scenario | dataNodes || expectedFragmentEntities
200 'empty data node list' | [] || []
201 'one data node in list' | [new DataNode(xpath: '/test/xpath', leaves: ['id': 'testId'], childDataNodes: [])] || [new FragmentEntity(xpath: '/test/xpath', attributes: '{"id":"testId"}', childFragments: [])]
204 def 'update data nodes and descendants'() {
205 given: 'the fragment repository returns fragment entities related to the xpath inputs'
206 mockFragmentRepository.findExtractsWithDescendants(123, ['/test/xpath1', '/test/xpath2'] as Set, _) >> [
207 mockFragmentExtract(1, null, 123, '/test/xpath1', null),
208 mockFragmentExtract(2, null, 123, '/test/xpath2', null)
210 and: 'some data nodes with descendants'
211 def dataNode1 = new DataNode(xpath: '/test/xpath1', leaves: ['id': 'testId1'], childDataNodes: [new DataNode(xpath: '/test/xpath1/child', leaves: ['id': 'childTestId1'])])
212 def dataNode2 = new DataNode(xpath: '/test/xpath2', leaves: ['id': 'testId2'], childDataNodes: [new DataNode(xpath: '/test/xpath2/child', leaves: ['id': 'childTestId2'])])
213 when: 'the fragment entities are update by the data nodes'
214 objectUnderTest.updateDataNodesAndDescendants('dataspaceName', 'anchorName', [dataNode1, dataNode2])
215 then: 'call fragment repository save all method is called with the updated fragments'
216 1 * mockFragmentRepository.saveAll({fragmentEntities -> {
217 fragmentEntities.containsAll([
218 new FragmentEntity(xpath: '/test/xpath1', attributes: '{"id":"testId1"}', childFragments: [new FragmentEntity(xpath: '/test/xpath1/child', attributes: '{"id":"childTestId1"}', childFragments: [])]),
219 new FragmentEntity(xpath: '/test/xpath2', attributes: '{"id":"testId2"}', childFragments: [new FragmentEntity(xpath: '/test/xpath2/child', attributes: '{"id":"childTestId2"}', childFragments: [])])
221 assert fragmentEntities.size() == 2
225 def createDataNodeAndMockRepositoryMethodSupportingIt(xpath, scenario) {
226 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
227 def fragmentEntity = new FragmentEntity(xpath: xpath, childFragments: [])
228 mockFragmentRepository.getByAnchorAndXpath(_, xpath) >> fragmentEntity
229 if ('EXCEPTION' == scenario) {
230 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
235 def createDataNodesAndMockRepositoryMethodSupportingThem(Map<String, String> xpathToScenarioMap) {
237 def fragmentExtracts = []
239 xpathToScenarioMap.each {
241 def scenario = it.value
242 def dataNode = new DataNodeBuilder().withXpath(xpath).build()
243 dataNodes.add(dataNode)
244 def fragmentExtract = mockFragmentExtract(fragmentId, null, null, xpath, null)
245 fragmentExtracts.add(fragmentExtract)
246 def fragmentEntity = new FragmentEntity(id: fragmentId, xpath: xpath, childFragments: [])
247 mockFragmentRepository.getByDataspaceAndAnchorAndXpath(_, _, xpath) >> fragmentEntity
248 if ('EXCEPTION' == scenario) {
249 mockFragmentRepository.save(fragmentEntity) >> { throw new StaleStateException("concurrent updates") }
253 mockFragmentRepository.findExtractsWithDescendants(_, xpathToScenarioMap.keySet(), _) >> fragmentExtracts
257 def mockFragmentWithJson(json) {
258 def fragmentExtract = mockFragmentExtract(456, null, 123, '/parent-01', json)
259 mockFragmentRepository.findExtractsWithDescendants(123, ['/parent-01'] as Set, _) >> [fragmentExtract]
262 def mockFragmentExtract(id, parentId, anchorId, xpath, attributes) {
263 def fragmentExtract = Mock(FragmentExtract)
264 fragmentExtract.getId() >> id
265 fragmentExtract.getParentId() >> parentId
266 fragmentExtract.getAnchorId() >> anchorId
267 fragmentExtract.getXpath() >> xpath
268 fragmentExtract.getAttributes() >> attributes
269 return fragmentExtract