fe47c0e2f25bec7992dfe9d95a5d76bdfec8c1b6
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  Modifications Copyright (C) 2024 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.impl.inventory;
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.impl.inventory.CmHandleRegistrationServicePropertyHandler.PropertyType.DMI_PROPERTY;
29 import static org.onap.cps.ncmp.impl.inventory.CmHandleRegistrationServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
30 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME;
31 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
32 import static org.onap.cps.ncmp.impl.inventory.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.utils.AlternateIdChecker;
49 import org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse;
50 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle;
51 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle;
52 import org.onap.cps.ncmp.impl.utils.YangDataConverter;
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.ContentType;
58 import org.onap.cps.utils.JsonObjectMapper;
59 import org.springframework.stereotype.Service;
60 import org.springframework.util.StringUtils;
61
62 @Slf4j
63 @Service
64 @RequiredArgsConstructor
65 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
66 @SuppressWarnings("squid:S5852")
67 public class CmHandleRegistrationServicePropertyHandler {
68
69     private final InventoryPersistence inventoryPersistence;
70     private final CpsDataService cpsDataService;
71     private final JsonObjectMapper jsonObjectMapper;
72     private final AlternateIdChecker alternateIdChecker;
73
74     /**
75      * Iterates over incoming updatedNcmpServiceCmHandles and update the dataNodes based on the updated attributes.
76      * The attributes which are not passed will remain as is.
77      *
78      * @param updatedNcmpServiceCmHandles collection of CmHandles
79      */
80     public List<CmHandleRegistrationResponse> updateCmHandleProperties(
81             final Collection<NcmpServiceCmHandle> updatedNcmpServiceCmHandles) {
82         final Collection<String> rejectedCmHandleIds = alternateIdChecker
83             .getIdsOfCmHandlesWithRejectedAlternateId(updatedNcmpServiceCmHandles, AlternateIdChecker.Operation.UPDATE);
84         final List<CmHandleRegistrationResponse> failureResponses =
85             CmHandleRegistrationResponse.createFailureResponses(rejectedCmHandleIds, ALTERNATE_ID_ALREADY_ASSOCIATED);
86         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>(failureResponses);
87         for (final NcmpServiceCmHandle updatedNcmpServiceCmHandle : updatedNcmpServiceCmHandles) {
88             final String cmHandleId = updatedNcmpServiceCmHandle.getCmHandleId();
89             if (!rejectedCmHandleIds.contains(cmHandleId)) {
90                 try {
91                     final DataNode existingCmHandleDataNode = inventoryPersistence
92                             .getCmHandleDataNodeByCmHandleId(cmHandleId).iterator().next();
93                     processUpdates(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
94                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
95                 } catch (final DataNodeNotFoundException e) {
96                     log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId,
97                             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         }
111         return cmHandleRegistrationResponses;
112     }
113
114     private void processUpdates(final DataNode existingCmHandleDataNode,
115                                 final NcmpServiceCmHandle updatedNcmpServiceCmHandle) {
116         setAndUpdateCmHandleField(
117             updatedNcmpServiceCmHandle.getCmHandleId(), "alternate-id", updatedNcmpServiceCmHandle.getAlternateId());
118         updateDataProducerIdentifier(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
119         if (!updatedNcmpServiceCmHandle.getPublicProperties().isEmpty()) {
120             updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY,
121                 updatedNcmpServiceCmHandle.getPublicProperties());
122         }
123         if (!updatedNcmpServiceCmHandle.getDmiProperties().isEmpty()) {
124             updateProperties(existingCmHandleDataNode, DMI_PROPERTY, updatedNcmpServiceCmHandle.getDmiProperties());
125         }
126     }
127
128     private void updateDataProducerIdentifier(final DataNode cmHandleDataNode,
129                                               final NcmpServiceCmHandle ncmpServiceCmHandle) {
130         final String newDataProducerIdentifier = ncmpServiceCmHandle.getDataProducerIdentifier();
131         if (StringUtils.hasText(newDataProducerIdentifier)) {
132             final YangModelCmHandle yangModelCmHandle = YangDataConverter.toYangModelCmHandle(cmHandleDataNode);
133             final String existingDataProducerIdentifier = yangModelCmHandle.getDataProducerIdentifier();
134             if (StringUtils.hasText(existingDataProducerIdentifier)) {
135                 if (!existingDataProducerIdentifier.equals(newDataProducerIdentifier)) {
136                     log.warn("Unable to update dataProducerIdentifier for cmHandle {}. "
137                             + "Value for dataProducerIdentifier has been set previously.",
138                         ncmpServiceCmHandle.getCmHandleId());
139                 } else {
140                     log.debug("dataProducerIdentifier for cmHandle {} is already set to {}.",
141                         ncmpServiceCmHandle.getCmHandleId(), newDataProducerIdentifier);
142                 }
143             } else {
144                 setAndUpdateCmHandleField(
145                     yangModelCmHandle.getId(), "data-producer-identifier", newDataProducerIdentifier);
146             }
147         }
148     }
149
150     private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
151                                   final Map<String, String> updatedProperties) {
152         final Collection<DataNode> replacementPropertyDataNodes =
153                 getReplacementDataNodes(existingCmHandleDataNode, propertyType, updatedProperties);
154         replacementPropertyDataNodes.addAll(
155                 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, updatedProperties));
156         if (replacementPropertyDataNodes.isEmpty()) {
157             removeAllProperties(existingCmHandleDataNode, propertyType);
158         } else {
159             inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
160         }
161     }
162
163     private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
164         existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
165             final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
166             if (matcher.find()) {
167                 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
168                 inventoryPersistence.deleteDataNode(dataNode.getXpath());
169             }
170         });
171     }
172
173     private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
174                                                                final PropertyType propertyType,
175                                                                final Map<String, String> updatedProperties) {
176         final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
177         for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
178             final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
179             if (matcher.find()) {
180                 final String keyName = matcher.group(2);
181                 if (!updatedProperties.containsKey(keyName)) {
182                     unchangedPropertyDataNodes.add(existingPropertyDataNode);
183                 }
184             }
185         }
186         return unchangedPropertyDataNodes;
187     }
188
189     private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
190                                                          final PropertyType propertyType,
191                                                          final Map<String, String> updatedProperties) {
192         final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
193         updatedProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
194             final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
195             if (updatedAttributeValue != null) {
196                 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
197                         updatedAttributeKey, updatedAttributeValue);
198                 replacementPropertyDataNodes.add(
199                         buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
200             }
201         });
202         return replacementPropertyDataNodes;
203     }
204
205     private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
206                                      final String attributeKey) {
207         return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
208     }
209
210     private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
211         final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
212         updatedLeaves.put("name", attributeKey);
213         updatedLeaves.put("value", attributeValue);
214         log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
215                 attributeValue);
216         return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
217     }
218
219     private void setAndUpdateCmHandleField(final String cmHandleIdToUpdate, final String fieldName,
220                                            final String newFieldValue) {
221         final Map<String, Map<String, String>> dmiRegistryData = new HashMap<>(1);
222         final Map<String, String> cmHandleData = new HashMap<>(2);
223         cmHandleData.put("id", cmHandleIdToUpdate);
224         cmHandleData.put(fieldName, newFieldValue);
225         dmiRegistryData.put("cm-handles", cmHandleData);
226         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
227                 jsonObjectMapper.asJsonString(dmiRegistryData), OffsetDateTime.now(), ContentType.JSON);
228         log.debug("Updating {} for cmHandle {} with value : {})", fieldName, cmHandleIdToUpdate, newFieldValue);
229     }
230
231     enum PropertyType {
232         DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
233
234         private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
235
236         final String xpathPrefix;
237         final Pattern propertyXpathPattern;
238
239         PropertyType(final String xpathPrefix) {
240             this.xpathPrefix = xpathPrefix;
241             this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);
242         }
243     }
244 }