Core logic to update,add or remove cmHandle properties
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServiceImpl.java
index 62a0922..38f8e17 100755 (executable)
@@ -1,7 +1,7 @@
 /*
  *  ============LICENSE_START=======================================================
  *  Copyright (C) 2021 highstreet technologies GmbH
- *  Modifications Copyright (C) 2021 Nordix Foundation
+ *  Modifications Copyright (C) 2021-2022 Nordix Foundation
  *  Modifications Copyright (C) 2021 Pantheon.tech
  *  Modifications Copyright (C) 2021 Bell Canada
  *  ================================================================================
 
 package org.onap.cps.ncmp.api.impl;
 
+import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DATASPACE_NAME;
+import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_ANCHOR;
+import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_PARENT;
+import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
+import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NO_TIMESTAMP;
 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum;
 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import java.time.OffsetDateTime;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.onap.cps.api.CpsAdminService;
 import org.onap.cps.api.CpsDataService;
 import org.onap.cps.api.CpsModuleService;
-import org.onap.cps.api.CpsQueryService;
 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
-import org.onap.cps.ncmp.api.impl.exception.NcmpException;
+import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException;
 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations;
 import org.onap.cps.ncmp.api.impl.operations.DmiOperations;
@@ -52,107 +51,31 @@ import org.onap.cps.ncmp.api.models.CmHandle;
 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
 import org.onap.cps.ncmp.api.models.PersistenceCmHandle;
 import org.onap.cps.ncmp.api.models.PersistenceCmHandlesList;
-import org.onap.cps.ncmp.api.models.YangResource;
-import org.onap.cps.spi.FetchDescendantsOption;
 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
 import org.onap.cps.spi.exceptions.DataValidationException;
-import org.onap.cps.spi.model.DataNode;
 import org.onap.cps.spi.model.ModuleReference;
+import org.onap.cps.utils.JsonObjectMapper;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
-import org.springframework.util.StringUtils;
 
 @Slf4j
 @Service
+@RequiredArgsConstructor
 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
 
-    private static final String NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME = "NFP-Operational";
+    private final CpsDataService cpsDataService;
 
-    private static final String NCMP_DATASPACE_NAME = "NCMP-Admin";
+    private final JsonObjectMapper jsonObjectMapper;
 
-    private static final String NCMP_DMI_REGISTRY_ANCHOR = "ncmp-dmi-registry";
+    private final DmiDataOperations dmiDataOperations;
 
-    private static final OffsetDateTime NO_TIMESTAMP = null;
+    private final DmiModelOperations dmiModelOperations;
 
-    private CpsDataService cpsDataService;
+    private final CpsModuleService cpsModuleService;
 
-    private ObjectMapper objectMapper;
+    private final CpsAdminService cpsAdminService;
 
-    private CpsQueryService cpsQueryService;
-
-    private DmiDataOperations dmiDataOperations;
-
-    private DmiModelOperations dmiModelOperations;
-
-    private CpsModuleService cpsModuleService;
-
-    private CpsAdminService cpsAdminService;
-
-    /**
-     * Constructor Injection for Dependencies.
-     * @param dmiDataOperations DMI operation
-     * @param cpsDataService Data Service Interface
-     * @param cpsQueryService Query Service Interface
-     * @param objectMapper Object Mapper
-     */
-    public NetworkCmProxyDataServiceImpl(final DmiDataOperations dmiDataOperations,
-                                         final DmiModelOperations dmiModelOperations,
-                                         final CpsModuleService cpsModuleService,
-                                         final CpsDataService cpsDataService,
-                                         final CpsQueryService cpsQueryService,
-                                         final CpsAdminService cpsAdminService,
-                                         final ObjectMapper objectMapper) {
-        this.dmiDataOperations = dmiDataOperations;
-        this.dmiModelOperations = dmiModelOperations;
-        this.cpsModuleService = cpsModuleService;
-        this.cpsDataService = cpsDataService;
-        this.cpsQueryService = cpsQueryService;
-        this.cpsAdminService = cpsAdminService;
-        this.objectMapper = objectMapper;
-    }
-
-    @Override
-    public DataNode getDataNode(final String cmHandle, final String xpath,
-        final FetchDescendantsOption fetchDescendantsOption) {
-        return cpsDataService
-            .getDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, xpath, fetchDescendantsOption);
-    }
-
-    @Override
-    public Collection<DataNode> queryDataNodes(final String cmHandle, final String cpsPath,
-        final FetchDescendantsOption fetchDescendantsOption) {
-        return cpsQueryService
-            .queryDataNodes(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, cpsPath, fetchDescendantsOption);
-    }
-
-    @Override
-    public void createDataNode(final String cmHandle, final String parentNodeXpath, final String jsonData) {
-        if (!StringUtils.hasText(parentNodeXpath) || "/".equals(parentNodeXpath)) {
-            cpsDataService.saveData(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, jsonData, NO_TIMESTAMP);
-        } else {
-            cpsDataService
-                .saveData(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, parentNodeXpath, jsonData, NO_TIMESTAMP);
-        }
-    }
-
-    @Override
-    public void addListNodeElements(final String cmHandle, final String parentNodeXpath, final String jsonData) {
-        cpsDataService.saveListElements(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, parentNodeXpath, jsonData,
-            NO_TIMESTAMP);
-    }
-
-    @Override
-    public void updateNodeLeaves(final String cmHandle, final String parentNodeXpath, final String jsonData) {
-        cpsDataService
-            .updateNodeLeaves(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, parentNodeXpath, jsonData,
-                NO_TIMESTAMP);
-    }
-
-    @Override
-    public void replaceNodeTree(final String cmHandle, final String parentNodeXpath, final String jsonData) {
-        cpsDataService.replaceNodeTree(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle, parentNodeXpath, jsonData,
-            NO_TIMESTAMP);
-    }
+    private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
 
     @Override
     public void updateDmiRegistrationAndSyncModule(final DmiPluginRegistration dmiPluginRegistration) {
@@ -167,8 +90,11 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
             if (dmiPluginRegistration.getRemovedCmHandles() != null) {
                 parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration);
             }
