Async: NCMP Rest impl. including Request ID generation
[cps.git] / cps-ncmp-rest / src / main / java / org / onap / cps / ncmp / rest / controller / NetworkCmProxyController.java
index ca661b8..19b9193 100755 (executable)
@@ -1,15 +1,16 @@
 /*
  *  ============LICENSE_START=======================================================
  *  Copyright (C) 2021 Pantheon.tech
- *  Modifications (C) 2021 Nordix Foundation
+ *  Modifications Copyright (C) 2021-2022 Nordix Foundation
  *  Modification Copyright (C) 2021 highstreet technologies GmbH
- *  Modifications (C) 2021 Bell Canada
+ *  Modifications (C) 2021-2022 Bell Canada
  *  ================================================================================
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
  *  You may obtain a copy of the License at
  *
  *        http://www.apache.org/licenses/LICENSE-2.0
+ *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
 package org.onap.cps.ncmp.rest.controller;
 
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE;
+import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE;
+import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH;
+import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.UUID;
 import java.util.stream.Collectors;
 import javax.validation.Valid;
 import javax.validation.constraints.NotNull;
+import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
+import org.onap.cps.ncmp.api.impl.exception.InvalidTopicException;
+import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
 import org.onap.cps.ncmp.rest.api.NetworkCmProxyApi;
 import org.onap.cps.ncmp.rest.model.CmHandleProperties;
 import org.onap.cps.ncmp.rest.model.CmHandleProperty;
+import org.onap.cps.ncmp.rest.model.CmHandlePublicProperties;
 import org.onap.cps.ncmp.rest.model.CmHandles;
 import org.onap.cps.ncmp.rest.model.ConditionProperties;
 import org.onap.cps.ncmp.rest.model.Conditions;
 import org.onap.cps.ncmp.rest.model.ModuleNameAsJsonObject;
 import org.onap.cps.ncmp.rest.model.ModuleNamesAsJsonArray;
-import org.onap.cps.spi.FetchDescendantsOption;
-import org.onap.cps.spi.model.DataNode;
-import org.onap.cps.spi.model.ModuleReference;
-import org.onap.cps.utils.DataMapUtils;
+import org.onap.cps.ncmp.rest.model.RestModuleReference;
+import org.onap.cps.ncmp.rest.model.RestOutputCmHandle;
+import org.onap.cps.utils.CpsValidator;
+import org.onap.cps.utils.JsonObjectMapper;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -53,116 +64,45 @@ import org.springframework.web.bind.annotation.RestController;
 @Slf4j
 @RestController
 @RequestMapping("${rest.api.ncmp-base-path}")
+@RequiredArgsConstructor
 public class NetworkCmProxyController implements NetworkCmProxyApi {
 
-    private static final Gson GSON = new GsonBuilder().create();
+    private static final String NO_BODY = null;
+    private static final String NO_REQUEST_ID = null;
+    private static final String NO_TOPIC = null;
+    public static final String ASYNC_REQUEST_ID = "requestId";
 
     private final NetworkCmProxyDataService networkCmProxyDataService;
-
-    /**
-     * Constructor Injection for Dependencies.
-     * @param networkCmProxyDataService Data Service Interface
-     */
-    public NetworkCmProxyController(final NetworkCmProxyDataService networkCmProxyDataService) {
-        this.networkCmProxyDataService = networkCmProxyDataService;
-    }
-
-    /**
-     * Create Node.
-     * @deprecated This Method is no longer used as part of NCMP.
-     */
-    @Override
-    @Deprecated(forRemoval = false)
-    public ResponseEntity<Void> createNode(final String cmHandle, @Valid final String jsonData,
-        @Valid final String parentNodeXpath) {
-        networkCmProxyDataService.createDataNode(cmHandle, parentNodeXpath, jsonData);
-        return new ResponseEntity<>(HttpStatus.CREATED);
-    }
-
-    /**
-     * Add List-node Child Element.
-     * @deprecated This Method is no longer used as part of NCMP.
-     */
-    @Override
-    @Deprecated(forRemoval = false)
-    public ResponseEntity<Void> addListNodeElements(@NotNull @Valid final String parentNodeXpath,
-        final String cmHandle, @Valid final String jsonData) {
-        networkCmProxyDataService.addListNodeElements(cmHandle, parentNodeXpath, jsonData);
-        return new ResponseEntity<>(HttpStatus.CREATED);
-    }
-
-    /**
-     * Get Node By CM Handle and X-Path.
-     * @deprecated This Method is no longer used as part of NCMP.
-     */
-    @Override
-    @Deprecated(forRemoval = false)
-    public ResponseEntity<Object> getNodeByCmHandleAndXpath(final String cmHandle, @Valid final String xpath,
-        @Valid final Boolean includeDescendants) {
-        final FetchDescendantsOption fetchDescendantsOption = Boolean.TRUE.equals(includeDescendants)
-            ? FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS : FetchDescendantsOption.OMIT_DESCENDANTS;
-        final var dataNode = networkCmProxyDataService.getDataNode(cmHandle, xpath, fetchDescendantsOption);
-        return new ResponseEntity<>(DataMapUtils.toDataMap(dataNode), HttpStatus.OK);
-    }
-
-    /**
-     * Query Data Nodes.
-     * @deprecated This Method is no longer used as part of NCMP.
-     */
-    @Override
-    @Deprecated(forRemoval = false)
-    public ResponseEntity<Object> queryNodesByCmHandleAndCpsPath(final String cmHandle, @Valid final String cpsPath,
-        @Valid final Boolean includeDescendants) {
-        final FetchDescendantsOption fetchDescendantsOption = Boolean.TRUE.equals(includeDescendants)
-            ? FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS : FetchDescendantsOption.OMIT_DESCENDANTS;
-        final Collection<DataNode> dataNodes =
-            networkCmProxyDataService.queryDataNodes(cmHandle, cpsPath, fetchDescendantsOption);
-        return new ResponseEntity<>(GSON.toJson(dataNodes), HttpStatus.OK);
-    }
-
-    /**
-     * Replace Node With Descendants.
-     * @deprecated This Method is no longer used as part of NCMP.
-     */
-    @Override
-    @Deprecated(forRemoval = false)
-    public ResponseEntity<Object> replaceNode(final String cmHandle, @Valid final String jsonData,
-        @Valid final String parentNodeXpath) {
-        networkCmProxyDataService.replaceNodeTree(cmHandle, parentNodeXpath, jsonData);
-        return new ResponseEntity<>(HttpStatus.OK);
-    }
-
-    /**
-     * Update Node Leaves.
-     * @deprecated This Method is no longer used as part of NCMP.
-     */
-    @Override
-    @Deprecated(forRemoval = false)
-    public ResponseEntity<Object> updateNodeLeaves(final String cmHandle, @Valid final String jsonData,
-        @Valid final String parentNodeXpath) {
-        networkCmProxyDataService.updateNodeLeaves(cmHandle, parentNodeXpath, jsonData);
-        return new ResponseEntity<>(HttpStatus.OK);
-    }
+    private final JsonObjectMapper jsonObjectMapper;
+    private final NcmpRestInputMapper ncmpRestInputMapper;
 
     /**
      * Get resource data from operational datastore.
      *
      * @param cmHandle cm handle identifier
      * @param resourceIdentifier resource identifier
-     * @param acceptParamInHeader accept header parameter
      * @param optionsParamInQuery options query parameter
+     * @param topicParamInQuery topic query parameter
      * @return {@code ResponseEntity} response from dmi plugin
      */
     @Override
     public ResponseEntity<Object> getResourceDataOperationalForCmHandle(final String cmHandle,
                                                                         final @NotNull @Valid String resourceIdentifier,
-                                                                        final String acceptParamInHeader,
-                                                                        final @Valid String optionsParamInQuery) {
+                                                                        final @Valid String optionsParamInQuery,
+                                                                        final @Valid String topicParamInQuery) {
+        final ResponseEntity<Map<String, Object>> asyncResponse = populateAsyncResponse(topicParamInQuery);
+        final Map<String, Object> asyncResponseData = asyncResponse.getBody();
+
         final Object responseObject = networkCmProxyDataService.getResourceDataOperationalForCmHandle(cmHandle,
                 resourceIdentifier,
-                acceptParamInHeader,
-                optionsParamInQuery);
-        return ResponseEntity.ok(responseObject);
+                optionsParamInQuery,
+                asyncResponseData == null ? NO_TOPIC : topicParamInQuery,
+                asyncResponseData == null ? NO_REQUEST_ID : asyncResponseData.get(ASYNC_REQUEST_ID).toString());
+
+        if (asyncResponseData == null) {
+            return ResponseEntity.ok(responseObject);
+        }
+        return ResponseEntity.ok(asyncResponse);
     }
 
     /**
@@ -170,57 +110,132 @@ public class NetworkCmProxyController implements NetworkCmProxyApi {
      *
      * @param cmHandle cm handle identifier
      * @param resourceIdentifier resource identifier
-     * @param acceptParamInHeader accept header parameter
      * @param optionsParamInQuery options query parameter
+     * @param topicParamInQuery topic query parameter
      * @return {@code ResponseEntity} response from dmi plugin
      */
     @Override
     public ResponseEntity<Object> getResourceDataRunningForCmHandle(final String cmHandle,
                                                                     final @NotNull @Valid String resourceIdentifier,
-                                                                    final String acceptParamInHeader,
-                                                                    final @Valid String optionsParamInQuery) {
+                                                                    final @Valid String optionsParamInQuery,
+                                                                    final @Valid String topicParamInQuery) {
+        final ResponseEntity<Map<String, Object>> asyncResponse = populateAsyncResponse(topicParamInQuery);
+        final Map<String, Object> asyncResponseData = asyncResponse.getBody();
+
         final Object responseObject = networkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(cmHandle,
                 resourceIdentifier,
-                acceptParamInHeader,
-                optionsParamInQuery);
+                optionsParamInQuery,
+                asyncResponseData == null ? NO_TOPIC : topicParamInQuery,
+                asyncResponseData == null ? NO_REQUEST_ID : asyncResponseData.get(ASYNC_REQUEST_ID).toString());
+
+        if (asyncResponseData == null) {
+            return ResponseEntity.ok(responseObject);
+        }
+        return ResponseEntity.ok(asyncResponse);
+    }
+
+    @Override
+    public ResponseEntity<Object> patchResourceDataRunningForCmHandle(final String resourceIdentifier,
+        final String cmHandle,
+        final Object requestBody, final String contentType) {
+        final Object responseObject = networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
+            resourceIdentifier, PATCH, jsonObjectMapper.asJsonString(requestBody), contentType);
         return ResponseEntity.ok(responseObject);
     }
 
     /**
-     * Create resource data in datastore pass through running
-     * for given cm-handle.
+     * Create resource data in datastore pass-through running for given cm-handle.
      *
      * @param resourceIdentifier resource identifier
      * @param cmHandle cm handle identifier
-     * @param requestBody requestBody
+     * @param requestBody the request body
      * @param contentType content type of body
-     * @return {@code ResponseEntity} response from dmi plugi
+     * @return {@code ResponseEntity} response from dmi plugin
      */
     @Override
     public ResponseEntity<Void> createResourceDataRunningForCmHandle(final String resourceIdentifier,
-                                                                     final String cmHandle,
-                                                                     final String requestBody,
-                                                                     final String contentType) {
-        networkCmProxyDataService.createResourceDataPassThroughRunningForCmHandle(cmHandle,
-                resourceIdentifier, requestBody, contentType);
+        final String cmHandle, final Object requestBody, final String contentType) {
+        networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
+                resourceIdentifier, CREATE, jsonObjectMapper.asJsonString(requestBody), contentType);
         return new ResponseEntity<>(HttpStatus.CREATED);
     }
 
