14259d87b4f2a227e098a44aa1f48f7be5cbc9c9
[cps.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2024-2025 OpenInfra Foundation Europe. All rights reserved.
4  *  Modifications Copyright (C) 2024 TechMahindra Ltd.
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.ncmp.impl.datajobs.subscription.utils;
23
24 import static org.onap.cps.api.parameters.FetchDescendantsOption.OMIT_DESCENDANTS;
25 import static org.onap.cps.ncmp.impl.datajobs.subscription.models.CmSubscriptionStatus.UNKNOWN;
26
27 import java.io.Serializable;
28 import java.time.OffsetDateTime;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Map;
34 import lombok.RequiredArgsConstructor;
35 import lombok.extern.slf4j.Slf4j;
36 import org.onap.cps.api.CpsDataService;
37 import org.onap.cps.api.CpsQueryService;
38 import org.onap.cps.api.model.DataNode;
39 import org.onap.cps.utils.ContentType;
40 import org.onap.cps.utils.JsonObjectMapper;
41 import org.springframework.stereotype.Service;
42
43 @Slf4j
44 @Service
45 @RequiredArgsConstructor
46 public class CmDataJobSubscriptionPersistenceService {
47
48     private static final String DATASPACE = "NCMP-Admin";
49     private static final String ANCHOR = "cm-data-job-subscriptions";
50
51     private static final String PARENT_NODE_XPATH = "/dataJob";
52     private static final String CPS_PATH_FOR_SUBSCRIPTION_NODE = "//subscription";
53     private static final String CPS_PATH_TEMPLATE_FOR_SUBSCRIPTIONS_WITH_DATA_NODE_SELECTOR =
54             CPS_PATH_FOR_SUBSCRIPTION_NODE + "[@dataNodeSelector='%s']";
55     private static final String CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_DATA_JOB_ID =
56         CPS_PATH_FOR_SUBSCRIPTION_NODE + "/dataJobId[text()='%s']";
57     private static final String CPS_PATH_TEMPLATE_FOR_INACTIVE_SUBSCRIPTIONS =
58             CPS_PATH_FOR_SUBSCRIPTION_NODE + "[@status='UNKNOWN' or @status='REJECTED']/dataJobId[text()='%s']";
59
60     private final JsonObjectMapper jsonObjectMapper;
61     private final CpsQueryService cpsQueryService;
62     private final CpsDataService cpsDataService;
63
64     /**
65      * Check if we have a cm data job subscription for the given data node selector.
66      *
67      * @param dataNodeSelector the target of the data job subscription
68      * @return true if the subscription details has at least one subscriber , otherwise false
69      */
70     public boolean hasAtLeastOneSubscription(final String dataNodeSelector) {
71         return !getSubscriptionIds(dataNodeSelector).isEmpty();
72     }
73
74     /**
75      * Check if the input is a new subscription ID against ongoing subscriptions.
76      *
77      * @param subscriptionId subscription ID
78      * @return true if subscriptionId is not used in active subscriptions, otherwise false
79      */
80     public boolean isNewSubscriptionId(final String subscriptionId) {
81         final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_DATA_JOB_ID.formatted(subscriptionId);
82         return cpsQueryService.queryDataNodes(DATASPACE, ANCHOR,
83             query, OMIT_DESCENDANTS).isEmpty();
84     }
85
86     /**
87      * Get the ids for the subscriptions for the given data node selector.
88      *
89      * @param dataNodeSelector the target of the data job subscription
90      * @return collection of subscription ids of ongoing cm notification subscription
91      */
92     @SuppressWarnings("unchecked")
93     public Collection<String> getSubscriptionIds(final String dataNodeSelector) {
94         final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTIONS_WITH_DATA_NODE_SELECTOR.formatted(dataNodeSelector);
95         final Collection<DataNode> existingNodes =
96             cpsQueryService.queryDataNodes(DATASPACE, ANCHOR,
97                 query, OMIT_DESCENDANTS);
98         if (existingNodes.isEmpty()) {
99             return Collections.emptyList();
100         }
101         return (Collection<String>) existingNodes.iterator().next().getLeaves().get("dataJobId");
102     }
103
104     /**
105      * Get data node selectors for subscriptions with status UNKNOWN or REJECTED.
106      *
107      * @param subscriptionId    subscription ID
108      * @return                  a list of data node selectors
109      */
110     public List<String> getInactiveDataNodeSelectors(final String subscriptionId) {
111         final String query = CPS_PATH_TEMPLATE_FOR_INACTIVE_SUBSCRIPTIONS.formatted(subscriptionId);
112         final Collection<DataNode> dataNodes = cpsQueryService.queryDataNodes(DATASPACE, ANCHOR, query,
113                 OMIT_DESCENDANTS);
114         final List<String> dataNodeSelectors = new ArrayList<>(dataNodes.size());
115         for (final DataNode dataNode : dataNodes) {
116             final String dataNodeSelector = dataNode.getLeaves().get("dataNodeSelector").toString();
117             dataNodeSelectors.add(dataNodeSelector);
118         }
119         return dataNodeSelectors;
120     }
121
122     /**
123      * Add cm notification data job subscription.
124      *
125      * @param subscriptionId   data job subscription id to be added
126      * @param dataNodeSelector the target of the data job subscription
127      */
128     public void add(final String subscriptionId, final String dataNodeSelector) {
129         final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTIONS_WITH_DATA_NODE_SELECTOR.formatted(dataNodeSelector);
130         final Collection<DataNode> dataNodes = cpsQueryService.queryDataNodes(DATASPACE, ANCHOR, query,
131                 OMIT_DESCENDANTS);
132         if (dataNodes.isEmpty()) {
133             addNewSubscriptionDetails(subscriptionId, dataNodeSelector);
134         } else {
135             final Collection<String> subscriptionIds = getSubscriptionIds(dataNodeSelector);
136             final String status = dataNodes.iterator().next().getLeaves().get("status").toString();
137             subscriptionIds.add(subscriptionId);
138             updateSubscriptionDetails(dataNodeSelector, subscriptionIds, status);
139         }
140     }
141
142     private void addNewSubscriptionDetails(final String subscriptionId,
143                                            final String dataNodeSelector) {
144         final Collection<String> newSubscriptionList = Collections.singletonList(subscriptionId);
145         final String status = UNKNOWN.name();
146         final String subscriptionDetailsAsJson = createSubscriptionDetailsAsJson(dataNodeSelector,
147                 newSubscriptionList, status);
148         cpsDataService.saveData(DATASPACE, ANCHOR, subscriptionDetailsAsJson,
149             OffsetDateTime.now(), ContentType.JSON);
150     }
151
152     private void updateSubscriptionDetails(final String dataNodeSelector, final Collection<String> subscriptionIds,
153                                            final String status) {
154         final String subscriptionDetailsAsJson = createSubscriptionDetailsAsJson(dataNodeSelector,
155                 subscriptionIds, status);
156         cpsDataService.updateNodeLeaves(DATASPACE, ANCHOR,
157                 PARENT_NODE_XPATH, subscriptionDetailsAsJson, OffsetDateTime.now(),
158             ContentType.JSON);
159     }
160
161     private String createSubscriptionDetailsAsJson(final String dataNodeSelector,
162                                                    final Collection<String> subscriptionIds,
163                                                    final String status) {
164         final Map<String, Serializable> subscriptionDetailsAsMap =
165             Map.of("dataNodeSelector", dataNodeSelector,
166                 "dataJobId", (Serializable) subscriptionIds,
167                 "status", status);
168         return "{\"subscription\":[" + jsonObjectMapper.asJsonString(subscriptionDetailsAsMap) + "]}";
169     }
170 }
171