-        } catch (final JsonProcessingException e) {
-            handleJsonProcessingException(dmiPluginRegistration, e);
+        } catch (final JsonProcessingException | DataNodeNotFoundException e) {
+            final String errorMessage = String.format(
+                    "Error occurred while processing the CM-handle registration request [%s] ,caused by : [%s]",
+                    dmiPluginRegistration, e.getMessage());
+            throw new DataValidationException(errorMessage, e.getMessage(), e);
         }
     }
 
@@ -199,12 +125,12 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
     }
 
     @Override
-    public void writeResourceDataPassThroughRunningForCmHandle(final String cmHandle,
+    public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandle,
                                                                final String resourceIdentifier,
                                                                final OperationEnum operation,
                                                                final String requestData,
                                                                final String dataType) {
-        handleResponse(
+        return handleResponse(
             dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(
                 cmHandle, resourceIdentifier, operation, requestData, dataType),
             "Not able to " + operation + " resource data.");
@@ -245,19 +171,14 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
         if (responseEntity.getStatusCode().is2xxSuccessful()) {
             return responseEntity.getBody();
         } else {
-            throw new NcmpException(exceptionMessage,
+            throw new ServerNcmpException(exceptionMessage,
                     "DMI status code: " + responseEntity.getStatusCodeValue()
                             + ", DMI response body: " + responseEntity.getBody());
         }
     }
 
-    private void parseAndUpdateCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration)
-        throws JsonProcessingException {
-        final PersistenceCmHandlesList updatedPersistenceCmHandlesList =
-            getUpdatedPersistenceCmHandlesList(dmiPluginRegistration, dmiPluginRegistration.getUpdatedCmHandles());
-        final String cmHandlesAsJson = objectMapper.writeValueAsString(updatedPersistenceCmHandlesList);
-        cpsDataService.updateNodeLeavesAndExistingDescendantLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
-                "/dmi-registry", cmHandlesAsJson, NO_TIMESTAMP);
+    private void parseAndUpdateCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration) {
+        networkCmProxyDataServicePropertyHandler.updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles());
     }
 
     private PersistenceCmHandlesList getUpdatedPersistenceCmHandlesList(
@@ -270,19 +191,10 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
             updatedCmHandles);
     }
 
