3371d59f7add58ac246ad227c396b3e7596e7b63
[cps.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2024 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
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.impl.cmnotificationsubscription.ncmp;
22
23 import io.cloudevents.CloudEvent;
24 import io.cloudevents.core.builder.CloudEventBuilder;
25 import java.net.URI;
26 import java.util.Map;
27 import java.util.UUID;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.Executors;
30 import java.util.concurrent.ScheduledExecutorService;
31 import java.util.concurrent.ScheduledFuture;
32 import java.util.concurrent.TimeUnit;
33 import lombok.RequiredArgsConstructor;
34 import lombok.extern.slf4j.Slf4j;
35 import org.onap.cps.events.EventsPublisher;
36 import org.onap.cps.ncmp.impl.cmnotificationsubscription.cache.DmiCacheHandler;
37 import org.onap.cps.ncmp.impl.cmnotificationsubscription_1_0_0.ncmp_to_client.NcmpOutEvent;
38 import org.onap.cps.utils.JsonObjectMapper;
39 import org.springframework.beans.factory.annotation.Value;
40 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
41 import org.springframework.stereotype.Component;
42
43 @Component
44 @Slf4j
45 @RequiredArgsConstructor
46 @ConditionalOnProperty(name = "notification.enabled", havingValue = "true", matchIfMissing = true)
47 public class NcmpOutEventProducer {
48
49     @Value("${app.ncmp.avc.cm-subscription-ncmp-out}")
50     private String ncmpOutEventTopic;
51
52     @Value("${ncmp.timers.subscription-forwarding.dmi-response-timeout-ms}")
53     private Integer dmiOutEventTimeoutInMs;
54
55     private final EventsPublisher<CloudEvent> eventsPublisher;
56     private final JsonObjectMapper jsonObjectMapper;
57     private final NcmpOutEventMapper ncmpOutEventMapper;
58     private final DmiCacheHandler dmiCacheHandler;
59     private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
60     private static final Map<String, ScheduledFuture<?>> scheduledTasksPerSubscriptionIdAndEventType =
61             new ConcurrentHashMap<>();
62
63     /**
64      * Publish the event to the client who requested the subscription with key as subscription id and event is Cloud
65      * Event compliant.
66      *
67      * @param subscriptionId   Cm Subscription Id
68      * @param eventType        Type of event
69      * @param ncmpOutEvent     Cm Notification Subscription Event for the
70      *                         client
71      * @param isScheduledEvent Determines if the event is to be scheduled
72      *                         or published now
73      */
74     public void publishNcmpOutEvent(final String subscriptionId, final String eventType,
75             final NcmpOutEvent ncmpOutEvent, final boolean isScheduledEvent) {
76
77         final String taskKey = subscriptionId.concat(eventType);
78
79         if (isScheduledEvent && !scheduledTasksPerSubscriptionIdAndEventType.containsKey(taskKey)) {
80             final ScheduledFuture<?> scheduledFuture = scheduleAndPublishNcmpOutEvent(subscriptionId, eventType);
81             scheduledTasksPerSubscriptionIdAndEventType.putIfAbsent(taskKey, scheduledFuture);
82             log.debug("Scheduled the Cm Subscription Event for subscriptionId : {} and eventType : {}", subscriptionId,
83                     eventType);
84         } else {
85             cancelScheduledTask(taskKey);
86             if (ncmpOutEvent != null) {
87                 publishNcmpOutEventNow(subscriptionId, eventType, ncmpOutEvent);
88                 log.debug("Published Cm Subscription Event on demand for subscriptionId : {} and eventType : {}",
89                         subscriptionId, eventType);
90             }
91         }
92     }
93
94     private ScheduledFuture<?> scheduleAndPublishNcmpOutEvent(final String subscriptionId, final String eventType) {
95         final NcmpOutEventPublishingTask ncmpOutEventPublishingTask =
96                 new NcmpOutEventPublishingTask(ncmpOutEventTopic, subscriptionId, eventType, eventsPublisher,
97                         jsonObjectMapper, ncmpOutEventMapper, dmiCacheHandler);
98         return scheduledExecutorService.schedule(ncmpOutEventPublishingTask, dmiOutEventTimeoutInMs,
99                 TimeUnit.MILLISECONDS);
100     }
101
102     private void cancelScheduledTask(final String taskKey) {
103
104         final ScheduledFuture<?> scheduledFuture = scheduledTasksPerSubscriptionIdAndEventType.get(taskKey);
105         if (scheduledFuture != null) {
106             scheduledFuture.cancel(true);
107             scheduledTasksPerSubscriptionIdAndEventType.remove(taskKey);
108         }
109
110     }
111
112
113     private void publishNcmpOutEventNow(final String subscriptionId, final String eventType,
114             final NcmpOutEvent ncmpOutEvent) {
115         final CloudEvent ncmpOutEventAsCloudEvent =
116                 buildAndGetNcmpOutEventAsCloudEvent(jsonObjectMapper, subscriptionId, eventType, ncmpOutEvent);
117         eventsPublisher.publishCloudEvent(ncmpOutEventTopic, subscriptionId, ncmpOutEventAsCloudEvent);
118         dmiCacheHandler.removeAcceptedAndRejectedDmiSubscriptionEntries(subscriptionId);
119     }
120
121     /**
122      * Get an NCMP out event as cloud event.
123      *
124      * @param jsonObjectMapper JSON object mapper
125      * @param subscriptionId   subscription id
126      * @param eventType        event type
127      * @param ncmpOutEvent     cm notification subscription NCMP out event
128      * @return cm notification subscription NCMP out event as cloud event
129      */
130     public static CloudEvent buildAndGetNcmpOutEventAsCloudEvent(final JsonObjectMapper jsonObjectMapper,
131             final String subscriptionId, final String eventType, final NcmpOutEvent ncmpOutEvent) {
132
133         return CloudEventBuilder.v1().withId(UUID.randomUUID().toString()).withType(eventType)
134                        .withSource(URI.create("NCMP")).withDataSchema(URI.create("org.onap.ncmp.cm.subscription:1.0.0"))
135                        .withExtension("correlationid", subscriptionId)
136                        .withData(jsonObjectMapper.asJsonBytes(ncmpOutEvent)).build();
137     }
138
139 }