f5d22af2818b9e0cfb7d73e25a0a1d7c8909994e
[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.CM_HANDLES_NOT_FOUND;
26 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
27 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.DMI_PROPERTY;
28 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
29 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME;
30 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
31 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
32
33 import com.google.common.collect.ImmutableMap;
34 import java.time.OffsetDateTime;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.LinkedHashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.regex.Matcher;
43 import java.util.regex.Pattern;
44 import lombok.RequiredArgsConstructor;
45 import lombok.extern.slf4j.Slf4j;
46 import org.onap.cps.api.CpsDataService;
47 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
48 import org.onap.cps.ncmp.api.impl.utils.AlternateIdChecker;
49 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
50 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
51 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
52 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
53 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
54 import org.onap.cps.spi.exceptions.DataValidationException;
55 import org.onap.cps.spi.model.DataNode;
56 import org.onap.cps.spi.model.DataNodeBuilder;
57 import org.onap.cps.utils.JsonObjectMapper;
58 import org.springframework.stereotype.Service;
59
60 @Slf4j
61 @Service
62 @RequiredArgsConstructor
63 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
64 @SuppressWarnings("squid:S5852")
65 public class NetworkCmProxyDataServicePropertyHandler {
66
67     private final InventoryPersistence inventoryPersistence;
68     private final CpsDataService cpsDataService;
69     private final JsonObjectMapper jsonObjectMapper;
70     private final AlternateIdChecker alternateIdChecker;
71
72     /**
73      * Iterates over incoming ncmpServiceCmHandles and update the dataNodes based on the updated attributes.
74      * The attributes which are not passed will remain as is.
75      *
76      * @param ncmpServiceCmHandles collection of ncmpServiceCmHandles
77      */
78     public List<CmHandleRegistrationResponse> updateCmHandleProperties(
79         final Collection<NcmpServiceCmHandle> ncmpServiceCmHandles) {
80         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses
81             = new ArrayList<>(ncmpServiceCmHandles.size());
82         for (final NcmpServiceCmHandle ncmpServiceCmHandle : ncmpServiceCmHandles) {
83             final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
84             try {
85                 final DataNode existingCmHandleDataNode = inventoryPersistence
86                     .getCmHandleDataNodeByCmHandleId(cmHandleId).iterator().next();
87                 updateAlternateId(existingCmHandleDataNode, ncmpServiceCmHandle);
88                 processUpdates(existingCmHandleDataNode, ncmpServiceCmHandle);
89                 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
90             } catch (final DataNodeNotFoundException e) {
91                 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId, e.getMessage());
92                 cmHandleRegistrationResponses.add(
93                     CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
94             } catch (final DataValidationException e) {
95                 log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
96                 cmHandleRegistrationResponses.add(
97                     CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
98             } catch (final Exception exception) {
99                 log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
100                 cmHandleRegistrationResponses.add(
101                     CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
102             }
103         }
104         return cmHandleRegistrationResponses;
105     }
106
107     private void updateAlternateId(final DataNode existingCmHandleDataNode,
108                                    final NcmpServiceCmHandle ncmpServiceCmHandle) {
109         final YangModelCmHandle yangModelCmHandle =
110             YangDataConverter.convertCmHandleToYangModel(existingCmHandleDataNode);
111         final String currentAlternateId = yangModelCmHandle.getAlternateId();
112         final String newAlternateId = ncmpServiceCmHandle.getAlternateId();
113         if (alternateIdChecker.canApplyAlternateId(ncmpServiceCmHandle.getCmHandleId(),
114             currentAlternateId, newAlternateId)) {
115             setAndUpdateAlternateId(yangModelCmHandle, newAlternateId);
116         }
117     }
118
119     private void processUpdates(final DataNode existingCmHandleDataNode, final NcmpServiceCmHandle incomingCmHandle) {
120         if (!incomingCmHandle.getPublicProperties().isEmpty()) {
121             updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY, incomingCmHandle.getPublicProperties());
122         }
123         if (!incomingCmHandle.getDmiProperties().isEmpty()) {
124             updateProperties(existingCmHandleDataNode, DMI_PROPERTY, incomingCmHandle.getDmiProperties());
125         }
126     }
127
128     private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
129             final Map<String, String> incomingProperties) {
130         final Collection<DataNode> replacementPropertyDataNodes =
131                 getReplacementDataNodes(existingCmHandleDataNode, propertyType, incomingProperties);
132         replacementPropertyDataNodes.addAll(
133                 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, incomingProperties));
134         if (replacementPropertyDataNodes.isEmpty()) {
135             removeAllProperties(existingCmHandleDataNode, propertyType);
136         } else {
137             inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
138         }
139     }
140
141     private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
142         existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
143             final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
144             if (matcher.find()) {
145                 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
146                 inventoryPersistence.deleteDataNode(dataNode.getXpath());
147             }
148         });
149     }
150
151     private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
152             final PropertyType propertyType, final Map<String, String> incomingProperties) {
153         final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
154         for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
155             final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
156             if (matcher.find()) {
157                 final String keyName = matcher.group(2);
158                 if (!incomingProperties.containsKey(keyName)) {
159                     unchangedPropertyDataNodes.add(existingPropertyDataNode);
160                 }
161             }
162         }
163         return unchangedPropertyDataNodes;
164     }
165
166     private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
167             final PropertyType propertyType, final Map<String, String> incomingProperties) {
168         final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
169         incomingProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
170             final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
171             if (updatedAttributeValue != null) {
172                 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
173                         updatedAttributeKey, updatedAttributeValue);
174                 replacementPropertyDataNodes.add(
175                         buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
176             }
177         });
178         return replacementPropertyDataNodes;
179     }
180
181     private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
182             final String attributeKey) {
183         return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
184     }
185
186     private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
187         final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
188         updatedLeaves.put("name", attributeKey);
189         updatedLeaves.put("value", attributeValue);
190         log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
191                 attributeValue);
192         return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
193     }
194
195     private void setAndUpdateAlternateId(final YangModelCmHandle upgradedCmHandle, final String alternateId) {
196         final Map<String, Map<String, String>> dmiRegistryProperties = new HashMap<>(1);
197         final Map<String, String> cmHandleProperties = new HashMap<>(2);
198         cmHandleProperties.put("id", upgradedCmHandle.getId());
199         cmHandleProperties.put("alternate-id", alternateId);
200         dmiRegistryProperties.put("cm-handles", cmHandleProperties);
201         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
202                 jsonObjectMapper.asJsonString(dmiRegistryProperties), OffsetDateTime.now());
203         log.info("Updating alternateId for cmHandle {} with value : {})", upgradedCmHandle.getId(), alternateId);
204     }
205
206     enum PropertyType {
207         DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
208
209         private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
210
211         final String xpathPrefix;
212         final Pattern propertyXpathPattern;
213
214         PropertyType(final String xpathPrefix) {
215             this.xpathPrefix = xpathPrefix;
216             this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);
217         }
218     }
219 }