+    /**
+     * Update resource data in datastore pass-through running for given cm-handle.
+     *
+     * @param resourceIdentifier resource identifier
+     * @param cmHandle cm handle identifier
+     * @param requestBody the request body
+     * @param contentType content type of the body
+     * @return response entity
+     */
+    @Override
+    public ResponseEntity<Object> updateResourceDataRunningForCmHandle(final String resourceIdentifier,
+                                                                       final String cmHandle,
+                                                                       final Object requestBody,
+                                                                       final String contentType) {
+        networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
+                resourceIdentifier, UPDATE, jsonObjectMapper.asJsonString(requestBody), contentType);
+        return new ResponseEntity<>(HttpStatus.OK);
+    }
+
+
+    /**
+     *  Delete resource data in datastore pass-through running for a given cm-handle.
+     *
+     * @param resourceIdentifier resource identifier
+     * @param cmHandle cm handle identifier
+     * @param contentType content type of the body
+     * @return response entity no content if request is successful
+     */
+    @Override
+    public ResponseEntity<Void> deleteResourceDataRunningForCmHandle(final String cmHandle,
+                                                                     final String resourceIdentifier,
+                                                                     final String contentType) {
+        networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
+            resourceIdentifier, DELETE, NO_BODY, contentType);
+        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+    }
+
+    /**
+     * Execute cm handle search.
+     *
+     * @param conditions the conditions
+     * @return cm handles returned from search.
+     */
     @Override
     public ResponseEntity<CmHandles> executeCmHandleSearch(final Conditions conditions) {
         final List<ConditionProperties> conditionProperties =
             conditions.getConditions().stream().collect(Collectors.toList());
         final CmHandles cmHandles = new CmHandles();
-        final Collection<String> cmHandleIdentifiers = processConditions(conditionProperties);
-        cmHandleIdentifiers.forEach(cmHandle -> cmHandles.setCmHandles(toCmHandleProperties(cmHandle)));
+        cmHandles.setCmHandles(toCmHandleProperties(processConditions(conditionProperties)));
         return ResponseEntity.ok(cmHandles);
     }
 
