2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2023-2025 OpenInfra Foundation Europe. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.ncmp.dmi.rest.stub.controller;
23 import static org.onap.cps.ncmp.dmi.rest.stub.utils.ModuleResponseType.MODULE_REFERENCE_RESPONSE;
24 import static org.onap.cps.ncmp.dmi.rest.stub.utils.ModuleResponseType.MODULE_RESOURCE_RESPONSE;
26 import com.fasterxml.jackson.core.JsonProcessingException;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import io.cloudevents.CloudEvent;
30 import io.cloudevents.core.builder.CloudEventBuilder;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
36 import java.util.UUID;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import java.util.stream.Collectors;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.json.simple.parser.JSONParser;
42 import org.json.simple.parser.ParseException;
43 import org.onap.cps.ncmp.dmi.datajobs.model.SubjobWriteRequest;
44 import org.onap.cps.ncmp.dmi.datajobs.model.SubjobWriteResponse;
45 import org.onap.cps.ncmp.dmi.rest.stub.controller.aop.ModuleInitialProcess;
46 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DataOperationRequest;
47 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DmiDataOperationRequest;
48 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DmiOperationCmHandle;
49 import org.onap.cps.ncmp.dmi.rest.stub.service.YangModuleFactory;
50 import org.onap.cps.ncmp.dmi.rest.stub.utils.EventDateTimeFormatter;
51 import org.onap.cps.ncmp.dmi.rest.stub.utils.ModuleResponseType;
52 import org.onap.cps.ncmp.dmi.rest.stub.utils.ResourceFileReaderUtil;
53 import org.onap.cps.ncmp.events.async1_0_0.Data;
54 import org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent;
55 import org.onap.cps.ncmp.events.async1_0_0.Response;
56 import org.springframework.beans.factory.annotation.Value;
57 import org.springframework.context.ApplicationContext;
58 import org.springframework.core.io.ResourceLoader;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.ResponseEntity;
61 import org.springframework.kafka.core.KafkaTemplate;
62 import org.springframework.web.bind.annotation.DeleteMapping;
63 import org.springframework.web.bind.annotation.GetMapping;
64 import org.springframework.web.bind.annotation.PathVariable;
65 import org.springframework.web.bind.annotation.PostMapping;
66 import org.springframework.web.bind.annotation.PutMapping;
67 import org.springframework.web.bind.annotation.RequestBody;
68 import org.springframework.web.bind.annotation.RequestHeader;
69 import org.springframework.web.bind.annotation.RequestMapping;
70 import org.springframework.web.bind.annotation.RequestParam;
71 import org.springframework.web.bind.annotation.RestController;
72 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
75 @RequestMapping("${rest.api.dmi-stub-base-path}")
77 @RequiredArgsConstructor
78 public class DmiRestStubController {
80 private static final String DEFAULT_PASSTHROUGH_OPERATION = "read";
81 private static final String DATA_OPERATION_EVENT_TYPE = "org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent";
82 private static final Map<String, String> moduleSetTagPerCmHandleId = new HashMap<>();
83 private static final List<String> MODULE_SET_TAGS = YangModuleFactory.generateTags();
84 private static final String DEFAULT_TAG = "tagDefault";
86 private final KafkaTemplate<String, CloudEvent> cloudEventKafkaTemplate;
87 private final ObjectMapper objectMapper;
88 private final ApplicationContext applicationContext;
89 private final AtomicInteger subJobWriteRequestCounter = new AtomicInteger();
90 private final YangModuleFactory yangModuleFactory;
92 @Value("${app.ncmp.async-m2m.topic}")
93 private String ncmpAsyncM2mTopic;
94 @Value("${delay.module-references-delay-ms}")
95 private long moduleReferencesDelayMs;
96 @Value("${delay.module-resources-delay-ms}")
97 private long moduleResourcesDelayMs;
98 @Value("${delay.read-data-for-cm-handle-delay-ms}")
99 private long readDataForCmHandleDelayMs;
100 @Value("${delay.write-data-for-cm-handle-delay-ms}")
101 private long writeDataForCmHandleDelayMs;
104 * This code defines a REST API endpoint for adding new the module set tag mapping. The endpoint receives the
105 * cmHandleId and moduleSetTag as request body and add into moduleSetTagPerCmHandleId map with the provided
108 * @param requestBody map of cmHandleId and moduleSetTag
109 * @return a ResponseEntity object containing the updated moduleSetTagPerCmHandleId map as the response body
111 @PostMapping("/v1/tagMapping")
112 public ResponseEntity<Map<String, String>> addTagForMapping(@RequestBody final Map<String, String> requestBody) {
113 moduleSetTagPerCmHandleId.putAll(requestBody);
114 return new ResponseEntity<>(requestBody, HttpStatus.CREATED);
118 * This code defines a GET endpoint of module set tag mapping.
120 * @return The map represents the module set tag mapping.
122 @GetMapping("/v1/tagMapping")
123 public ResponseEntity<Map<String, String>> getTagMapping() {
124 return ResponseEntity.ok(moduleSetTagPerCmHandleId);
128 * This code defines a GET endpoint of module set tag by cm handle ID.
130 * @return The map represents the module set tag mapping filtered by cm handle ID.
132 @GetMapping("/v1/tagMapping/ch/{cmHandleId}")
133 public ResponseEntity<String> getTagMappingByCmHandleId(@PathVariable final String cmHandleId) {
134 return ResponseEntity.ok(moduleSetTagPerCmHandleId.get(cmHandleId));
138 * This code defines a REST API endpoint for updating the module set tag mapping. The endpoint receives the
139 * cmHandleId and moduleSetTag as request body and updates the moduleSetTagPerCmHandleId map with the provided
142 * @param requestBody map of cmHandleId and moduleSetTag
143 * @return a ResponseEntity object containing the updated moduleSetTagPerCmHandleId map as the response body
146 @PutMapping("/v1/tagMapping")
147 public ResponseEntity<Map<String, String>> updateTagMapping(@RequestBody final Map<String, String> requestBody) {
148 moduleSetTagPerCmHandleId.putAll(requestBody);
149 return ResponseEntity.noContent().build();
153 * It contains a method to delete an entry from the moduleSetTagPerCmHandleId map.
154 * The method takes a cmHandleId as a parameter and removes the corresponding entry from the map.
156 * @return a ResponseEntity containing the updated map.
158 @DeleteMapping("/v1/tagMapping/ch/{cmHandleId}")
159 public ResponseEntity<String> deleteTagMappingByCmHandleId(@PathVariable final String cmHandleId) {
160 moduleSetTagPerCmHandleId.remove(cmHandleId);
161 return ResponseEntity.ok(String.format("Mapping of %s is deleted successfully", cmHandleId));
165 * Get all modules for given cm handle.
167 * @param cmHandleId The identifier for a network function, network element, subnetwork,
168 * or any other cm object by managed Network CM Proxy
169 * @param moduleReferencesRequest module references request body
170 * @return ResponseEntity response entity having module response as json string.
172 @PostMapping("/v1/ch/{cmHandleId}/modules")
173 @ModuleInitialProcess
174 public ResponseEntity<String> getModuleReferences(@PathVariable("cmHandleId") final String cmHandleId,
175 @RequestBody final Object moduleReferencesRequest) {
176 return processModuleRequest(moduleReferencesRequest, MODULE_REFERENCE_RESPONSE, moduleReferencesDelayMs);
180 * Get module resources for a given cmHandleId.
182 * @param cmHandleId The identifier for a network function, network element, subnetwork,
183 * or any other cm object by managed Network CM Proxy
184 * @param moduleResourcesReadRequest module resources read request body
185 * @return ResponseEntity response entity having module resources response as json string.
187 @PostMapping("/v1/ch/{cmHandleId}/moduleResources")
188 @ModuleInitialProcess
189 public ResponseEntity<String> getModuleResources(
190 @PathVariable("cmHandleId") final String cmHandleId,
191 @RequestBody final Object moduleResourcesReadRequest) {
192 return processModuleRequest(moduleResourcesReadRequest, MODULE_RESOURCE_RESPONSE, moduleResourcesDelayMs);
196 * Create resource data from passthrough operational or running for a cm handle.
198 * @param cmHandleId The identifier for a network function, network element, subnetwork,
199 * or any other cm object by managed Network CM Proxy
200 * @param datastoreName datastore name
201 * @param resourceIdentifier resource identifier
202 * @param options options
203 * @param topic client given topic name
204 * @return (@ code ResponseEntity) response entity
206 @PostMapping("/v1/ch/{cmHandleId}/data/ds/{datastoreName}")
207 public ResponseEntity<String> getResourceDataForCmHandle(
208 @PathVariable("cmHandleId") final String cmHandleId,
209 @PathVariable("datastoreName") final String datastoreName,
210 @RequestParam(value = "resourceIdentifier") final String resourceIdentifier,
211 @RequestParam(value = "options", required = false) final String options,
212 @RequestParam(value = "topic", required = false) final String topic,
213 @RequestHeader(value = "Authorization", required = false) final String authorization,
214 @RequestBody final String requestBody) {
215 log.debug("DMI AUTH HEADER: {}", authorization);
216 final String passthroughOperationType = getPassthroughOperationType(requestBody);
217 if (passthroughOperationType.equals("read")) {
218 delay(readDataForCmHandleDelayMs);
220 delay(writeDataForCmHandleDelayMs);
222 log.debug("Logging request body {}", requestBody);
224 final String sampleJson = ResourceFileReaderUtil.getResourceFileContent(applicationContext.getResource(
225 ResourceLoader.CLASSPATH_URL_PREFIX + "data/ietf-network-topology-sample-rfc8345.json"));
226 return ResponseEntity.ok(sampleJson.replace("#network-id", getCompositeNetworkId(cmHandleId)));
230 * This method is not implemented for ONAP DMI plugin.
232 * @param topic client given topic name
233 * @param requestId requestId generated by NCMP as an ack for client
234 * @param dmiDataOperationRequest list of operation details
235 * @return (@ code ResponseEntity) response entity
237 @PostMapping("/v1/data")
238 public ResponseEntity<Void> getResourceDataForCmHandleDataOperation(
239 @RequestParam(value = "topic") final String topic,
240 @RequestParam(value = "requestId") final String requestId,
241 @RequestBody final DmiDataOperationRequest dmiDataOperationRequest) {
242 delay(writeDataForCmHandleDelayMs);
244 log.debug("Request received from the NCMP to DMI Plugin: {}",
245 objectMapper.writeValueAsString(dmiDataOperationRequest));
246 } catch (final JsonProcessingException jsonProcessingException) {
247 log.warn("Unable to process dmi data operation request to json string");
249 dmiDataOperationRequest.getOperations().forEach(dmiDataOperation -> {
250 final DataOperationEvent dataOperationEvent = getDataOperationEvent(dmiDataOperation);
251 dmiDataOperation.getCmHandles().forEach(dmiOperationCmHandle -> {
252 log.debug("Module Set Tag received: {}", dmiOperationCmHandle.getModuleSetTag());
253 dataOperationEvent.getData().getResponses().get(0).setIds(List.of(dmiOperationCmHandle.getId()));
254 final CloudEvent cloudEvent = buildAndGetCloudEvent(topic, requestId, dataOperationEvent);
255 cloudEventKafkaTemplate.send(ncmpAsyncM2mTopic, UUID.randomUUID().toString(), cloudEvent);
258 return new ResponseEntity<>(HttpStatus.ACCEPTED);
262 * Consume sub-job write requests from NCMP.
264 * @param subJobWriteRequest contains a collection of write requests and metadata.
265 * @param destination the destination of the results. ( e.g. S3 Bucket).
266 * @return (@ code ResponseEntity) response for the write request.
268 @PostMapping("/v1/cmwriteJob")
269 public ResponseEntity<SubjobWriteResponse> consumeWriteSubJobs(
270 @RequestBody final SubjobWriteRequest subJobWriteRequest,
271 @RequestParam("destination") final String destination) {
272 log.debug("Destination: {}", destination);
273 log.debug("Request body: {}", subJobWriteRequest);
274 return ResponseEntity.ok(new SubjobWriteResponse(String.valueOf(subJobWriteRequestCounter.incrementAndGet()),
275 "some-dmi-service-name", "my-data-producer-id"));
279 * Retrieves the status of a given data job identified by {@code requestId} and {@code dataProducerJobId}.
281 * @param dataProducerId ID of the producer registered by DMI for the alternateIDs
282 * in the operations in this request.
283 * @param dataProducerJobId Identifier of the data producer job.
284 * @return A ResponseEntity with HTTP status 200 (OK) and the data job's status as a string.
286 @GetMapping("/v1/cmwriteJob/dataProducer/{dataProducerId}/dataProducerJob/{dataProducerJobId}/status")
287 public ResponseEntity<Map<String, String>> retrieveDataJobStatus(
288 @PathVariable("dataProducerId") final String dataProducerId,
289 @PathVariable("dataProducerJobId") final String dataProducerJobId) {
290 log.debug("Received request to retrieve data job status. Request ID: {}, Data Producer Job ID: {}",
291 dataProducerId, dataProducerJobId);
292 return ResponseEntity.ok(Map.of("status", "FINISHED"));
296 * Retrieves the result of a given data job identified by {@code requestId} and {@code dataProducerJobId}.
298 * @param dataProducerId Identifier for the data producer as a query parameter (required)
299 * @param dataProducerJobId Identifier for the data producer job (required)
300 * @param destination The destination of the results, Kafka topic name or s3 bucket name (required)
301 * @return A ResponseEntity with HTTP status 200 (OK) and the data job's result as an Object.
303 @GetMapping("/v1/cmwriteJob/dataProducer/{dataProducerId}/dataProducerJob/{dataProducerJobId}/result")
304 public ResponseEntity<Object> retrieveDataJobResult(
305 @PathVariable("dataProducerId") final String dataProducerId,
306 @PathVariable("dataProducerJobId") final String dataProducerJobId,
307 @RequestParam(name = "destination") final String destination) {
308 log.debug("Received request to retrieve data job result. Data Producer ID: {}, "
309 + "Data Producer Job ID: {}, Destination: {}",
310 dataProducerId, dataProducerJobId, destination);
311 return ResponseEntity.ok(Map.of("result", "some status"));
314 private CloudEvent buildAndGetCloudEvent(final String topic, final String requestId,
315 final DataOperationEvent dataOperationEvent) {
316 CloudEvent cloudEvent = null;
318 cloudEvent = CloudEventBuilder.v1()
319 .withId(UUID.randomUUID().toString())
320 .withSource(URI.create("DMI"))
321 .withType(DATA_OPERATION_EVENT_TYPE)
322 .withDataSchema(URI.create("urn:cps:" + DATA_OPERATION_EVENT_TYPE + ":1.0.0"))
323 .withTime(EventDateTimeFormatter.toIsoOffsetDateTime(
324 EventDateTimeFormatter.getCurrentIsoFormattedDateTime()))
325 .withData(objectMapper.writeValueAsBytes(dataOperationEvent))
326 .withExtension("destination", topic)
327 .withExtension("correlationid", requestId)
329 } catch (final JsonProcessingException jsonProcessingException) {
330 log.error("Unable to parse event into bytes. cause : {}", jsonProcessingException.getMessage());
335 private DataOperationEvent getDataOperationEvent(final DataOperationRequest dataOperationRequest) {
336 final Response response = new Response();
338 response.setOperationId(dataOperationRequest.getOperationId());
339 response.setStatusCode("0");
340 response.setStatusMessage("Successfully applied changes");
341 response.setIds(dataOperationRequest.getCmHandles().stream().map(DmiOperationCmHandle::getId)
342 .collect(Collectors.toList()));
343 response.setResourceIdentifier(dataOperationRequest.getResourceIdentifier());
344 response.setOptions(dataOperationRequest.getOptions());
345 final String ietfNetworkTopologySample = ResourceFileReaderUtil.getResourceFileContent(
346 applicationContext.getResource(ResourceLoader.CLASSPATH_URL_PREFIX
347 + "data/ietf-network-topology-sample-rfc8345.json"));
348 final JSONParser jsonParser = new JSONParser();
350 response.setResult(jsonParser.parse(ietfNetworkTopologySample));
351 } catch (final ParseException parseException) {
352 log.error("Unable to parse event result as json object. cause : {}", parseException.getMessage());
354 final List<Response> responseList = new ArrayList<>(1);
355 responseList.add(response);
356 final Data data = new Data();
357 data.setResponses(responseList);
358 final DataOperationEvent dataOperationEvent = new DataOperationEvent();
359 dataOperationEvent.setData(data);
360 return dataOperationEvent;
363 private ResponseEntity<String> processModuleRequest(final Object moduleRequest,
364 final ModuleResponseType moduleResponseType,
365 final long simulatedResponseDelay) {
366 logRequestBody(moduleRequest);
367 String moduleResponseContent = "";
368 String moduleSetTag = extractModuleSetTagFromRequest(moduleRequest);
370 moduleSetTag = (!isModuleSetTagNullOrEmpty(moduleSetTag)
371 && MODULE_SET_TAGS.contains(moduleSetTag)) ? moduleSetTag : DEFAULT_TAG;
373 if (MODULE_RESOURCE_RESPONSE == moduleResponseType) {
374 moduleResponseContent = yangModuleFactory.getModuleResourcesJson(moduleSetTag);
376 moduleResponseContent = yangModuleFactory.getModuleReferencesJson(moduleSetTag);
379 delay(simulatedResponseDelay);
380 return ResponseEntity.ok(moduleResponseContent);
383 private String extractModuleSetTagFromRequest(final Object moduleReferencesRequest) {
384 final JsonNode rootNode = objectMapper.valueToTree(moduleReferencesRequest);
385 return rootNode.path("moduleSetTag").asText(null);
388 private boolean isModuleSetTagNullOrEmpty(final String moduleSetTag) {
389 return moduleSetTag == null || moduleSetTag.trim().isEmpty();
392 private void logRequestBody(final Object request) {
394 log.debug("Incoming DMI request body: {}", objectMapper.writeValueAsString(request));
395 } catch (final JsonProcessingException jsonProcessingException) {
396 log.warn("Unable to parse DMI request to json string");
400 private String getPassthroughOperationType(final String requestBody) {
402 final JsonNode rootNode = objectMapper.readTree(requestBody);
403 return rootNode.path("operation").asText();
404 } catch (final JsonProcessingException jsonProcessingException) {
405 log.error("Invalid JSON format. cause : {}", jsonProcessingException.getMessage());
407 return DEFAULT_PASSTHROUGH_OPERATION;
410 private void delay(final long milliseconds) {
412 Thread.sleep(milliseconds);
413 } catch (final InterruptedException e) {
414 log.error("Thread sleep interrupted: {}", e.getMessage());
415 Thread.currentThread().interrupt();
419 private static String getCompositeNetworkId(final String cmHandleId) {
420 final String servletUri = ServletUriComponentsBuilder
421 .fromCurrentContextPath() // scheme://host:port
424 return servletUri + "-" + cmHandleId; // e.g. http://cps-ncmp-dmi-stub-1:8092-my-cm-handle