c29d042293ec331e33e5d1d7ab012114dd12acac
[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  * Modifications Copyright (C) 2022-2023 Nordix Foundation
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *         http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.notification;
23
24 import jakarta.annotation.PostConstruct;
25 import java.time.OffsetDateTime;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.concurrent.CompletableFuture;
30 import java.util.concurrent.Future;
31 import java.util.regex.Pattern;
32 import java.util.stream.Collectors;
33 import lombok.RequiredArgsConstructor;
34 import lombok.extern.slf4j.Slf4j;
35 import org.onap.cps.api.CpsAdminService;
36 import org.onap.cps.spi.model.Anchor;
37 import org.springframework.scheduling.annotation.Async;
38 import org.springframework.stereotype.Service;
39
40 @Service
41 @Slf4j
42 @RequiredArgsConstructor
43 public class NotificationService {
44
45     private final NotificationProperties notificationProperties;
46     private final NotificationPublisher notificationPublisher;
47     private final CpsDataUpdatedEventFactory cpsDataUpdatedEventFactory;
48     private final NotificationErrorHandler notificationErrorHandler;
49     private final CpsAdminService cpsAdminService;
50     private List<Pattern> dataspacePatterns;
51
52     @PostConstruct
53     public void init() {
54         log.info("Notification Properties {}", notificationProperties);
55         this.dataspacePatterns = getDataspaceFilterPatterns(notificationProperties);
56     }
57
58     private List<Pattern> getDataspaceFilterPatterns(final NotificationProperties notificationProperties) {
59         if (notificationProperties.isEnabled()) {
60             return Arrays.stream(notificationProperties.getFilters()
61                 .getOrDefault("enabled-dataspaces", "")
62                 .split(","))
63                 .map(filterPattern -> Pattern.compile(filterPattern, Pattern.CASE_INSENSITIVE))
64                 .collect(Collectors.toList());
65         } else {
66             return Collections.emptyList();
67         }
68     }
69
70     /**
71      * Process Data Updated Event and publishes the notification.
72      *
73      * @param anchor            anchor
74      * @param xpath             xpath of changed data node
75      * @param operation         operation
76      * @param observedTimestamp observedTimestamp
77      * @return future
78      */
79     @Async("notificationExecutor")
80     public Future<Void> processDataUpdatedEvent(final Anchor anchor, final String xpath, final Operation operation,
81                                                 final OffsetDateTime observedTimestamp) {
82
83         log.debug("process data updated event for anchor '{}'", anchor);
84         try {
85             if (shouldSendNotification(anchor.getDataspaceName())) {
86                 final var cpsDataUpdatedEvent =
87                         cpsDataUpdatedEventFactory.createCpsDataUpdatedEvent(anchor,
88                                 observedTimestamp, getRootNodeOperation(xpath, operation));
89                 log.debug("data updated event to be published {}", cpsDataUpdatedEvent);
90                 notificationPublisher.sendNotification(cpsDataUpdatedEvent);
91             }
92         } catch (final Exception exception) {
93             /* All the exceptions are handled to not to propagate it to caller.
94                CPS operation should not fail if sending event fails for any reason.
95              */
96             notificationErrorHandler.onException("Failed to process cps-data-updated-event.",
97                     exception, anchor, xpath, operation);
98         }
99         return CompletableFuture.completedFuture(null);
100     }
101
102     /*
103         Add more complex rules based on dataspace and anchor later
104      */
105     private boolean shouldSendNotification(final String dataspaceName) {
106
107         return notificationProperties.isEnabled()
108             && dataspacePatterns.stream()
109             .anyMatch(pattern -> pattern.matcher(dataspaceName).find());
110     }
111
112     private Operation getRootNodeOperation(final String xpath, final Operation operation) {
113         return isRootXpath(xpath) || isRootContainerNodeXpath(xpath) ? operation : Operation.UPDATE;
114     }
115
116     private static boolean isRootXpath(final String xpath) {
117         return "/".equals(xpath) || "".equals(xpath);
118     }
119
120     private static boolean isRootContainerNodeXpath(final String xpath) {
121         return 0 == xpath.lastIndexOf('/');
122     }
123
124 }