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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.ncmp.api.impl;
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;
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;
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;
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 {
67 private final InventoryPersistence inventoryPersistence;
68 private final CpsDataService cpsDataService;
69 private final JsonObjectMapper jsonObjectMapper;
70 private final AlternateIdChecker alternateIdChecker;
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.
76 * @param ncmpServiceCmHandles collection of ncmpServiceCmHandles
78 public List<CmHandleRegistrationResponse> updateCmHandleProperties(
79 final Collection<NcmpServiceCmHandle> ncmpServiceCmHandles) {
80 final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>();
81 for (final NcmpServiceCmHandle ncmpServiceCmHandle : ncmpServiceCmHandles) {
82 final String cmHandleId = ncmpServiceCmHandle.getCmHandleId();
84 final DataNode existingCmHandleDataNode = inventoryPersistence
85 .getCmHandleDataNodeByCmHandleId(cmHandleId).iterator().next();
86 updateAlternateId(existingCmHandleDataNode, ncmpServiceCmHandle);
87 processUpdates(existingCmHandleDataNode, ncmpServiceCmHandle);
88 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
89 } catch (final DataNodeNotFoundException e) {
90 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId, e.getMessage());
91 cmHandleRegistrationResponses.add(
92 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
93 } catch (final DataValidationException e) {
94 log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
95 cmHandleRegistrationResponses.add(
96 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
97 } catch (final Exception exception) {
98 log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
99 cmHandleRegistrationResponses.add(
100 CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
103 return cmHandleRegistrationResponses;
106 private void updateAlternateId(final DataNode existingCmHandleDataNode,
107 final NcmpServiceCmHandle ncmpServiceCmHandle) {
108 final YangModelCmHandle yangModelCmHandle =
109 YangDataConverter.convertCmHandleToYangModel(existingCmHandleDataNode,
110 ncmpServiceCmHandle.getCmHandleId());
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);
119 private void processUpdates(final DataNode existingCmHandleDataNode, final NcmpServiceCmHandle incomingCmHandle) {
120 if (!incomingCmHandle.getPublicProperties().isEmpty()) {
121 updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY, incomingCmHandle.getPublicProperties());
123 if (!incomingCmHandle.getDmiProperties().isEmpty()) {
124 updateProperties(existingCmHandleDataNode, DMI_PROPERTY, incomingCmHandle.getDmiProperties());
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);
137 inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
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());
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);
163 return unchangedPropertyDataNodes;
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));
178 return replacementPropertyDataNodes;
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);
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,
192 return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
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);
207 DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
209 private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
211 final String xpathPrefix;
212 final Pattern propertyXpathPattern;
214 PropertyType(final String xpathPrefix) {
215 this.xpathPrefix = xpathPrefix;
216 this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);