2  * ============LICENSE_START=======================================================
 
   3  * Copyright (c) 2023 Nordix Foundation.
 
   4  *  ================================================================================
 
   5  *  Licensed under the Apache License, Version 2.0 (the "License");
 
   6  *  you may not use this file except in compliance with the License.
 
   7  *  You may obtain a copy of the License at
 
   9  *        http://www.apache.org/licenses/LICENSE-2.0
 
  11  *  Unless required by applicable law or agreed to in writing, software
 
  12  *  distributed under the License is distributed on an 'AS IS' BASIS,
 
  13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  14  *  See the License for the specific language governing permissions and
 
  15  *  limitations under the License.
 
  17  *  SPDX-License-Identifier: Apache-2.0
 
  18  *  ============LICENSE_END=========================================================
 
  21 package org.onap.cps.ncmp.api.impl.events.avcsubscription
 
  23 import com.fasterxml.jackson.databind.ObjectMapper
 
  24 import com.hazelcast.map.IMap
 
  25 import io.cloudevents.CloudEvent
 
  26 import io.cloudevents.core.CloudEventUtils
 
  27 import io.cloudevents.core.data.PojoCloudEventData
 
  28 import io.cloudevents.jackson.PojoCloudEventDataMapper
 
  29 import org.mapstruct.factory.Mappers
 
  30 import org.onap.cps.ncmp.api.impl.events.EventsPublisher
 
  31 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionPersistence
 
  32 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionStatus
 
  33 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
 
  34 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelSubscriptionEvent.TargetCmHandle
 
  35 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
 
  36 import org.onap.cps.ncmp.api.kafka.MessagingBaseSpec
 
  37 import org.onap.cps.ncmp.events.avcsubscription1_0_0.client_to_ncmp.SubscriptionEvent
 
  38 import org.onap.cps.ncmp.events.avcsubscription1_0_0.dmi_to_ncmp.Data
 
  39 import org.onap.cps.ncmp.events.avcsubscription1_0_0.dmi_to_ncmp.SubscriptionEventResponse
 
  40 import org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.CmHandle;
 
  41 import org.onap.cps.ncmp.utils.TestUtils
 
  42 import org.onap.cps.spi.exceptions.OperationNotYetSupportedException
 
  43 import org.onap.cps.utils.JsonObjectMapper
 
  44 import org.spockframework.spring.SpringBean
 
  45 import org.springframework.beans.factory.annotation.Autowired
 
  46 import org.springframework.boot.test.context.SpringBootTest
 
  47 import spock.util.concurrent.BlockingVariable
 
  49 import java.util.concurrent.TimeUnit
 
  51 @SpringBootTest(classes = [ObjectMapper, JsonObjectMapper, SubscriptionEventForwarder])
 
  52 class SubscriptionEventForwarderSpec extends MessagingBaseSpec {
 
  55     SubscriptionEventForwarder objectUnderTest
 
  58     InventoryPersistence mockInventoryPersistence = Mock(InventoryPersistence)
 
  60     EventsPublisher<CloudEvent> mockSubscriptionEventPublisher = Mock(EventsPublisher<CloudEvent>)
 
  62     IMap<String, Set<String>> mockForwardedSubscriptionEventCache = Mock(IMap<String, Set<String>>)
 
  64     SubscriptionEventResponseOutcome mockSubscriptionEventResponseOutcome = Mock(SubscriptionEventResponseOutcome)
 
  66     SubscriptionPersistence mockSubscriptionPersistence = Mock(SubscriptionPersistence)
 
  68     SubscriptionEventMapper subscriptionEventMapper = Mappers.getMapper(SubscriptionEventMapper)
 
  70     ClientSubscriptionEventMapper clientSubscriptionEventMapper = Mappers.getMapper(ClientSubscriptionEventMapper)
 
  72     JsonObjectMapper jsonObjectMapper
 
  74     def objectMapper = new ObjectMapper()
 
  76     def 'Forward valid CM create subscription and simulate timeout'() {
 
  78             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
 
  79             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
 
  80         and: 'the InventoryPersistence returns private properties for the supplied CM Handles'
 
  81             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> [
 
  82                 createYangModelCmHandleWithDmiProperty(1, 1,"shape","circle"),
 
  83                 createYangModelCmHandleWithDmiProperty(2, 1,"shape","square")
 
  85         and: 'the thread creation delay is reduced to 2 seconds for testing'
 
  86             objectUnderTest.dmiResponseTimeoutInMs = 2000
 
  87         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
 
  88             def block = new BlockingVariable<Object>(5)
 
  89         when: 'the valid event is forwarded'
 
  90             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent, 'subscriptionCreated')
 
  91         then: 'An asynchronous call is made to the blocking variable'
 
  93         then: 'the event is added to the forwarded subscription event cache'
 
  94             1 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1"] as Set, 600, TimeUnit.SECONDS)
 
  95         and: 'the event is forwarded twice with the CMHandle private properties and provides a valid listenable future'
 
  96             1 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
 
  98                     def targets = toSubscriptionEvent(cloudEvent).getData().getPredicates().getTargets()
 
  99                     def cmHandle2 = createCmHandle('CMHandle2', ['shape':'square'] as Map)
 
 100                     def cmHandle1 = createCmHandle('CMHandle1', ['shape':'circle'] as Map)
 
 101                     targets == [cmHandle2, cmHandle1]
 
 104         and: 'a separate thread has been created where the map is polled'
 
 105             1 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
 
 106             1 * mockSubscriptionEventResponseOutcome.sendResponse(*_)
 
 107         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
 
 108             1 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
 
 111     def 'Forward CM create subscription where target CM Handles are #scenario'() {
 
 113             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
 
 114             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
 
 115         and: 'the target CMHandles are set to #scenario'
 
 116             testEventSent.getData().getPredicates().setTargets(invalidTargets)
 
 117         when: 'the event is forwarded'
 
 118             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent, 'some-event-type')
 
 119         then: 'an operation not yet supported exception is thrown'
 
 120             thrown(OperationNotYetSupportedException)
 
 122             scenario   | invalidTargets
 
 125             'wildcard' | ['CMHandle*']
 
 128     def 'Forward valid CM create subscription where targets are not associated to any existing CMHandles'() {
 
 130             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
 
 131             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
 
 132         and: 'a subscription event response'
 
 133             def emptySubscriptionEventResponse = new SubscriptionEventResponse().withData(new Data());
 
 134             emptySubscriptionEventResponse.getData().setSubscriptionName('cm-subscription-001');
 
 135             emptySubscriptionEventResponse.getData().setClientId('SCO-9989752');
 
 136         and: 'the cm handles will be rejected'
 
 137             def rejectedCmHandles = [new TargetCmHandle('CMHandle1', SubscriptionStatus.REJECTED, 'Cm handle does not exist'),
 
 138                                      new TargetCmHandle('CMHandle2',SubscriptionStatus.REJECTED, 'Cm handle does not exist'),
 
 139                                      new TargetCmHandle('CMHandle3',SubscriptionStatus.REJECTED, 'Cm handle does not exist')]
 
 140         and: 'a yang model subscription event will be saved into the db with rejected cm handles'
 
 141             def yangModelSubscriptionEvent = subscriptionEventMapper.toYangModelSubscriptionEvent(testEventSent)
 
 142             yangModelSubscriptionEvent.getPredicates().setTargetCmHandles(rejectedCmHandles)
 
 143         and: 'the InventoryPersistence returns no private properties for the supplied CM Handles'
 
 144             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> []
 
 145         and: 'the thread creation delay is reduced to 2 seconds for testing'
 
 146             objectUnderTest.dmiResponseTimeoutInMs = 2000
 
 147         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
 
 148             def block = new BlockingVariable<Object>(5)
 
 149         when: 'the valid event is forwarded'
 
 150             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent, 'subscriptionCreatedStatus')
 
 151         then: 'the event is not added to the forwarded subscription event cache'
 
 152             0 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1", "DMIName2"] as Set)
 
 153         and: 'the event is not being forwarded with the CMHandle private properties and does not provides a valid listenable future'
 
 154             0 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
 
 156                     def targets = toSubscriptionEvent(cloudEvent).getData().getPredicates().getTargets()
 
 157                     def cmHandle2 = createCmHandle('CMHandle2', ['shape':'square'] as Map)
 
 158                     def cmHandle1 = createCmHandle('CMHandle1', ['shape':'circle'] as Map)
 
 159                     targets == [cmHandle2, cmHandle1]
 
 162             0 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
 
 164                     def targets = toSubscriptionEvent(cloudEvent).getData().getPredicates().getTargets()
 
 165                     def cmHandle3 = createCmHandle('CMHandle3', ['shape':'triangle'] as Map)
 
 166                     targets == [cmHandle3]
 
 169         and: 'a separate thread has been created where the map is polled'
 
 170             0 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
 
 171             0 * mockForwardedSubscriptionEventCache.get(_)
 
 172         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
 
 173             0 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
 
 174         and: 'the persistence service save target cm handles of the yang model subscription event as rejected '
 
 175             1 * mockSubscriptionPersistence.saveSubscriptionEvent(yangModelSubscriptionEvent)
 
 176         and: 'subscription outcome has been sent'
 
 177             1 * mockSubscriptionEventResponseOutcome.sendResponse(emptySubscriptionEventResponse, 'subscriptionCreatedStatus')
 
 180     static def createYangModelCmHandleWithDmiProperty(id, dmiId,propertyName, propertyValue) {
 
 181         return new YangModelCmHandle(id:"CMHandle" + id, dmiDataServiceName: "DMIName" + dmiId, dmiProperties: [new YangModelCmHandle.Property(propertyName,propertyValue)])
 
 184     static def createCmHandle(id, additionalProperties) {
 
 185         def cmHandle = new CmHandle();
 
 187         cmHandle.setAdditionalProperties(additionalProperties)
 
 191     def toSubscriptionEvent(cloudEvent) {
 
 192         final PojoCloudEventData<org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent> deserializedCloudEvent = CloudEventUtils
 
 193             .mapData(cloudEvent, PojoCloudEventDataMapper.from(objectMapper,
 
 194                 org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent.class));
 
 195         if (deserializedCloudEvent == null) {
 
 198             return deserializedCloudEvent.getValue();