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