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