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