Introduce Hazelcast for alternateId-cmHandle relation pt. 2 - error collection
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServicePropertyHandler.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  Modifications Copyright (C) 2023 TechMahindra Ltd.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.ncmp.api.impl;
24
25 import static org.onap.cps.ncmp.api.NcmpResponseStatus.ALTERNATE_ID_ALREADY_ASSOCIATED;
26 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
27 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
28 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.DMI_PROPERTY;
29 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
30 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME;
31 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
32 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
33
34 import com.google.common.collect.ImmutableMap;
35 import java.time.OffsetDateTime;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.LinkedHashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import lombok.RequiredArgsConstructor;
46 import lombok.extern.slf4j.Slf4j;
47 import org.onap.cps.api.CpsDataService;
48 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
49 import org.onap.cps.ncmp.api.impl.utils.CmHandleIdMapper;
50 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
51 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
52 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
53 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
54 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
55 import org.onap.cps.spi.exceptions.DataValidationException;
56 import org.onap.cps.spi.model.DataNode;
57 import org.onap.cps.spi.model.DataNodeBuilder;
58 import org.onap.cps.utils.JsonObjectMapper;
59 import org.springframework.stereotype.Service;
60
61 @Slf4j
62 @Service
63 @RequiredArgsConstructor
64 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
65 @SuppressWarnings("squid:S5852")
66 public class NetworkCmProxyDataServicePropertyHandler {
67
68     private final InventoryPersistence inventoryPersistence;
69     private final CpsDataService cpsDataService;
70     private final JsonObjectMapper jsonObjectMapper;
71     private final CmHandleIdMapper cmHandleIdMapper;
72
73     /**
74      * Iterates over incoming ncmpServiceCmHandles and update the dataNodes based on the updated attributes.
75      * The attributes which are not passed will remain as is.
76      *
77      * @param ncmpServiceCmHandles collection of ncmpServiceCmHandles
78      */
79     public List<CmHandleRegistrationResponse> updateCmHandleProperties(
80         final Collection<NcmpServiceCmHandle> ncmpServiceCmHandles) {
81         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>();
82         for (final NcmpServiceCmHandle ncmpServiceCmHandle : ncmpServiceCmHandles) {
83             final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
84             try {
85                 if (cmHandleIdMapper.isDuplicateId(ncmpServiceCmHandle.getCmHandleId(),
86                         ncmpServiceCmHandle.getAlternateId())) {
87                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createFailureResponse(cmHandleId,
88                             ALTERNATE_ID_ALREADY_ASSOCIATED));
89                 } else {
90                     final DataNode existingCmHandleDataNode = inventoryPersistence.getCmHandleDataNode(cmHandleId)
91                             .iterator().next();
92                     updateAlternateId(existingCmHandleDataNode, ncmpServiceCmHandle);
93                     processUpdates(existingCmHandleDataNode, ncmpServiceCmHandle);
94                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
95                 }
96             } catch (final DataNodeNotFoundException e) {
97                 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId, e.getMessage());
98                 cmHandleRegistrationResponses.add(
99                     CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
100             } catch (final DataValidationException e) {
101                 log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
102                 cmHandleRegistrationResponses.add(
103                     CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
104             } catch (final Exception exception) {
105                 log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
106                 cmHandleRegistrationResponses.add(
107                     CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
108             }
109         }
110         return cmHandleRegistrationResponses;
111     }
112
113     private void updateAlternateId(final DataNode existingCmHandleDataNode,
114                                    final NcmpServiceCmHandle ncmpServiceCmHandle) {
115         final String newAlternateId = ncmpServiceCmHandle.getAlternateId();
116         if (cmHandleIdMapper.addMapping(ncmpServiceCmHandle.getCmHandleId(), newAlternateId)) {
117             try {
118                 final YangModelCmHandle yangModelCmHandle =
119                         YangDataConverter.convertCmHandleToYangModel(existingCmHandleDataNode,
120                                 ncmpServiceCmHandle.getCmHandleId());
121                 setAndUpdateAlternateId(yangModelCmHandle, newAlternateId);
122             } catch (final Exception e) {
123                 cmHandleIdMapper.removeMapping(ncmpServiceCmHandle.getCmHandleId());
124                 throw e;
125             }
126         }
127     }
128
129     private void processUpdates(final DataNode existingCmHandleDataNode, final NcmpServiceCmHandle incomingCmHandle) {
130         if (!incomingCmHandle.getPublicProperties().isEmpty()) {
131             updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY, incomingCmHandle.getPublicProperties());
132         }
133         if (!incomingCmHandle.getDmiProperties().isEmpty()) {
134             updateProperties(existingCmHandleDataNode, DMI_PROPERTY, incomingCmHandle.getDmiProperties());
135         }
136     }
137
138     private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
139             final Map<String, String> incomingProperties) {
140         final Collection<DataNode> replacementPropertyDataNodes =
141                 getReplacementDataNodes(existingCmHandleDataNode, propertyType, incomingProperties);
142         replacementPropertyDataNodes.addAll(
143                 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, incomingProperties));
144         if (replacementPropertyDataNodes.isEmpty()) {
145             removeAllProperties(existingCmHandleDataNode, propertyType);
146         } else {
147             inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
148         }
149     }
150
151     private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
152         existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
153             final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
154             if (matcher.find()) {
155                 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
156                 inventoryPersistence.deleteDataNode(dataNode.getXpath());
157             }
158         });
159     }
160
161     private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
162             final PropertyType propertyType, final Map<String, String> incomingProperties) {
163         final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
164         for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
165             final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
166             if (matcher.find()) {
167                 final String keyName = matcher.group(2);
168                 if (!incomingProperties.containsKey(keyName)) {
169                     unchangedPropertyDataNodes.add(existingPropertyDataNode);
170                 }
171             }
172         }
173         return unchangedPropertyDataNodes;
174     }
175
176     private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
177             final PropertyType propertyType, final Map<String, String> incomingProperties) {
178         final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
179         incomingProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
180             final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
181             if (updatedAttributeValue != null) {
182                 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
183                         updatedAttributeKey, updatedAttributeValue);
184                 replacementPropertyDataNodes.add(
185                         buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
186             }
187         });
188         return replacementPropertyDataNodes;
189     }
190
191     private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
192             final String attributeKey) {
193         return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
194     }
195
196     private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
197         final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
198         updatedLeaves.put("name", attributeKey);
199         updatedLeaves.put("value", attributeValue);
200         log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
201                 attributeValue);
202         return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
203     }
204
205     private void setAndUpdateAlternateId(final YangModelCmHandle upgradedCmHandle, final String alternateId) {
206         final Map<String, Map<String, String>> dmiRegistryProperties = new HashMap<>(1);
207         final Map<String, String> cmHandleProperties = new HashMap<>(2);
208         cmHandleProperties.put("id", upgradedCmHandle.getId());
209         cmHandleProperties.put("alternate-id", alternateId);
210         dmiRegistryProperties.put("cm-handles", cmHandleProperties);
211         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
212                 jsonObjectMapper.asJsonString(dmiRegistryProperties), OffsetDateTime.now());
213         log.info("Updating alternateId for cmHandle {} with value : {})", upgradedCmHandle.getId(), alternateId);
214     }
215
216     enum PropertyType {
217         DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
218
219         private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
220
221         final String xpathPrefix;
222         final Pattern propertyXpathPattern;
223
224         PropertyType(final String xpathPrefix) {
225             this.xpathPrefix = xpathPrefix;
226             this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);
227         }
228     }
229 }