CPS-2182 - #4 Add module Set tag to NCMPs DMI Batch Data interface
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / operations / DmiModelOperations.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.impl.operations;
23
24 import static org.onap.cps.ncmp.api.impl.operations.RequiredDmiService.MODEL;
25
26 import com.google.gson.JsonArray;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonObject;
29 import com.google.gson.JsonParser;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import org.onap.cps.ncmp.api.impl.client.DmiRestClient;
37 import org.onap.cps.ncmp.api.impl.config.DmiWebClientConfiguration.DmiProperties;
38 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
39 import org.onap.cps.ncmp.api.impl.utils.DmiServiceUrlBuilder;
40 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
41 import org.onap.cps.ncmp.api.models.YangResource;
42 import org.onap.cps.spi.model.ModuleReference;
43 import org.onap.cps.utils.JsonObjectMapper;
44 import org.springframework.http.ResponseEntity;
45 import org.springframework.stereotype.Component;
46
47 /**
48  * Operations class for DMI Model.
49  */
50 @Component
51 public class DmiModelOperations extends DmiOperations {
52
53     /**
54      * Constructor for {@code DmiOperations}. This method also manipulates url properties.
55      *
56      * @param dmiRestClient {@code DmiRestClient}
57      */
58     public DmiModelOperations(final InventoryPersistence inventoryPersistence,
59                               final JsonObjectMapper jsonObjectMapper,
60                               final DmiProperties dmiProperties,
61                               final DmiRestClient dmiRestClient, final DmiServiceUrlBuilder dmiServiceUrlBuilder) {
62         super(inventoryPersistence, jsonObjectMapper, dmiProperties, dmiRestClient, dmiServiceUrlBuilder);
63     }
64
65     /**
66      * Retrieves module references.
67      *
68      * @param yangModelCmHandle the yang model cm handle
69      * @return module references
70      */
71     public List<ModuleReference> getModuleReferences(final YangModelCmHandle yangModelCmHandle) {
72         final DmiRequestBody dmiRequestBody = DmiRequestBody.builder()
73                 .moduleSetTag(yangModelCmHandle.getModuleSetTag()).build();
74         dmiRequestBody.asDmiProperties(yangModelCmHandle.getDmiProperties());
75         final ResponseEntity<Object> dmiFetchModulesResponseEntity = getResourceFromDmiWithJsonData(
76             yangModelCmHandle.resolveDmiServiceName(MODEL),
77                 jsonObjectMapper.asJsonString(dmiRequestBody), yangModelCmHandle.getId(), "modules");
78         return toModuleReferences((Map) dmiFetchModulesResponseEntity.getBody());
79     }
80
81     /**
82      * Retrieve yang resources from dmi for any modules that CPS-NCMP hasn't cached before.
83      *
84      * @param yangModelCmHandle the yangModelCmHandle
85      * @param newModuleReferences the unknown module references
86      * @return yang resources as map of module name to yang(re)source
87      */
88     public Map<String, String> getNewYangResourcesFromDmi(final YangModelCmHandle yangModelCmHandle,
89                                                           final Collection<ModuleReference> newModuleReferences) {
90         if (newModuleReferences.isEmpty()) {
91             return Collections.emptyMap();
92         }
93         final String jsonWithDataAndDmiProperties = getRequestBodyToFetchYangResources(newModuleReferences,
94                 yangModelCmHandle.getDmiProperties(), yangModelCmHandle.getModuleSetTag());
95         final ResponseEntity<Object> responseEntity = getResourceFromDmiWithJsonData(
96             yangModelCmHandle.resolveDmiServiceName(MODEL),
97             jsonWithDataAndDmiProperties,
98             yangModelCmHandle.getId(),
99             "moduleResources");
100         return asModuleNameToYangResourceMap(responseEntity);
101     }
102
103     /**
104      * Get resources from DMI for modules.
105      *
106      * @param dmiServiceName dmi service name
107      * @param jsonRequestBody module names and revisions as JSON
108      * @param cmHandle cmHandle
109      * @param resourceName name of the resource(s)
110      * @return {@code ResponseEntity} response entity
111      */
112     private ResponseEntity<Object> getResourceFromDmiWithJsonData(final String dmiServiceName,
113                                                                   final String jsonRequestBody,
114                                                                   final String cmHandle,
115                                                                   final String resourceName) {
116         final String dmiResourceDataUrl = getDmiResourceUrl(dmiServiceName, cmHandle, resourceName);
117         return dmiRestClient.postOperationWithJsonData(dmiResourceDataUrl, jsonRequestBody,
118                 OperationType.READ, null);
119     }
120
121     private static String getRequestBodyToFetchYangResources(final Collection<ModuleReference> newModuleReferences,
122                                                              final List<YangModelCmHandle.Property> dmiProperties,
123                                                              final String moduleSetTag) {
124         final JsonArray moduleReferencesAsJson = getModuleReferencesAsJson(newModuleReferences);
125         final JsonObject data = new JsonObject();
126         data.add("modules", moduleReferencesAsJson);
127         final JsonObject jsonRequestObject = new JsonObject();
128         if (!moduleSetTag.isEmpty()) {
129             final JsonElement moduleSetTagAsJson = JsonParser.parseString(moduleSetTag);
130             jsonRequestObject.add("moduleSetTag", moduleSetTagAsJson);
131         }
132         jsonRequestObject.add("data", data);
133         jsonRequestObject.add("cmHandleProperties", toJsonObject(dmiProperties));
134         return jsonRequestObject.toString();
135     }
136
137     private static JsonArray getModuleReferencesAsJson(final Collection<ModuleReference> unknownModuleReferences) {
138         final JsonArray moduleReferences = new JsonArray();
139
140         for (final ModuleReference moduleReference : unknownModuleReferences) {
141             final JsonObject moduleReferenceAsJson = new JsonObject();
142             moduleReferenceAsJson.addProperty("name", moduleReference.getModuleName());
143             moduleReferenceAsJson.addProperty("revision", moduleReference.getRevision());
144             moduleReferences.add(moduleReferenceAsJson);
145         }
146         return moduleReferences;
147     }
148
149     private static JsonObject toJsonObject(final List<YangModelCmHandle.Property>
150                                                dmiProperties) {
151         final JsonObject asJsonObject = new JsonObject();
152         for (final YangModelCmHandle.Property additionalProperty : dmiProperties) {
153             asJsonObject.addProperty(additionalProperty.getName(), additionalProperty.getValue());
154         }
155         return asJsonObject;
156     }
157
158     private List<ModuleReference> toModuleReferences(final Map<String, Object> dmiFetchModulesResponseAsMap) {
159         final List<ModuleReference> moduleReferences = new ArrayList<>();
160
161         if (dmiFetchModulesResponseAsMap != null) {
162             final List<Object> moduleReferencesAsList = (List) dmiFetchModulesResponseAsMap.get("schemas");
163             if (moduleReferencesAsList != null) {
164                 moduleReferencesAsList.forEach(moduleReferenceAsMap -> {
165                     final ModuleReference moduleReference =
166                             jsonObjectMapper.convertToValueType(moduleReferenceAsMap, ModuleReference.class);
167                     moduleReferences.add(moduleReference);
168                 });
169             }
170         }
171         return moduleReferences;
172     }
173
174     private Map<String, String> asModuleNameToYangResourceMap(final ResponseEntity<Object> responseEntity) {
175         final Map<String, String> yangResourcesModuleNameToContentMap = new HashMap<>();
176         final List<Map<String, String>> yangResourcesAsList = (List) responseEntity.getBody();
177
178         if (yangResourcesAsList != null) {
179             yangResourcesAsList.forEach(yangResourceAsMap -> {
180                 final YangResource yangResource =
181                         jsonObjectMapper.convertToValueType(yangResourceAsMap, YangResource.class);
182                 yangResourcesModuleNameToContentMap.put(yangResource.getModuleName(),
183                     yangResource.getYangSource());
184             });
185         }
186         return yangResourcesModuleNameToContentMap;
187     }
188 }