c57cf0ecb0d2828201f9a4e9e475a82d0215f9ea
[cps.git] / dmi-plugin-demo-and-csit-stub / dmi-plugin-demo-and-csit-stub-service / src / main / java / org / onap / cps / ncmp / dmi / rest / stub / controller / DmiRestStubController.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2024 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.dmi.rest.stub.controller;
22
23 import static org.onap.cps.ncmp.api.NcmpResponseStatus.SUCCESS;
24
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import io.cloudevents.CloudEvent;
28 import io.cloudevents.core.builder.CloudEventBuilder;
29 import java.net.URI;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.UUID;
35 import lombok.RequiredArgsConstructor;
36 import lombok.extern.slf4j.Slf4j;
37 import org.json.simple.parser.JSONParser;
38 import org.json.simple.parser.ParseException;
39 import org.onap.cps.ncmp.api.impl.utils.EventDateTimeFormatter;
40 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.CmHandle;
41 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DataOperationRequest;
42 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DmiDataOperationRequest;
43 import org.onap.cps.ncmp.dmi.rest.stub.utils.ResourceFileReaderUtil;
44 import org.onap.cps.ncmp.events.async1_0_0.Data;
45 import org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent;
46 import org.onap.cps.ncmp.events.async1_0_0.Response;
47 import org.springframework.beans.factory.annotation.Value;
48 import org.springframework.context.ApplicationContext;
49 import org.springframework.core.io.Resource;
50 import org.springframework.core.io.ResourceLoader;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.http.ResponseEntity;
53 import org.springframework.kafka.core.KafkaTemplate;
54 import org.springframework.web.bind.annotation.DeleteMapping;
55 import org.springframework.web.bind.annotation.GetMapping;
56 import org.springframework.web.bind.annotation.PathVariable;
57 import org.springframework.web.bind.annotation.PostMapping;
58 import org.springframework.web.bind.annotation.PutMapping;
59 import org.springframework.web.bind.annotation.RequestBody;
60 import org.springframework.web.bind.annotation.RequestHeader;
61 import org.springframework.web.bind.annotation.RequestMapping;
62 import org.springframework.web.bind.annotation.RequestParam;
63 import org.springframework.web.bind.annotation.RestController;
64
65 @RestController
66 @RequestMapping("${rest.api.dmi-stub-base-path}")
67 @RequiredArgsConstructor
68 @Slf4j
69 public class DmiRestStubController {
70
71     private static final String DEFAULT_TAG = "tagD";
72     private static final String dataOperationEventType = "org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent";
73     private static final Map<String, String> moduleSetTagPerCmHandleId = new HashMap<>();
74     private final KafkaTemplate<String, CloudEvent> cloudEventKafkaTemplate;
75     private final ObjectMapper objectMapper;
76     private final ApplicationContext applicationContext;
77     @Value("${app.ncmp.async-m2m.topic}")
78     private String ncmpAsyncM2mTopic;
79     @Value("${delay.module-references-delay-ms}")
80     private long moduleReferencesDelayMs;
81     @Value("${delay.module-resources-delay-ms}")
82     private long moduleResourcesDelayMs;
83     @Value("${delay.data-for-cm-handle-delay-ms}")
84     private long dataForCmHandleDelayMs;
85
86     /**
87      * This code defines a REST API endpoint for adding new the module set tag mapping. The endpoint receives the
88      * cmHandleId and moduleSetTag as request body and add into moduleSetTagPerCmHandleId map with the provided
89      * values.
90      *
91      * @param requestBody map of cmHandleId and moduleSetTag
92      * @return a ResponseEntity object containing the updated moduleSetTagPerCmHandleId map as the response body
93      */
94     @PostMapping("/v1/tagMapping")
95     public ResponseEntity<Map<String, String>> addTagForMapping(@RequestBody final Map<String, String> requestBody) {
96         moduleSetTagPerCmHandleId.putAll(requestBody);
97         return new ResponseEntity<>(requestBody, HttpStatus.CREATED);
98     }
99
100     /**
101      * This code defines a GET endpoint of  module set tag mapping.
102      *
103      * @return The map represents the module set tag mapping.
104      */
105     @GetMapping("/v1/tagMapping")
106     public ResponseEntity<Map<String, String>> getTagMapping() {
107         return ResponseEntity.ok(moduleSetTagPerCmHandleId);
108     }
109
110     /**
111      * This code defines a GET endpoint of  module set tag by cm handle ID.
112      *
113      * @return The map represents the module set tag mapping filtered by cm handle ID.
114      */
115     @GetMapping("/v1/tagMapping/ch/{cmHandleId}")
116     public ResponseEntity<String> getTagMappingByCmHandleId(@PathVariable final String cmHandleId) {
117         return ResponseEntity.ok(moduleSetTagPerCmHandleId.get(cmHandleId));
118     }
119
120     /**
121      * This code defines a REST API endpoint for updating the module set tag mapping. The endpoint receives the
122      * cmHandleId and moduleSetTag as request body and updates the moduleSetTagPerCmHandleId map with the provided
123      * values.
124      *
125      * @param requestBody map of cmHandleId and moduleSetTag
126      * @return a ResponseEntity object containing the updated moduleSetTagPerCmHandleId map as the response body
127      */
128
129     @PutMapping("/v1/tagMapping")
130     public ResponseEntity<Map<String, String>> updateTagMapping(@RequestBody final Map<String, String> requestBody) {
131         moduleSetTagPerCmHandleId.putAll(requestBody);
132         return ResponseEntity.noContent().build();
133     }
134
135     /**
136      * It contains a method to delete an entry from the moduleSetTagPerCmHandleId map.
137      * The method takes a cmHandleId as a parameter and removes the corresponding entry from the map.
138      *
139      * @return a ResponseEntity containing the updated map.
140      */
141     @DeleteMapping("/v1/tagMapping/ch/{cmHandleId}")
142     public ResponseEntity<String> deleteTagMappingByCmHandleId(@PathVariable final String cmHandleId) {
143         moduleSetTagPerCmHandleId.remove(cmHandleId);
144         return ResponseEntity.ok(String.format("Mapping of %s is deleted successfully", cmHandleId));
145     }
146
147     /**
148      * Get all modules for given cm handle.
149      *
150      * @param cmHandleId              The identifier for a network function, network element, subnetwork,
151      *                                or any other cm object by managed Network CM Proxy
152      * @param moduleReferencesRequest module references request body
153      * @return ResponseEntity response entity having module response as json string.
154      */
155     @PostMapping("/v1/ch/{cmHandleId}/modules")
156     public ResponseEntity<String> getModuleReferences(@PathVariable final String cmHandleId,
157                                                       @RequestBody final Object moduleReferencesRequest) {
158         delay(moduleReferencesDelayMs);
159         final String moduleResponseContent = getModuleResourceResponse(cmHandleId,
160                 "ModuleResponse.json");
161         log.info("cm handle: {} requested for modules", cmHandleId);
162         return ResponseEntity.ok(moduleResponseContent);
163     }
164
165     /**
166      * Retrieves module resources for a given cmHandleId.
167      *
168      * @param cmHandleId                 The identifier for a network function, network element, subnetwork,
169      *                                   or any other cm object by managed Network CM Proxy
170      * @param moduleResourcesReadRequest module resources read request body
171      * @return ResponseEntity response entity having module resources response as json string.
172      */
173     @PostMapping("/v1/ch/{cmHandleId}/moduleResources")
174     public ResponseEntity<String> retrieveModuleResources(
175             @PathVariable final String cmHandleId,
176             @RequestBody final Object moduleResourcesReadRequest) {
177         delay(moduleResourcesDelayMs);
178         final String moduleResourcesResponseContent = getModuleResourceResponse(cmHandleId,
179                 "ModuleResourcesResponse.json");
180         log.info("cm handle: {} requested for modules resources", cmHandleId);
181         return ResponseEntity.ok(moduleResourcesResponseContent);
182     }
183
184     /**
185      * Create resource data from passthrough operational or running for a cm handle.
186      *
187      * @param cmHandleId              The identifier for a network function, network element, subnetwork,
188      *                                or any other cm object by managed Network CM Proxy
189      * @param datastoreName           datastore name
190      * @param resourceIdentifier      resource identifier
191      * @param options                 options
192      * @param topic                   client given topic name
193      * @return (@ code ResponseEntity) response entity
194      */
195     @PostMapping("/v1/ch/{cmHandleId}/data/ds/{datastoreName}")
196     public ResponseEntity<String> getResourceDataForCmHandle(
197             @PathVariable("cmHandleId") final String cmHandleId,
198             @PathVariable("datastoreName") final String datastoreName,
199             @RequestParam(value = "resourceIdentifier") final String resourceIdentifier,
200             @RequestParam(value = "options", required = false) final String options,
201             @RequestParam(value = "topic", required = false) final String topic,
202             @RequestHeader(value = "Authorization", required = false) final String authorization) {
203         log.info("DMI AUTH HEADER: {}", authorization);
204         delay(dataForCmHandleDelayMs);
205         final String sampleJson = ResourceFileReaderUtil.getResourceFileContent(applicationContext.getResource(
206                 ResourceLoader.CLASSPATH_URL_PREFIX + "data/operational/ietf-network-topology-sample-rfc8345.json"));
207         return ResponseEntity.ok(sampleJson);
208     }
209
210     /**
211      * This method is not implemented for ONAP DMI plugin.
212      *
213      * @param topic                   client given topic name
214      * @param requestId               requestId generated by NCMP as an ack for client
215      * @param dmiDataOperationRequest list of operation details
216      * @return (@ code ResponseEntity) response entity
217      */
218     @PostMapping("/v1/data")
219     public ResponseEntity<Void> getResourceDataForCmHandleDataOperation(
220             @RequestParam(value = "topic") final String topic,
221             @RequestParam(value = "requestId") final String requestId,
222             @RequestBody final DmiDataOperationRequest dmiDataOperationRequest) {
223         delay(dataForCmHandleDelayMs);
224         try {
225             log.info("Request received from the NCMP to DMI Plugin: {}",
226                     objectMapper.writeValueAsString(dmiDataOperationRequest));
227         } catch (final JsonProcessingException jsonProcessingException) {
228             log.info("Unable to process dmi data operation request to json string");
229         }
230         dmiDataOperationRequest.getOperations().forEach(dmiDataOperation -> {
231             final DataOperationEvent dataOperationEvent = getDataOperationEvent(dmiDataOperation);
232             dmiDataOperation.getCmHandles().forEach(cmHandle -> {
233                 dataOperationEvent.getData().getResponses().get(0).setIds(List.of(cmHandle.getId()));
234                 final CloudEvent cloudEvent = buildAndGetCloudEvent(topic, requestId, dataOperationEvent);
235                 cloudEventKafkaTemplate.send(ncmpAsyncM2mTopic, UUID.randomUUID().toString(), cloudEvent);
236             });
237         });
238         return new ResponseEntity<>(HttpStatus.ACCEPTED);
239     }
240
241     private CloudEvent buildAndGetCloudEvent(final String topic, final String requestId,
242                                              final DataOperationEvent dataOperationEvent) {
243         CloudEvent cloudEvent = null;
244         try {
245             cloudEvent = CloudEventBuilder.v1()
246                     .withId(UUID.randomUUID().toString())
247                     .withSource(URI.create("DMI"))
248                     .withType(dataOperationEventType)
249                     .withDataSchema(URI.create("urn:cps:" + dataOperationEventType + ":1.0.0"))
250                     .withTime(EventDateTimeFormatter.toIsoOffsetDateTime(
251                             EventDateTimeFormatter.getCurrentIsoFormattedDateTime()))
252                     .withData(objectMapper.writeValueAsBytes(dataOperationEvent))
253                     .withExtension("destination", topic)
254                     .withExtension("correlationid", requestId)
255                     .build();
256         } catch (final JsonProcessingException jsonProcessingException) {
257             log.error("Unable to parse event into bytes. cause : {}", jsonProcessingException.getMessage());
258         }
259         return cloudEvent;
260     }
261
262     private DataOperationEvent getDataOperationEvent(final DataOperationRequest dataOperationRequest) {
263         final Response response = new Response();
264         response.setOperationId(dataOperationRequest.getOperationId());
265         response.setStatusCode(SUCCESS.getCode());
266         response.setStatusMessage(SUCCESS.getMessage());
267         response.setIds(dataOperationRequest.getCmHandles().stream().map(CmHandle::getId).toList());
268         response.setResourceIdentifier(dataOperationRequest.getResourceIdentifier());
269         response.setOptions(dataOperationRequest.getOptions());
270         final String ietfNetworkTopologySample = ResourceFileReaderUtil
271                 .getResourceFileContent(applicationContext.getResource(
272                         ResourceLoader.CLASSPATH_URL_PREFIX
273                                 + "data/operational/ietf-network-topology-sample-rfc8345.json"));
274         final JSONParser jsonParser = new JSONParser();
275         try {
276             response.setResult(jsonParser.parse(ietfNetworkTopologySample));
277         } catch (final ParseException parseException) {
278             log.error("Unable to parse event result as json object. cause : {}", parseException.getMessage());
279         }
280         final List<Response> responseList = new ArrayList<>(1);
281         responseList.add(response);
282         final Data data = new Data();
283         data.setResponses(responseList);
284         final DataOperationEvent dataOperationEvent = new DataOperationEvent();
285         dataOperationEvent.setData(data);
286         return dataOperationEvent;
287     }
288
289     private String getModuleResourceResponse(final String cmHandleId, final String moduleResponseType) {
290         if (moduleSetTagPerCmHandleId.isEmpty()) {
291             log.info("Using default module responses of type ietfYang");
292             return ResourceFileReaderUtil.getResourceFileContent(applicationContext.getResource(
293                     ResourceLoader.CLASSPATH_URL_PREFIX
294                             + String.format("module/ietfYang-%s", moduleResponseType)));
295         }
296         final String moduleSetTag = moduleSetTagPerCmHandleId.getOrDefault(cmHandleId, DEFAULT_TAG);
297         final String moduleResponseFilePath = String.format("module/%s-%s", moduleSetTag, moduleResponseType);
298         final Resource moduleResponseResource = applicationContext.getResource(
299                 ResourceLoader.CLASSPATH_URL_PREFIX + moduleResponseFilePath);
300         log.info("Using module responses from : {}", moduleResponseFilePath);
301         return ResourceFileReaderUtil.getResourceFileContent(moduleResponseResource);
302     }
303
304     private void delay(final long milliseconds) {
305         try {
306             Thread.sleep(milliseconds);
307         } catch (final InterruptedException e) {
308             log.error("Thread sleep interrupted: {}", e.getMessage());
309             Thread.currentThread().interrupt();
310         }
311     }
312 }