029efbe7957e1061a607779dd97996ec2703930f
[cps.git] / cps-service / src / main / java / org / onap / cps / notification / NotificationService.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (c) 2021 Bell Canada.
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.notification;
22
23 import java.time.OffsetDateTime;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.concurrent.CompletableFuture;
28 import java.util.concurrent.Future;
29 import java.util.regex.Pattern;
30 import java.util.stream.Collectors;
31 import lombok.extern.slf4j.Slf4j;
32 import org.springframework.scheduling.annotation.Async;
33 import org.springframework.stereotype.Service;
34
35 @Service
36 @Slf4j
37 public class NotificationService {
38
39     private NotificationProperties notificationProperties;
40     private NotificationPublisher notificationPublisher;
41     private CpsDataUpdatedEventFactory cpsDataUpdatedEventFactory;
42     private NotificationErrorHandler notificationErrorHandler;
43     private List<Pattern> dataspacePatterns;
44
45     /**
46      * Create an instance of Notification Subscriber.
47      *
48      * @param notificationProperties     properties for notification
49      * @param notificationPublisher      notification Publisher
50      * @param cpsDataUpdatedEventFactory to create CPSDataUpdatedEvent
51      * @param notificationErrorHandler   error handler
52      */
53     public NotificationService(
54         final NotificationProperties notificationProperties,
55         final NotificationPublisher notificationPublisher,
56         final CpsDataUpdatedEventFactory cpsDataUpdatedEventFactory,
57         final NotificationErrorHandler notificationErrorHandler) {
58         log.info("Notification Properties {}", notificationProperties);
59         this.notificationProperties = notificationProperties;
60         this.notificationPublisher = notificationPublisher;
61         this.cpsDataUpdatedEventFactory = cpsDataUpdatedEventFactory;
62         this.notificationErrorHandler = notificationErrorHandler;
63         this.dataspacePatterns = getDataspaceFilterPatterns(notificationProperties);
64     }
65
66     private List<Pattern> getDataspaceFilterPatterns(final NotificationProperties notificationProperties) {
67         if (notificationProperties.isEnabled()) {
68             return Arrays.stream(notificationProperties.getFilters()
69                 .getOrDefault("enabled-dataspaces", "")
70                 .split(","))
71                 .map(filterPattern -> Pattern.compile(filterPattern, Pattern.CASE_INSENSITIVE))
72                 .collect(Collectors.toList());
73         } else {
74             return Collections.emptyList();
75         }
76     }
77
78     /**
79      * Process Data Updated Event and publishes the notification.
80      *
81      * @param dataspaceName dataspace name
82      * @param anchorName    anchor name
83      * @param observedTimestamp observedTimestamp
84      * @return future
85      */
86     @Async("notificationExecutor")
87     public Future<Void> processDataUpdatedEvent(final String dataspaceName, final String anchorName,
88         final OffsetDateTime observedTimestamp) {
89         log.debug("process data updated event for dataspace '{}' & anchor '{}'", dataspaceName, anchorName);
90         try {
91             if (shouldSendNotification(dataspaceName)) {
92                 final var cpsDataUpdatedEvent =
93                     cpsDataUpdatedEventFactory.createCpsDataUpdatedEvent(dataspaceName, anchorName, observedTimestamp);
94                 log.debug("data updated event to be published {}", cpsDataUpdatedEvent);
95                 notificationPublisher.sendNotification(cpsDataUpdatedEvent);
96             }
97         } catch (final Exception exception) {
98             /* All the exceptions are handled to not to propagate it to caller.
99                CPS operation should not fail if sending event fails for any reason.
100              */
101             notificationErrorHandler.onException("Failed to process cps-data-updated-event.",
102                 exception, dataspaceName, anchorName);
103         }
104         return CompletableFuture.completedFuture(null);
105     }
106
107     /*
108         Add more complex rules based on dataspace and anchor later
109      */
110     private boolean shouldSendNotification(final String dataspaceName) {
111
112         return notificationProperties.isEnabled()
113             && dataspacePatterns.stream()
114             .anyMatch(pattern -> pattern.matcher(dataspaceName).find());
115     }
116
117 }