657b0b4740bf05363d3899141c1114afa1f52cc6
[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-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.operations;
22
23 import static org.onap.cps.ncmp.api.impl.operations.RequiredDmiService.MODEL;
24
25 import com.google.gson.JsonArray;
26 import com.google.gson.JsonObject;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import org.onap.cps.ncmp.api.impl.client.DmiRestClient;
32 import org.onap.cps.ncmp.api.impl.config.NcmpConfiguration;
33 import org.onap.cps.ncmp.api.models.PersistenceCmHandle;
34 import org.onap.cps.ncmp.api.models.YangResource;
35 import org.onap.cps.spi.model.ModuleReference;
36 import org.onap.cps.utils.JsonObjectMapper;
37 import org.springframework.http.HttpHeaders;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.stereotype.Component;
40
41 /**
42  * Operations class for DMI Model.
43  */
44 @Component
45 public class DmiModelOperations extends DmiOperations {
46
47     /**
48      * Constructor for {@code DmiOperations}. This method also manipulates url properties.
49      *
50      * @param dmiRestClient {@code DmiRestClient}
51      */
52     public DmiModelOperations(final PersistenceCmHandleRetriever dmiPropertiesRetriever,
53                               final JsonObjectMapper jsonObjectMapper,
54                               final NcmpConfiguration.DmiProperties dmiProperties,
55                               final DmiRestClient dmiRestClient) {
56         super(dmiPropertiesRetriever, jsonObjectMapper, dmiProperties, dmiRestClient);
57     }
58
59     /**
60      * Retrieves module references.
61      *
62      * @param persistenceCmHandle the persistence cm handle
63      * @return module references
64      */
65     public List<ModuleReference> getModuleReferences(final PersistenceCmHandle persistenceCmHandle) {
66         final DmiRequestBody dmiRequestBody = DmiRequestBody.builder()
67             .build();
68         dmiRequestBody.asDmiProperties(persistenceCmHandle.getDmiProperties());
69         final ResponseEntity<Object> dmiFetchModulesResponseEntity = getResourceFromDmiWithJsonData(
70             persistenceCmHandle.resolveDmiServiceName(MODEL),
71                 jsonObjectMapper.asJsonString(dmiRequestBody), persistenceCmHandle.getId(), "modules");
72         return toModuleReferences((Map) dmiFetchModulesResponseEntity.getBody());
73     }
74
75     /**
76      * Retrieve yang resources from dmi for any modules that CPS-NCMP hasn't cached before.
77      *
78      * @param persistenceCmHandle the persistenceCmHandle
79      * @param unknownModuleReferences the unknown module references
80      * @return yang resources as map of module name to yang(re)source
81      */
82     public Map<String, String> getNewYangResourcesFromDmi(final PersistenceCmHandle persistenceCmHandle,
83                                                           final List<ModuleReference> unknownModuleReferences) {
84         final String jsonWithDataAndDmiProperties = getRequestBodyToFetchYangResources(
85             unknownModuleReferences, persistenceCmHandle.getDmiProperties());
86         final ResponseEntity<Object> responseEntity = getResourceFromDmiWithJsonData(
87             persistenceCmHandle.resolveDmiServiceName(MODEL),
88             jsonWithDataAndDmiProperties,
89             persistenceCmHandle.getId(),
90             "moduleResources");
91         return asModuleNameToYangResourceMap(responseEntity);
92     }
93
94     /**
95      * Get resources from DMI for modules.
96      *
97      * @param dmiServiceName dmi service name
98      * @param jsonData module names and revisions as JSON
99      * @param cmHandle cmHandle
100      * @param resourceName name of the resource(s)
101      * @return {@code ResponseEntity} response entity
102      */
103     private ResponseEntity<Object> getResourceFromDmiWithJsonData(final String dmiServiceName,
104                                                                   final String jsonData,
105                                                                   final String cmHandle,
106                                                                   final String resourceName) {
107         final String dmiResourceDataUrl = getDmiResourceUrl(dmiServiceName, cmHandle, resourceName);
108         return dmiRestClient.postOperationWithJsonData(dmiResourceDataUrl, jsonData, new HttpHeaders());
109     }
110
111     private static String getRequestBodyToFetchYangResources(final List<ModuleReference> unknownModuleReferences,
112         final List<PersistenceCmHandle.Property> dmiProperties) {
113         final JsonArray moduleReferencesAsJson = getModuleReferencesAsJson(unknownModuleReferences);
114         final JsonObject data = new JsonObject();
115         data.add("modules", moduleReferencesAsJson);
116         final JsonObject jsonRequestObject = new JsonObject();
117         jsonRequestObject.add("data", data);
118         jsonRequestObject.add("cmHandleProperties", toJsonObject(dmiProperties));
119         return jsonRequestObject.toString();
120     }
121
122     private static JsonArray getModuleReferencesAsJson(final List<ModuleReference> unknownModuleReferences) {
123         final JsonArray moduleReferences = new JsonArray();
124
125         for (final ModuleReference moduleReference : unknownModuleReferences) {
126             final JsonObject moduleReferenceAsJson = new JsonObject();
127             moduleReferenceAsJson.addProperty("name", moduleReference.getModuleName());
128             moduleReferenceAsJson.addProperty("revision", moduleReference.getRevision());
129             moduleReferences.add(moduleReferenceAsJson);
130         }
131         return moduleReferences;
132     }
133
134     private static JsonObject toJsonObject(final List<PersistenceCmHandle.Property>
135                                                dmiProperties) {
136         final JsonObject asJsonObject = new JsonObject();
137         for (final PersistenceCmHandle.Property additionalProperty : dmiProperties) {
138             asJsonObject.addProperty(additionalProperty.getName(), additionalProperty.getValue());
139         }
140         return asJsonObject;
141     }
142
143     private List<ModuleReference> toModuleReferences(final Map<String, Object> dmiFetchModulesResponseAsMap) {
144         final List<ModuleReference> moduleReferences = new ArrayList<>();
145
146         if (dmiFetchModulesResponseAsMap != null) {
147             final List<Object> moduleReferencesAsList = (List) dmiFetchModulesResponseAsMap.get("schemas");
148             if (moduleReferencesAsList != null) {
149                 moduleReferencesAsList.forEach(moduleReferenceAsMap -> {
150                     final ModuleReference moduleReference =
151                             jsonObjectMapper.convertToValueType(moduleReferenceAsMap, ModuleReference.class);
152                     moduleReferences.add(moduleReference);
153                 });
154             }
155         }
156         return moduleReferences;
157     }
158
159     private Map<String, String> asModuleNameToYangResourceMap(final ResponseEntity<Object> responseEntity) {
160         final Map<String, String> yangResourcesModuleNameToContentMap = new HashMap<>();
161         final List<Map<String, String>> yangResourcesAsList = (List) responseEntity.getBody();
162
163         if (yangResourcesAsList != null) {
164             yangResourcesAsList.forEach(yangResourceAsMap -> {
165                 final YangResource yangResource =
166                         jsonObjectMapper.convertToValueType(yangResourceAsMap, YangResource.class);
167                 yangResourcesModuleNameToContentMap.put(yangResource.getModuleName(),
168                     yangResource.getYangSource());
169             });
170         }
171         return yangResourcesModuleNameToContentMap;
172     }
173 }