b67ae0c19e82017f38ac0f6e268ecdf69de13017
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / NetworkCmProxyCmHandlerQueryServiceImpl.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.impl;
22
23 import static org.onap.cps.ncmp.api.impl.utils.RestQueryParametersValidator.validateCpsPathConditionProperties;
24 import static org.onap.cps.ncmp.api.impl.utils.RestQueryParametersValidator.validateModuleNameConditionProperties;
25 import static org.onap.cps.ncmp.api.impl.utils.YangDataConverter.convertYangModelCmHandleToNcmpServiceCmHandle;
26 import static org.onap.cps.spi.FetchDescendantsOption.FETCH_DIRECT_CHILDREN_ONLY;
27 import static org.onap.cps.spi.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS;
28
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.function.Function;
38 import java.util.stream.Collectors;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.onap.cps.cpspath.parser.PathParsingException;
42 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandlerQueryService;
43 import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
44 import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
45 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
46 import org.onap.cps.ncmp.api.inventory.CmHandleQueries;
47 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
48 import org.onap.cps.ncmp.api.inventory.enums.PropertyType;
49 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
50 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
51 import org.onap.cps.spi.exceptions.DataValidationException;
52 import org.onap.cps.spi.model.ConditionProperties;
53 import org.onap.cps.spi.model.DataNode;
54 import org.springframework.stereotype.Service;
55
56 @Service
57 @Slf4j
58 @RequiredArgsConstructor
59 public class NetworkCmProxyCmHandlerQueryServiceImpl implements NetworkCmProxyCmHandlerQueryService {
60
61     private static final Map<String, NcmpServiceCmHandle> NO_QUERY_TO_EXECUTE = null;
62     private final CmHandleQueries cmHandleQueries;
63     private final InventoryPersistence inventoryPersistence;
64
65     /**
66      * Query and return cm handles that match the given query parameters.
67      *
68      * @param cmHandleQueryServiceParameters the cm handle query parameters
69      * @return collection of cm handles
70      */
71     @Override
72     public Set<NcmpServiceCmHandle> queryCmHandles(
73             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
74
75         if (cmHandleQueryServiceParameters.getCmHandleQueryParameters().isEmpty()) {
76             return getAllCmHandles();
77         }
78
79         final Map<String, NcmpServiceCmHandle> combinedQueryResult = executeInventoryQueries(
80                 cmHandleQueryServiceParameters);
81
82         return new HashSet<>(combineWithModuleNameQuery(cmHandleQueryServiceParameters, combinedQueryResult).values());
83     }
84
85     /**
86      * Query and return cm handles that match the given query parameters.
87      *
88      * @param cmHandleQueryServiceParameters the cm handle query parameters
89      * @return collection of cm handle ids
90      */
91     @Override
92     public Set<String> queryCmHandleIds(
93             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
94
95         if (cmHandleQueryServiceParameters.getCmHandleQueryParameters().isEmpty()) {
96             return getAllCmHandleIds();
97         }
98
99         final Map<String, NcmpServiceCmHandle> combinedQueryResult = executeInventoryQueries(
100                 cmHandleQueryServiceParameters);
101
102         final Collection<String> moduleNamesForQuery =
103                 getModuleNamesForQuery(cmHandleQueryServiceParameters.getCmHandleQueryParameters());
104         if (moduleNamesForQuery.isEmpty()) {
105             return combinedQueryResult.keySet();
106         }
107         final Set<String> moduleNameQueryResult =
108                 new HashSet<>(inventoryPersistence.getCmHandleIdsWithGivenModules(moduleNamesForQuery));
109
110         if (combinedQueryResult == NO_QUERY_TO_EXECUTE) {
111             return moduleNameQueryResult;
112         }
113
114         moduleNameQueryResult.retainAll(combinedQueryResult.keySet());
115         return moduleNameQueryResult;
116     }
117
118     @Override
119     public Set<String> queryCmHandleIdsForInventory(
120             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
121
122         if (cmHandleQueryServiceParameters.getCmHandleQueryParameters().isEmpty()) {
123             return getAllCmHandleIds();
124         }
125
126         final Map<String, NcmpServiceCmHandle> publicPropertiesQueryResult = queryCmHandlesByPublicProperties(
127                 cmHandleQueryServiceParameters);
128         if (publicPropertiesQueryResult != null && publicPropertiesQueryResult.isEmpty()) {
129             return Collections.emptySet();
130         }
131
132         final Map<String, NcmpServiceCmHandle> privatePropertiesQueryResult = queryCmHandlesByPrivateProperties(
133                 cmHandleQueryServiceParameters);
134         if (privatePropertiesQueryResult != null && privatePropertiesQueryResult.isEmpty()) {
135             return Collections.emptySet();
136         }
137
138         final Map<String, NcmpServiceCmHandle> dmiPropertiesQueryResult = queryCmHandlesByDmiPlugin(
139                 cmHandleQueryServiceParameters);
140         if (dmiPropertiesQueryResult != null && dmiPropertiesQueryResult.isEmpty()) {
141             return Collections.emptySet();
142         }
143
144         final Map<String, NcmpServiceCmHandle> combinedResult =
145               combineQueryResults(publicPropertiesQueryResult, privatePropertiesQueryResult, dmiPropertiesQueryResult);
146
147         return combinedResult.keySet();
148     }
149
150     private Map<String, NcmpServiceCmHandle> queryCmHandlesByDmiPlugin(
151             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
152         final Map<String, String> dmiPropertyQueryPairs =
153                 getPropertyPairs(cmHandleQueryServiceParameters.getCmHandleQueryParameters(),
154                         InventoryQueryConditions.CM_HANDLE_WITH_DMI_PLUGIN.getName());
155         if (dmiPropertyQueryPairs.isEmpty()) {
156             return NO_QUERY_TO_EXECUTE;
157         }
158
159         final String dmiPluginIdentifierValue = dmiPropertyQueryPairs.get(
160                 PropertyType.DMI_PLUGIN.getYangContainerName());
161
162         final Set<NcmpServiceCmHandle> cmHandlesByDmiPluginIdentifier = cmHandleQueries
163                 .getCmHandlesByDmiPluginIdentifier(dmiPluginIdentifierValue);
164
165         return cmHandlesByDmiPluginIdentifier.stream()
166                 .collect(Collectors.toMap(NcmpServiceCmHandle::getCmHandleId, cmH -> cmH));
167     }
168
169     private Map<String, NcmpServiceCmHandle> queryCmHandlesByPrivateProperties(
170             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
171
172         final Map<String, String> privatePropertyQueryPairs =
173                 getPropertyPairs(cmHandleQueryServiceParameters.getCmHandleQueryParameters(),
174                         InventoryQueryConditions.HAS_ALL_ADDITIONAL_PROPERTIES.getName());
175
176         return privatePropertyQueryPairs.isEmpty()
177                 ? NO_QUERY_TO_EXECUTE
178                 : cmHandleQueries.queryCmHandleAdditionalProperties(privatePropertyQueryPairs);
179     }
180
181     private Map<String, NcmpServiceCmHandle> queryCmHandlesByPublicProperties(
182             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
183
184         final Map<String, String> publicPropertyQueryPairs =
185                 getPropertyPairs(cmHandleQueryServiceParameters.getCmHandleQueryParameters(),
186                         CmHandleQueryConditions.HAS_ALL_PROPERTIES.getConditionName());
187
188         return publicPropertyQueryPairs.isEmpty()
189                 ? NO_QUERY_TO_EXECUTE
190                 : cmHandleQueries.queryCmHandlePublicProperties(publicPropertyQueryPairs);
191     }
192
193     private Map<String, NcmpServiceCmHandle> combineQueryResults(
194             final Map<String, NcmpServiceCmHandle> publicPropertiesQueryResult,
195             final Map<String, NcmpServiceCmHandle> privatePropertiesQueryResult,
196             final Map<String, NcmpServiceCmHandle> dmiPropertiesQueryResult) {
197
198         final Map<String, NcmpServiceCmHandle> propertiesCombinedResult = cmHandleQueries
199                 .combineCmHandleQueries(publicPropertiesQueryResult, privatePropertiesQueryResult);
200         return cmHandleQueries
201                 .combineCmHandleQueries(propertiesCombinedResult, dmiPropertiesQueryResult);
202     }
203
204     private Map<String, NcmpServiceCmHandle> combineWithModuleNameQuery(
205             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters,
206             final Map<String, NcmpServiceCmHandle> previousQueryResult) {
207         final Collection<String> moduleNamesForQuery =
208                 getModuleNamesForQuery(cmHandleQueryServiceParameters.getCmHandleQueryParameters());
209         if (moduleNamesForQuery.isEmpty()) {
210             return previousQueryResult;
211         }
212         final Collection<String> cmHandleIdsByModuleName =
213                 inventoryPersistence.getCmHandleIdsWithGivenModules(moduleNamesForQuery);
214         if (cmHandleIdsByModuleName.isEmpty()) {
215             return Collections.emptyMap();
216         }
217         final Map<String, NcmpServiceCmHandle> queryResult = new HashMap<>(cmHandleIdsByModuleName.size());
218         if (previousQueryResult == NO_QUERY_TO_EXECUTE) {
219             cmHandleIdsByModuleName.forEach(cmHandleId ->
220                     queryResult.put(cmHandleId, createNcmpServiceCmHandle(
221                             inventoryPersistence.getDataNode("/dmi-registry/cm-handles[@id='" + cmHandleId + "']")))
222             );
223             return queryResult;
224         }
225         previousQueryResult.keySet().retainAll(cmHandleIdsByModuleName);
226         queryResult.putAll(previousQueryResult);
227         return queryResult;
228     }
229
230     private Map<String, NcmpServiceCmHandle> executeInventoryQueries(
231             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
232         final Map<String, String> cpsPath = getCpsPath(cmHandleQueryServiceParameters.getCmHandleQueryParameters());
233         if (!validateCpsPathConditionProperties(cpsPath)) {
234             return Collections.emptyMap();
235         }
236         final Map<String, NcmpServiceCmHandle> cpsPathQueryResult;
237         if (cpsPath.isEmpty()) {
238             cpsPathQueryResult = NO_QUERY_TO_EXECUTE;
239         } else {
240             try {
241                 cpsPathQueryResult = cmHandleQueries.queryCmHandleDataNodesByCpsPath(
242                                 cpsPath.get("cpsPath"), INCLUDE_ALL_DESCENDANTS)
243                         .stream().map(this::createNcmpServiceCmHandle)
244                         .collect(Collectors.toMap(NcmpServiceCmHandle::getCmHandleId,
245                                 Function.identity()));
246             } catch (final PathParsingException pathParsingException) {
247                 throw new DataValidationException(pathParsingException.getMessage(), pathParsingException.getDetails(),
248                         pathParsingException);
249             }
250             if (cpsPathQueryResult.isEmpty()) {
251                 return Collections.emptyMap();
252             }
253         }
254
255         final Map<String, String> publicPropertyQueryPairs =
256                 getPropertyPairs(cmHandleQueryServiceParameters.getCmHandleQueryParameters(),
257                         CmHandleQueryConditions.HAS_ALL_PROPERTIES.getConditionName());
258         final Map<String, NcmpServiceCmHandle> propertiesQueryResult = publicPropertyQueryPairs.isEmpty()
259                 ? NO_QUERY_TO_EXECUTE : cmHandleQueries.queryCmHandlePublicProperties(publicPropertyQueryPairs);
260
261         return cmHandleQueries.combineCmHandleQueries(cpsPathQueryResult, propertiesQueryResult);
262     }
263
264     private Collection<String> getModuleNamesForQuery(final List<ConditionProperties> conditionProperties) {
265         final List<String> result = new ArrayList<>();
266         getConditions(conditionProperties, CmHandleQueryConditions.HAS_ALL_MODULES.getConditionName())
267             .parallelStream().forEach(
268                 conditionProperty -> {
269                     validateModuleNameConditionProperties(conditionProperty);
270                     result.add(conditionProperty.get("moduleName"));
271                 }
272             );
273         return result;
274     }
275
276     private Map<String, String> getCpsPath(final List<ConditionProperties> conditionProperties) {
277         final Map<String, String> result = new HashMap<>();
278         getConditions(conditionProperties, CmHandleQueryConditions.WITH_CPS_PATH.getConditionName()).forEach(
279                 result::putAll);
280         return result;
281     }
282
283     private Map<String, String> getPropertyPairs(final List<ConditionProperties> conditionProperties,
284                                                        final String queryProperty) {
285         final Map<String, String> result = new HashMap<>();
286         getConditions(conditionProperties, queryProperty).forEach(result::putAll);
287         return result;
288     }
289
290     private List<Map<String, String>> getConditions(final List<ConditionProperties> conditionProperties,
291                                                     final String name) {
292         for (final ConditionProperties conditionProperty : conditionProperties) {
293             if (conditionProperty.getConditionName().equals(name)) {
294                 return conditionProperty.getConditionParameters();
295             }
296         }
297         return Collections.emptyList();
298     }
299
300     private Set<NcmpServiceCmHandle> getAllCmHandles() {
301         return inventoryPersistence.getDataNode("/dmi-registry")
302                 .getChildDataNodes().stream().map(this::createNcmpServiceCmHandle).collect(Collectors.toSet());
303     }
304
305     private Set<String> getAllCmHandleIds() {
306         return inventoryPersistence.getDataNode("/dmi-registry", FETCH_DIRECT_CHILDREN_ONLY)
307                 .getChildDataNodes().stream().map(dataNode -> dataNode.getLeaves().get("id").toString())
308                 .collect(Collectors.toSet());
309     }
310
311     private NcmpServiceCmHandle createNcmpServiceCmHandle(final DataNode dataNode) {
312         return convertYangModelCmHandleToNcmpServiceCmHandle(YangDataConverter
313                 .convertCmHandleToYangModel(dataNode, dataNode.getLeaves().get("id").toString()));
314     }
315 }