2efd321b8d19a5d121a4fe1ad0d9bac8877a4c9d
[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.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import lombok.RequiredArgsConstructor;
34 import lombok.extern.slf4j.Slf4j;
35 import org.onap.cps.api.CpsDataService;
36 import org.onap.cps.api.CpsQueryService;
37 import org.onap.cps.cpspath.parser.CpsPathUtil;
38 import org.onap.cps.ncmp.api.impl.operations.DatastoreType;
39 import org.onap.cps.spi.model.DataNode;
40 import org.onap.cps.utils.ContentType;
41 import org.onap.cps.utils.JsonObjectMapper;
42 import org.springframework.stereotype.Service;
43
44 @Slf4j
45 @Service
46 @RequiredArgsConstructor
47 public class CmNotificationSubscriptionPersistenceServiceImpl implements CmNotificationSubscriptionPersistenceService {
48
49     private static final String SUBSCRIPTION_ANCHOR_NAME = "cm-data-subscriptions";
50     private static final String CM_SUBSCRIPTION_CPS_PATH_QUERY = """
51             /datastores/datastore[@name='%s']/cm-handles/cm-handle[@id='%s']/filters/filter[@xpath='%s']
52             """.trim();
53     private static final String SUBSCRIPTION_IDS_CPS_PATH_QUERY = """
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                 SUBSCRIPTION_IDS_CPS_PATH_QUERY.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                 CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
80                         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 addOrUpdateCmNotificationSubscription(final DatastoreType datastoreType, final String cmHandleId,
92                                                       final String xpath, final String newSubscriptionId) {
93         if (isOngoingCmNotificationSubscription(datastoreType, cmHandleId, xpath)) {
94             final DataNode existingFilterNode =
95                     cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
96                             CM_SUBSCRIPTION_CPS_PATH_QUERY.formatted(datastoreType.getDatastoreName(), cmHandleId,
97                                     escapeQuotesByDoublingThem(xpath)),
98                             OMIT_DESCENDANTS).iterator().next();
99             final Collection<String> existingSubscriptionIds = getOngoingCmNotificationSubscriptionIds(datastoreType,
100                     cmHandleId, xpath);
101             if (!existingSubscriptionIds.contains(newSubscriptionId)) {
102                 updateListOfSubscribers(existingSubscriptionIds, newSubscriptionId, existingFilterNode);
103             }
104         } else {
105             addNewSubscriptionViaDatastore(datastoreType, cmHandleId, xpath, newSubscriptionId);
106         }
107     }
108
109     private void addNewSubscriptionViaDatastore(final DatastoreType datastoreType, final String cmHandleId,
110                                                 final String xpath, final String newSubscriptionId) {
111         final String parentXpath = "/datastores/datastore[@name='%s']/cm-handles"
112                 .formatted(datastoreType.getDatastoreName());
113         final String updatedJson = String.format("{\"cm-handle\":[{\"id\":\"%s\",\"filters\":{\"filter\":"
114                 + "[{\"xpath\":\"%s\",\"subscriptionIds\":[\"%s\"]}]}}]}", cmHandleId, xpath, newSubscriptionId);
115         cpsDataService.saveData(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME, parentXpath, updatedJson,
116                 OffsetDateTime.now(), ContentType.JSON);
117     }
118
119     private void updateListOfSubscribers(final Collection<String> existingSubscriptionIds,
120                                          final String newSubscriptionId, final DataNode existingFilterNode) {
121         final String parentXpath = CpsPathUtil.getNormalizedParentXpath(existingFilterNode.getXpath());
122         final List<String> updatedSubscribers = new ArrayList<>(existingSubscriptionIds);
123         updatedSubscribers.add(newSubscriptionId);
124         final Map<String, Serializable> updatedLeaves = new HashMap<>();
125         updatedLeaves.put("xpath", existingFilterNode.getLeaves().get("xpath"));
126         updatedLeaves.put("subscriptionIds", (Serializable) updatedSubscribers);
127         final String updatedJson = "{\"filter\":[" + jsonObjectMapper.asJsonString(updatedLeaves) + "]}";
128         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME, parentXpath, updatedJson,
129                 OffsetDateTime.now());
130     }
131
132     private static String escapeQuotesByDoublingThem(final String inputXpath) {
133         return inputXpath.replace("'", "''");
134     }
135 }