+    /**
+     * Search for Cm Handle and Properties by Name.
+     * @param cmHandleId cm-handle identifier
+     * @return cm handle and its properties
+     */
     @Override
-    public ResponseEntity<Object> getModuleReferencesByCmHandle(final String cmHandle) {
-        final Collection<ModuleReference>
-            moduleReferences = networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle);
-        return new ResponseEntity<>(new Gson().toJson(moduleReferences), HttpStatus.OK);
+    public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
+        final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
+        final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
+        return ResponseEntity.ok(restOutputCmHandle);
+    }
+
+    /**
+     * Return module references for a cm handle.
+     *
+     * @param cmHandle the cm handle
+     * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
+     */
+    public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
+        final List<RestModuleReference> restModuleReferences =
+            networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
+            .map(ncmpRestInputMapper::toRestModuleReference)
+                .collect(Collectors.toList());
+        return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
     }
 
     private Collection<String> processConditions(final List<ConditionProperties> conditionProperties) {
@@ -248,13 +263,51 @@ public class NetworkCmProxyController implements NetworkCmProxyApi {
         return moduleNames;
     }
 
-    private CmHandleProperties toCmHandleProperties(final String cmHandleId) {
+    private CmHandleProperties toCmHandleProperties(final Collection<String> cmHandleIdentifiers) {
         final CmHandleProperties cmHandleProperties = new CmHandleProperties();
-        final CmHandleProperty cmHandleProperty = new CmHandleProperty();
-        cmHandleProperty.setCmHandleId(cmHandleId);
-        cmHandleProperties.add(cmHandleProperty);
+        for (final String cmHandleIdentifier : cmHandleIdentifiers) {
+            final CmHandleProperty cmHandleProperty = new CmHandleProperty();
+            cmHandleProperty.setCmHandleId(cmHandleIdentifier);
+            cmHandleProperties.add(cmHandleProperty);
+        }
         return cmHandleProperties;
     }
 
+    private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
+        final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
+        final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
+        restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleID());
+        cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
+        restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
+        return restOutputCmHandle;
+    }
+
+    private ResponseEntity<Map<String, Object>> populateAsyncResponse(final String topicParamInQuery) {
+        final boolean processAsynchronously = hasTopicParameter(topicParamInQuery);
+        final Map<String, Object> responseData;
+        if (processAsynchronously) {
+            responseData = getAsyncResponseData();
+        } else {
+            responseData = null;
+        }
+        return ResponseEntity.ok().body(responseData);
+    }
+
+    private static boolean hasTopicParameter(final String topicName) {
+        if (topicName == null) {
+            return false;
+        }
+        if (CpsValidator.validateTopicName(topicName)) {
+            return true;
+        }
+        throw new InvalidTopicException("Topic name " + topicName + " is invalid", "invalid topic");
+    }
+
+    private Map<String, Object> getAsyncResponseData() {
+        final Map<String, Object> asyncResponseData = new HashMap<>(1);
+        final String resourceDataRequestId = UUID.randomUUID().toString();
+        asyncResponseData.put(ASYNC_REQUEST_ID, resourceDataRequestId);
+        return asyncResponseData;
+    }
 
 }