-    private static void handleJsonProcessingException(final DmiPluginRegistration dmiPluginRegistration,
-                                                      final JsonProcessingException e) {
-        final String message = "Parsing error occurred while processing DMI Plugin Registration"
-            + dmiPluginRegistration;
-        log.error(message);
-        throw new DataValidationException(message, e.getMessage(), e);
-    }
-
-    private void registerAndSyncNewCmHandles(final PersistenceCmHandlesList persistenceCmHandlesList)
-        throws JsonProcessingException  {
-        final String cmHandleJsonData = objectMapper.writeValueAsString(persistenceCmHandlesList);
-        cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, "/dmi-registry",
-            cmHandleJsonData, NO_TIMESTAMP);
+    private void registerAndSyncNewCmHandles(final PersistenceCmHandlesList persistenceCmHandlesList) {
+        final String cmHandleJsonData = jsonObjectMapper.asJsonString(persistenceCmHandlesList);
+        cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
+                cmHandleJsonData, NO_TIMESTAMP);
 
         for (final PersistenceCmHandle persistenceCmHandle : persistenceCmHandlesList.getPersistenceCmHandles()) {
             syncModulesAndCreateAnchor(persistenceCmHandle);
@@ -316,9 +228,8 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
     }
 
     private void syncAndCreateSchemaSet(final PersistenceCmHandle persistenceCmHandle) {
-
         final List<ModuleReference> moduleReferencesFromCmHandle =
-            toModuleReferences(dmiModelOperations.getModuleReferences(persistenceCmHandle));
+            dmiModelOperations.getModuleReferences(persistenceCmHandle);
         final List<ModuleReference> existingModuleReferences = new ArrayList<>();
         final List<ModuleReference> unknownModuleReferences = new ArrayList<>();
         prepareModuleSubsets(moduleReferencesFromCmHandle, existingModuleReferences, unknownModuleReferences);
@@ -327,7 +238,7 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
         if (unknownModuleReferences.isEmpty()) {
             newYangResourcesModuleNameToContentMap = new HashMap<>();
         } else {
-            newYangResourcesModuleNameToContentMap = getNewYangResourcesFromDmi(persistenceCmHandle,
+            newYangResourcesModuleNameToContentMap = dmiModelOperations.getNewYangResourcesFromDmi(persistenceCmHandle,
                 unknownModuleReferences);
         }
         cpsModuleService
@@ -355,48 +266,4 @@ public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService
         cpsAdminService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, persistenceCmHandle.getId(),
             persistenceCmHandle.getId());
     }
-
-    private Map<String, String> getNewYangResourcesFromDmi(final PersistenceCmHandle persistenceCmHandle,
-                                                           final List<ModuleReference> unknownModuleReferences) {
-        final ResponseEntity<String> responseEntity =
-            dmiModelOperations.getNewYangResourcesFromDmi(persistenceCmHandle, unknownModuleReferences);
-
-        final JsonArray moduleResources = new Gson().fromJson(responseEntity.getBody(),
-            JsonArray.class);
-        final Map<String, String> newYangResourcesModuleNameToContentMap = new HashMap<>();
-
-        for (final JsonElement moduleResource : moduleResources) {
-            final YangResource yangResource = toYangResource((JsonObject) moduleResource);
-            newYangResourcesModuleNameToContentMap.put(yangResource.getModuleName(), yangResource.getYangSource());
-        }
-        return newYangResourcesModuleNameToContentMap;
-    }
-
-    private static YangResource toYangResource(final JsonObject yangResourceAsJson) {
-        final YangResource yangResource = new YangResource();
-        yangResource.setModuleName(yangResourceAsJson.get("moduleName").getAsString());
-        yangResource.setRevision(yangResourceAsJson.get("revision").getAsString());
-        yangResource.setYangSource(yangResourceAsJson.get("yangSource").getAsString());
-        return yangResource;
-    }
-
-    private static List<ModuleReference> toModuleReferences(
-            final ResponseEntity<String> dmiFetchModulesResponseEntity) {
-        final List<ModuleReference> moduleReferences = new ArrayList<>();
-        final JsonObject bodyAsJsonObject = new Gson().fromJson(dmiFetchModulesResponseEntity.getBody(),
-            JsonObject.class);
-        final JsonArray moduleReferencesAsJson = bodyAsJsonObject.getAsJsonArray("schemas");
-        for (final JsonElement moduleReferenceAsJson : moduleReferencesAsJson) {
-            final ModuleReference moduleReference = toModuleReference((JsonObject) moduleReferenceAsJson);
-            moduleReferences.add(moduleReference);
-        }
-        return moduleReferences;
-    }
-
-    private static ModuleReference toModuleReference(final JsonObject moduleReferenceAsJson) {
-        final ModuleReference moduleReference = new ModuleReference();
-        moduleReference.setModuleName(moduleReferenceAsJson.get("moduleName").getAsString());
-        moduleReference.setRevision(moduleReferenceAsJson.get("revision").getAsString());
-        return moduleReference;
-    }
 }