CM SUBSCRIPTION: Update schemas
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / events / cmsubscription / service / CmNotificationSubscriptionPersistenceServiceImpl.java
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.api.impl.events.cmsubscription.service;
22
23 import static org.onap.cps.spi.FetchDescendantsOption.OMIT_DESCENDANTS;
24
25 import java.io.Serializable;
26 import java.time.OffsetDateTime;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Map;
31 import lombok.RequiredArgsConstructor;
32 import lombok.extern.slf4j.Slf4j;
33 import org.onap.cps.api.CpsDataService;
34 import org.onap.cps.api.CpsQueryService;
35 import org.onap.cps.ncmp.api.impl.operations.DatastoreType;
36 import org.onap.cps.spi.model.DataNode;
37 import org.onap.cps.utils.ContentType;
38 import org.onap.cps.utils.JsonObjectMapper;
39 import org.springframework.stereotype.Service;
40
41 @Slf4j
42 @Service
43 @RequiredArgsConstructor
44 public class CmNotificationSubscriptionPersistenceServiceImpl implements CmNotificationSubscriptionPersistenceService {
45
46     private static final String SUBSCRIPTION_ANCHOR_NAME = "cm-data-subscriptions";
47     private static final String CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_AND_CMHANDLE = """
48             /datastores/datastore[@name='%s']/cm-handles/cm-handle[@id='%s']/filters
49             """.trim();
50     private static final String CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_CMHANDLE_AND_XPATH =
51             CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_AND_CMHANDLE + "/filter[@xpath='%s']";
52
53     private static final String CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_ID = """
54             //filter/subscriptionIds[text()='%s']
55             """.trim();
56
57     private final JsonObjectMapper jsonObjectMapper;
58     private final CpsQueryService cpsQueryService;
59     private final CpsDataService cpsDataService;
60
61     @Override
62     public boolean isOngoingCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
63                                                        final String xpath) {
64         return !getOngoingCmNotificationSubscriptionIds(datastoreType, cmHandleId, xpath).isEmpty();
65     }
66
67     @Override
68     public boolean isUniqueSubscriptionId(final String subscriptionId) {
69         return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
70                 CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_ID.formatted(subscriptionId),
71                 OMIT_DESCENDANTS).isEmpty();
72     }
73
74     @Override
75     public Collection<String> getOngoingCmNotificationSubscriptionIds(final DatastoreType datastoreType,
76                                                                       final String cmHandleId, final String xpath) {
77
78         final String isOngoingCmSubscriptionCpsPathQuery =
79                 CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_CMHANDLE_AND_XPATH.formatted(
80                         datastoreType.getDatastoreName(), cmHandleId, escapeQuotesByDoublingThem(xpath));
81         final Collection<DataNode> existingNodes =
82                 cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, CM_SUBSCRIPTIONS_ANCHOR_NAME,
83                         isOngoingCmSubscriptionCpsPathQuery, OMIT_DESCENDANTS);
84         if (existingNodes.isEmpty()) {
85             return Collections.emptyList();
86         }
87         return (List<String>) existingNodes.iterator().next().getLeaves().get("subscriptionIds");
88     }
89
90     @Override
91     public void addCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
92                                               final String xpath, final String subscriptionId) {
93         final Collection<String> subscriptionIds = getOngoingCmNotificationSubscriptionIds(datastoreType,
94                 cmHandleId, xpath);
95         if (subscriptionIds.isEmpty()) {
96             addFirstSubscriptionForDatastoreCmHandleAndXpath(datastoreType, cmHandleId, xpath, subscriptionId);
97         } else if (!subscriptionIds.contains(subscriptionId)) {
98             subscriptionIds.add(subscriptionId);
99             saveSubscriptionDetails(datastoreType, cmHandleId, xpath, subscriptionIds);
100         }
101     }
102
103     @Override
104     public void removeCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
105                                                  final String xpath, final String subscriptionId) {
106         final Collection<String> subscriptionIds = getOngoingCmNotificationSubscriptionIds(datastoreType,
107                 cmHandleId, xpath);
108         if (subscriptionIds.remove(subscriptionId)) {
109             if (isOngoingCmNotificationSubscription(datastoreType, cmHandleId, xpath)) {
110                 saveSubscriptionDetails(datastoreType, cmHandleId, xpath, subscriptionIds);
111                 log.info("There are subscribers left for the following cps path {} :",
112                         CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_CMHANDLE_AND_XPATH.formatted(
113                                 datastoreType.getDatastoreName(), cmHandleId, escapeQuotesByDoublingThem(xpath)));
114             } else {
115                 log.info("No subscribers left for the following cps path {} :",
116                         CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_CMHANDLE_AND_XPATH.formatted(
117                                 datastoreType.getDatastoreName(), cmHandleId, escapeQuotesByDoublingThem(xpath)));
118                 deleteListOfSubscriptionsFor(datastoreType, cmHandleId, xpath);
119             }
120         }
121     }
122
123     private void deleteListOfSubscriptionsFor(final DatastoreType datastoreType, final String cmHandleId,
124                                               final String xpath) {
125         cpsDataService.deleteDataNode(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
126                 CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_CMHANDLE_AND_XPATH.formatted(
127                         datastoreType.getDatastoreName(), cmHandleId, escapeQuotesByDoublingThem(xpath)),
128                 OffsetDateTime.now());
129     }
130
131     private boolean isFirstSubscriptionForCmHandle(final DatastoreType datastoreType, final String cmHandleId) {
132         return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, CM_SUBSCRIPTIONS_ANCHOR_NAME,
133                 CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_AND_CMHANDLE.formatted(
134                         datastoreType.getDatastoreName(), cmHandleId),
135                 OMIT_DESCENDANTS).isEmpty();
136     }
137
138     private void addFirstSubscriptionForDatastoreCmHandleAndXpath(final DatastoreType datastoreType,
139                                                                   final String cmHandleId,
140                                                                   final String xpath,
141                                                                   final String subscriptionId) {
142         final Collection<String> newSubscriptionList = Collections.singletonList(subscriptionId);
143         final String subscriptionDetailsAsJson = getSubscriptionDetailsAsJson(xpath, newSubscriptionList);
144         if (isFirstSubscriptionForCmHandle(datastoreType, cmHandleId)) {
145             final String parentXpath = "/datastores/datastore[@name='%s']/cm-handles"
146                     .formatted(datastoreType.getDatastoreName());
147             final String subscriptionAsJson = String.format("{\"cm-handle\":[{\"id\":\"%s\",\"filters\":%s}]}",
148                     cmHandleId, subscriptionDetailsAsJson);
149             cpsDataService.saveData(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME, parentXpath, subscriptionAsJson,
150                     OffsetDateTime.now(), ContentType.JSON);
151         } else {
152             cpsDataService.saveListElements(NCMP_DATASPACE_NAME, CM_SUBSCRIPTIONS_ANCHOR_NAME,
153                     CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_AND_CMHANDLE.formatted(
154                             datastoreType.getDatastoreName(), cmHandleId),
155                     subscriptionDetailsAsJson, OffsetDateTime.now());
156         }
157     }
158
159     private void saveSubscriptionDetails(final DatastoreType datastoreType, final String cmHandleId,
160                                          final String xpath,
161                                          final  Collection<String> subscriptionIds) {
162         final String subscriptionDetailsAsJson = getSubscriptionDetailsAsJson(xpath, subscriptionIds);
163         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, CM_SUBSCRIPTIONS_ANCHOR_NAME,
164                 CPS_PATH_QUERY_FOR_CM_SUBSCRIPTION_WITH_DATASTORE_AND_CMHANDLE.formatted(
165                         datastoreType.getDatastoreName(), cmHandleId), subscriptionDetailsAsJson, OffsetDateTime.now());
166     }
167
168     private String getSubscriptionDetailsAsJson(final String xpath, final Collection<String> subscriptionIds) {
169         final Map<String, Serializable> subscriptionDetailsAsMap =
170                 Map.of("xpath", xpath, "subscriptionIds", (Serializable) subscriptionIds);
171         return "{\"filter\":[" + jsonObjectMapper.asJsonString(subscriptionDetailsAsMap) + "]}";
172     }
173
174     private static String escapeQuotesByDoublingThem(final String inputXpath) {
175         return inputXpath.replace("'", "''");
176     }
177 }