Link the existing CommissioningController with the generated code 57/132257/5
authorFrancescoFioraEst <francesco.fiora@est.tech>
Tue, 15 Nov 2022 17:03:34 +0000 (17:03 +0000)
committerFrancesco Fiora <francesco.fiora@est.tech>
Fri, 18 Nov 2022 08:57:36 +0000 (08:57 +0000)
Link the existing CommissioningController
endpoint implementation code with the generated code in Acm.

Issue-ID: POLICY-4454
Change-Id: Ie10296b6af8c8bfdbfa7f54714b22ca4804a2eef
Signed-off-by: FrancescoFioraEst <francesco.fiora@est.tech>
25 files changed:
models/src/main/java/org/onap/policy/clamp/models/acm/messages/rest/commissioning/CommissioningResponse.java
models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/AcDefinitionProvider.java [new file with mode: 0644]
models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/AutomationCompositionProvider.java
models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/ParticipantProvider.java
models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/ServiceTemplateProvider.java [deleted file]
models/src/main/java/org/onap/policy/clamp/models/acm/utils/AcmUtils.java
models/src/test/java/org/onap/policy/clamp/models/acm/persistence/provider/AcDefinitionProviderTest.java [moved from models/src/test/java/org/onap/policy/clamp/models/acm/persistence/provider/ServiceTemplateProviderTest.java with 50% similarity]
models/src/test/java/org/onap/policy/clamp/models/acm/utils/AcmUtilsTest.java
packages/policy-clamp-tarball/src/main/resources/etc/AcRuntimeParameters.yaml
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/commissioning/CommissioningProvider.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/instantiation/AutomationCompositionInstantiationProvider.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/main/rest/CommissioningController.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/main/web/AbstractRestController.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/supervision/SupervisionHandler.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/supervision/SupervisionScanner.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/supervision/comm/AutomationCompositionUpdatePublisher.java
runtime-acm/src/main/java/org/onap/policy/clamp/acm/runtime/supervision/comm/ParticipantUpdatePublisher.java
runtime-acm/src/main/resources/application.yaml
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/commissioning/CommissioningProviderTest.java
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/commissioning/rest/CommissioningControllerTest.java
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/instantiation/AutomationCompositionInstantiationProviderTest.java
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/instantiation/rest/InstantiationControllerTest.java
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/supervision/SupervisionHandlerTest.java
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/supervision/SupervisionScannerTest.java
runtime-acm/src/test/java/org/onap/policy/clamp/acm/runtime/supervision/comm/SupervisionMessagesTest.java

index 42ce798..9f6736d 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021-2022 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@
 package org.onap.policy.clamp.models.acm.messages.rest.commissioning;
 
 import java.util.List;
+import java.util.UUID;
 import lombok.Getter;
 import lombok.Setter;
 import lombok.ToString;
@@ -34,5 +35,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 @Setter
 @ToString(callSuper = true)
 public class CommissioningResponse extends SimpleResponse {
+    private UUID compositionId;
+
     private List<ToscaConceptIdentifier> affectedAutomationCompositionDefinitions;
 }
diff --git a/models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/AcDefinitionProvider.java b/models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/AcDefinitionProvider.java
new file mode 100644 (file)
index 0000000..5740207
--- /dev/null
@@ -0,0 +1,132 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2021-2022 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.clamp.models.acm.persistence.provider;
+
+import java.util.List;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import lombok.RequiredArgsConstructor;
+import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionDefinition;
+import org.onap.policy.clamp.models.acm.persistence.concepts.JpaAutomationCompositionDefinition;
+import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionDefinitionRepository;
+import org.onap.policy.clamp.models.acm.persistence.repository.ToscaServiceTemplateRepository;
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional
+@RequiredArgsConstructor
+public class AcDefinitionProvider {
+
+    private final ToscaServiceTemplateRepository serviceTemplateRepository;
+    private final AutomationCompositionDefinitionRepository acmDefinitionRepository;
+
+    /**
+     * Create Automation Composition Definition.
+     *
+     * @param serviceTemplate the service template to be created
+     * @return the created ACM Definition
+     */
+    public AutomationCompositionDefinition createAutomationCompositionDefinition(
+            final ToscaServiceTemplate serviceTemplate) {
+        var acmDefinition = new AutomationCompositionDefinition();
+        acmDefinition.setCompositionId(UUID.randomUUID());
+        acmDefinition.setServiceTemplate(serviceTemplate);
+        var result = acmDefinitionRepository.save(new JpaAutomationCompositionDefinition(acmDefinition));
+        return result.toAuthorative();
+    }
+
+    /**
+     * Update the ServiceTemplate.
+     *
+     * @param compositionId The UUID of the automation composition definition to delete
+     * @param serviceTemplate the service template to be created
+     */
+    public void updateServiceTemplate(UUID compositionId, ToscaServiceTemplate serviceTemplate) {
+        var jpaServiceTemplate =
+                ProviderUtils.getJpaAndValidate(serviceTemplate, JpaToscaServiceTemplate::new, "toscaServiceTemplate");
+        serviceTemplateRepository.save(jpaServiceTemplate);
+    }
+
+    /**
+     * Delete Automation Composition Definition.
+     *
+     * @param compositionId The UUID of the automation composition definition to delete
+     * @return the TOSCA service template that was deleted
+     */
+    public ToscaServiceTemplate deleteAcDefintion(UUID compositionId) {
+        var jpaDelete = acmDefinitionRepository.findById(compositionId.toString());
+        if (jpaDelete.isEmpty()) {
+            String errorMessage = "delete of Automation Composition Definition \"" + compositionId
+                    + "\" failed, Automation Composition Definition does not exist";
+            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
+        }
+
+        var item = jpaDelete.get().getServiceTemplate();
+        serviceTemplateRepository.deleteById(item.getKey());
+        acmDefinitionRepository.deleteById(compositionId.toString());
+        return item.toAuthorative();
+    }
+
+    /**
+     * Get the requested automation composition definitions.
+     *
+     * @param compositionId The UUID of the automation composition definition to delete
+     * @return the automation composition definition
+     */
+    @Transactional(readOnly = true)
+    public ToscaServiceTemplate getAcDefinition(UUID compositionId) {
+        var jpaGet = acmDefinitionRepository.findById(compositionId.toString());
+        if (jpaGet.isEmpty()) {
+            String errorMessage =
+                    "Get serviceTemplate \"" + compositionId + "\" failed, serviceTemplate does not exist";
+            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, errorMessage);
+        }
+        return jpaGet.get().getServiceTemplate().toAuthorative();
+    }
+
+    /**
+     * Get service templates.
+     *
+     * @return the topology templates found
+     */
+    @Transactional(readOnly = true)
+    public List<ToscaServiceTemplate> getAllServiceTemplates() {
+        var jpaList = serviceTemplateRepository.findAll();
+        return ProviderUtils.asEntityList(jpaList);
+    }
+
+    /**
+     * Get service templates.
+     *
+     * @param name the name of the topology template to get, set to null to get all service templates
+     * @param version the version of the service template to get, set to null to get all service templates
+     * @return the topology templates found
+     */
+    @Transactional(readOnly = true)
+    public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version) {
+        var jpaList = serviceTemplateRepository.getFiltered(JpaToscaServiceTemplate.class, name, version);
+        return ProviderUtils.asEntityList(jpaList);
+    }
+}
index 5ee7d02..c4f8b91 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021-2022 Nordix Foundation.
  * ================================================================================
  * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
@@ -189,7 +189,7 @@ public class AutomationCompositionProvider {
         if (jpaDeleteAutomationComposition.isEmpty()) {
             String errorMessage = "delete of automation composition \"" + automationCompositionKey.getId()
                 + "\" failed, automation composition does not exist";
-            throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage);
+            throw new PfModelException(Response.Status.NOT_FOUND, errorMessage);
         }
 
         automationCompositionRepository.deleteById(automationCompositionKey);
index 1f9e07f..6e3b56d 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021-2022 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -51,10 +51,9 @@ public class ParticipantProvider {
      * @param name the name of the participant to get, null to get all participants
      * @param version the version of the participant to get, null to get all participants
      * @return the participants found
-     * @throws PfModelException on errors getting participants
      */
     @Transactional(readOnly = true)
-    public List<Participant> getParticipants(final String name, final String version) throws PfModelException {
+    public List<Participant> getParticipants(final String name, final String version) {
 
         return ProviderUtils.asEntityList(participantRepository.getFiltered(JpaParticipant.class, name, version));
     }
@@ -63,10 +62,9 @@ public class ParticipantProvider {
      * Get all participants.
      *
      * @return the participants found
-     * @throws PfModelException on errors getting policies
      */
     @Transactional(readOnly = true)
-    public List<Participant> getParticipants() throws PfModelException {
+    public List<Participant> getParticipants() {
         return ProviderUtils.asEntityList(participantRepository.findAll());
     }
 
@@ -93,11 +91,9 @@ public class ParticipantProvider {
      *
      * @param filter the filter for the participants to get
      * @return the participants found
-     * @throws PfModelException on errors getting policies
      */
     @Transactional(readOnly = true)
-    public List<Participant> getFilteredParticipants(@NonNull final ToscaTypedEntityFilter<Participant> filter)
-            throws PfModelException {
+    public List<Participant> getFilteredParticipants(@NonNull final ToscaTypedEntityFilter<Participant> filter) {
 
         return filter.filter(ProviderUtils.asEntityList(
                 participantRepository.getFiltered(JpaParticipant.class, filter.getName(), filter.getVersion())));
diff --git a/models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/ServiceTemplateProvider.java b/models/src/main/java/org/onap/policy/clamp/models/acm/persistence/provider/ServiceTemplateProvider.java
deleted file mode 100644 (file)
index 4661c74..0000000
+++ /dev/null
@@ -1,230 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2021-2022 Nordix Foundation.
- * ================================================================================
- * 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.clamp.models.acm.persistence.provider;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import lombok.RequiredArgsConstructor;
-import org.onap.policy.clamp.models.acm.persistence.repository.ToscaServiceTemplateRepository;
-import org.onap.policy.models.base.PfConceptKey;
-import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service
-@Transactional
-@RequiredArgsConstructor
-public class ServiceTemplateProvider {
-
-    private final ToscaServiceTemplateRepository serviceTemplateRepository;
-
-    /**
-     * Create service template.
-     *
-     * @param serviceTemplate the service template to be created
-     * @return the created service template
-     * @throws PfModelException on errors creating the service template
-     */
-    public ToscaServiceTemplate createServiceTemplate(final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        try {
-            var result = serviceTemplateRepository.save(ProviderUtils.getJpaAndValidate(serviceTemplate,
-                    JpaToscaServiceTemplate::new, "toscaServiceTemplate"));
-            return result.toAuthorative();
-        } catch (IllegalArgumentException e) {
-            throw new PfModelException(Status.BAD_REQUEST, "Error in save serviceTemplate", e);
-        }
-    }
-
-    /**
-     * Delete service template.
-     *
-     * @param name the name of the service template to delete.
-     * @param version the version of the service template to delete.
-     * @return the TOSCA service template that was deleted
-     * @throws PfModelException on errors deleting policy types
-     */
-    public ToscaServiceTemplate deleteServiceTemplate(final String name, final String version) throws PfModelException {
-        var serviceTemplateKey = new PfConceptKey(name, version);
-        var jpaDelete = serviceTemplateRepository.findById(serviceTemplateKey);
-        if (jpaDelete.isEmpty()) {
-            String errorMessage = "delete of serviceTemplate \"" + serviceTemplateKey.getId()
-                    + "\" failed, serviceTemplate does not exist";
-            throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage);
-        }
-        serviceTemplateRepository.deleteById(serviceTemplateKey);
-        return jpaDelete.get().toAuthorative();
-    }
-
-    /**
-     * Get the requested automation composition definitions.
-     *
-     * @param name the name of the definition to get, null for all definitions
-     * @param version the version of the definition to get, null for all definitions
-     * @return the automation composition definitions
-     * @throws PfModelException on errors getting automation composition definitions
-     */
-    @Transactional(readOnly = true)
-    public ToscaServiceTemplate getToscaServiceTemplate(String name, String version) throws PfModelException {
-        var serviceTemplateKey = new PfConceptKey(name, version);
-        var jpaServiceTemplates = serviceTemplateRepository.findById(serviceTemplateKey);
-        if (jpaServiceTemplates.isEmpty()) {
-            throw new PfModelException(Status.NOT_FOUND, "Automation composition definitions not found");
-        }
-        return jpaServiceTemplates.get().toAuthorative();
-    }
-
-    /**
-     * Get service templates.
-     *
-     * @return the topology templates found
-     * @throws PfModelException on errors getting service templates
-     */
-    @Transactional(readOnly = true)
-    public List<ToscaServiceTemplate> getAllServiceTemplates() throws PfModelException {
-        var jpaList = serviceTemplateRepository.findAll();
-        return ProviderUtils.asEntityList(jpaList);
-    }
-
-    /**
-     * Get service templates.
-     *
-     * @param name the name of the topology template to get, set to null to get all service templates
-     * @param version the version of the service template to get, set to null to get all service templates
-     * @return the topology templates found
-     * @throws PfModelException on errors getting service templates
-     */
-    @Transactional(readOnly = true)
-    public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version)
-            throws PfModelException {
-        var jpaList = serviceTemplateRepository.getFiltered(JpaToscaServiceTemplate.class, name, version);
-        return ProviderUtils.asEntityList(jpaList);
-    }
-
-    /**
-     * Get the initial node types with common or instance properties.
-     *
-     * @param fullNodeTypes map of all the node types in the specified template
-     * @param common boolean to indicate whether common or instance properties are required
-     * @return node types map that only has common properties
-     */
-    private Map<String, ToscaNodeType> getInitialNodeTypesMap(Map<String, ToscaNodeType> fullNodeTypes,
-            boolean common) {
-
-        var tempNodeTypesMap = new HashMap<String, ToscaNodeType>();
-
-        fullNodeTypes.forEach((key, nodeType) -> {
-            var tempToscaNodeType = new ToscaNodeType();
-            tempToscaNodeType.setName(key);
-
-            var resultantPropertyMap = findCommonOrInstancePropsInNodeTypes(nodeType, common);
-
-            if (!resultantPropertyMap.isEmpty()) {
-                tempToscaNodeType.setProperties(resultantPropertyMap);
-                tempNodeTypesMap.put(key, tempToscaNodeType);
-            }
-        });
-        return tempNodeTypesMap;
-    }
-
-    private Map<String, ToscaProperty> findCommonOrInstancePropsInNodeTypes(ToscaNodeType nodeType, boolean common) {
-
-        var tempCommonPropertyMap = new HashMap<String, ToscaProperty>();
-        var tempInstancePropertyMap = new HashMap<String, ToscaProperty>();
-
-        nodeType.getProperties().forEach((propKey, prop) -> {
-
-            if (prop.getMetadata() != null) {
-                prop.getMetadata().forEach((k, v) -> {
-                    if (k.equals("common") && v.equals("true") && common) {
-                        tempCommonPropertyMap.put(propKey, prop);
-                    } else if (k.equals("common") && v.equals("false") && !common) {
-                        tempInstancePropertyMap.put(propKey, prop);
-                    }
-
-                });
-            } else {
-                tempInstancePropertyMap.put(propKey, prop);
-            }
-        });
-
-        if (tempCommonPropertyMap.isEmpty() && !common) {
-            return tempInstancePropertyMap;
-        } else {
-            return tempCommonPropertyMap;
-        }
-    }
-
-    /**
-     * Get the node types derived from those that have common properties.
-     *
-     * @param initialNodeTypes map of all the node types in the specified template
-     * @param filteredNodeTypes map of all the node types that have common or instance properties
-     * @return all node types that have common properties including their children
-     * @throws PfModelException on errors getting node type with common properties
-     */
-    private Map<String, ToscaNodeType> getFinalNodeTypesMap(Map<String, ToscaNodeType> initialNodeTypes,
-            Map<String, ToscaNodeType> filteredNodeTypes) {
-        for (var i = 0; i < initialNodeTypes.size(); i++) {
-            initialNodeTypes.forEach((key, nodeType) -> {
-                var tempToscaNodeType = new ToscaNodeType();
-                tempToscaNodeType.setName(key);
-
-                if (filteredNodeTypes.get(nodeType.getDerivedFrom()) != null) {
-                    tempToscaNodeType.setName(key);
-
-                    var finalProps = new HashMap<String, ToscaProperty>(
-                            filteredNodeTypes.get(nodeType.getDerivedFrom()).getProperties());
-
-                    tempToscaNodeType.setProperties(finalProps);
-                } else {
-                    return;
-                }
-                filteredNodeTypes.putIfAbsent(key, tempToscaNodeType);
-
-            });
-        }
-        return filteredNodeTypes;
-    }
-
-    /**
-     * Get the requested node types with common or instance properties.
-     *
-     * @param common boolean indicating common or instance properties
-     * @param serviceTemplate the ToscaServiceTemplate
-     * @return the node types with common or instance properties
-     * @throws PfModelException on errors getting node type properties
-     */
-    public Map<String, ToscaNodeType> getCommonOrInstancePropertiesFromNodeTypes(boolean common,
-            ToscaServiceTemplate serviceTemplate) throws PfModelException {
-        var tempNodeTypesMap = this.getInitialNodeTypesMap(serviceTemplate.getNodeTypes(), common);
-
-        return this.getFinalNodeTypesMap(serviceTemplate.getNodeTypes(), tempNodeTypesMap);
-
-    }
-}
index f54ecb4..283edd4 100644 (file)
 package org.onap.policy.clamp.models.acm.utils;
 
 import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
+import java.util.function.UnaryOperator;
+import java.util.stream.Collectors;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.collections4.MapUtils;
+import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementDefinition;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantDefinition;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantUpdates;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ObjectValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
+import org.onap.policy.common.parameters.ValidationStatus;
+import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
 
@@ -37,11 +53,11 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
  * Utility functions used in acm-runtime and participants.
  *
  */
-public class AcmUtils {
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class AcmUtils {
 
-    private AcmUtils() {
-        throw new IllegalStateException("Utility class");
-    }
+    private static final String AUTOMATION_COMPOSITION_NODE_TYPE = "org.onap.policy.clamp.acm.AutomationComposition";
+    public static final String ENTRY = "entry ";
 
     /**
      * Prepare participant updates map.
@@ -50,7 +66,7 @@ public class AcmUtils {
      * @param participantUpdates list of participantUpdates
      */
     public static void prepareParticipantUpdate(AutomationCompositionElement acElement,
-        List<ParticipantUpdates> participantUpdates) {
+            List<ParticipantUpdates> participantUpdates) {
         if (participantUpdates.isEmpty()) {
             participantUpdates.add(getAutomationCompositionElementList(acElement));
             return;
@@ -81,11 +97,11 @@ public class AcmUtils {
      * @param acElement automation composition element
      * @param toscaServiceTemplate ToscaServiceTemplate
      */
-    public static void setServiceTemplatePolicyInfo(AutomationCompositionElement acElement,
-        ToscaServiceTemplate toscaServiceTemplate) {
+    public static void setAcPolicyInfo(AutomationCompositionElement acElement,
+            ToscaServiceTemplate toscaServiceTemplate) {
         // Pass respective PolicyTypes or Policies as part of toscaServiceTemplateFragment
         if (toscaServiceTemplate.getPolicyTypes() == null
-            && toscaServiceTemplate.getToscaTopologyTemplate().getPolicies() == null) {
+                && toscaServiceTemplate.getToscaTopologyTemplate().getPolicies() == null) {
             return;
         }
         ToscaServiceTemplate toscaServiceTemplateFragment = new ToscaServiceTemplate();
@@ -107,8 +123,8 @@ public class AcmUtils {
      * @param commonPropertiesMap common properties map
      */
     public static void prepareParticipantDefinitionUpdate(ToscaConceptIdentifier acParticipantType, String entryKey,
-        ToscaNodeTemplate entryValue, List<ParticipantDefinition> participantDefinitionUpdates,
-        Map<String, ToscaNodeType> commonPropertiesMap) {
+            ToscaNodeTemplate entryValue, List<ParticipantDefinition> participantDefinitionUpdates,
+            Map<String, ToscaNodeType> commonPropertiesMap) {
 
         var acDefinition = new AutomationCompositionElementDefinition();
         acDefinition.setAcElementDefinitionId(new ToscaConceptIdentifier(entryKey, entryValue.getVersion()));
@@ -123,8 +139,8 @@ public class AcmUtils {
         List<AutomationCompositionElementDefinition> automationCompositionElementDefinitionList = new ArrayList<>();
 
         if (participantDefinitionUpdates.isEmpty()) {
-            participantDefinitionUpdates.add(
-                getParticipantDefinition(acDefinition, acParticipantType, automationCompositionElementDefinitionList));
+            participantDefinitionUpdates.add(getParticipantDefinition(acDefinition, acParticipantType,
+                    automationCompositionElementDefinitionList));
         } else {
             var participantExists = false;
             for (ParticipantDefinition participantDefinitionUpdate : participantDefinitionUpdates) {
@@ -135,18 +151,207 @@ public class AcmUtils {
             }
             if (!participantExists) {
                 participantDefinitionUpdates.add(getParticipantDefinition(acDefinition, acParticipantType,
-                    automationCompositionElementDefinitionList));
+                        automationCompositionElementDefinitionList));
             }
         }
     }
 
     private static ParticipantDefinition getParticipantDefinition(AutomationCompositionElementDefinition acDefinition,
-        ToscaConceptIdentifier acParticipantType,
-        List<AutomationCompositionElementDefinition> automationCompositionElementDefinitionList) {
+            ToscaConceptIdentifier acParticipantType,
+            List<AutomationCompositionElementDefinition> automationCompositionElementDefinitionList) {
         var participantDefinition = new ParticipantDefinition();
         participantDefinition.setParticipantType(acParticipantType);
         automationCompositionElementDefinitionList.add(acDefinition);
         participantDefinition.setAutomationCompositionElementDefinitionList(automationCompositionElementDefinitionList);
         return participantDefinition;
     }
+
+    /**
+     * Validate AutomationComposition.
+     *
+     * @param automationComposition AutomationComposition to validate
+     * @param serviceTemplate the service template
+     * @return the result of validation
+     */
+    public static BeanValidationResult validateAutomationComposition(AutomationComposition automationComposition,
+            ToscaServiceTemplate serviceTemplate) {
+        var result = new BeanValidationResult(ENTRY + automationComposition.getDefinition().getName(),
+                automationComposition);
+
+        var map = getMapToscaNodeTemplates(serviceTemplate);
+
+        var toscaNodeTemplate = map.get(new ToscaConceptIdentifier(automationComposition.getDefinition().getName(),
+                automationComposition.getDefinition().getVersion()));
+
+        if (toscaNodeTemplate == null || !AUTOMATION_COMPOSITION_NODE_TYPE.equals(toscaNodeTemplate.getType())) {
+            result.addResult(
+                    new ObjectValidationResult("AutomationComposition", automationComposition.getDefinition().getName(),
+                            ValidationStatus.INVALID, "Commissioned automation composition definition not found"));
+        } else {
+
+            var acElementDefinitions = getAutomationCompositionElementDefinitions(map, toscaNodeTemplate);
+
+            // @formatter:off
+            var definitions = acElementDefinitions
+                    .stream()
+                    .map(nodeTemplate -> nodeTemplate.getKey().asIdentifier())
+                    .collect(Collectors.toMap(ToscaConceptIdentifier::getName, UnaryOperator.identity()));
+            // @formatter:on
+
+            for (var element : automationComposition.getElements().values()) {
+                result.addResult(validateDefinition(definitions, element.getDefinition()));
+            }
+        }
+
+        return result;
+
+    }
+
+    private static ValidationResult validateDefinition(Map<String, ToscaConceptIdentifier> definitions,
+            ToscaConceptIdentifier definition) {
+        var result = new BeanValidationResult(ENTRY + definition.getName(), definition);
+        var identifier = definitions.get(definition.getName());
+        if (identifier == null) {
+            result.setResult(ValidationStatus.INVALID, "Not found");
+        } else if (!identifier.equals(definition)) {
+            result.setResult(ValidationStatus.INVALID, "Version not matching");
+        }
+        return (result.isClean() ? null : result);
+    }
+
+    private static Map<ToscaConceptIdentifier, ToscaNodeTemplate> getMapToscaNodeTemplates(
+            ToscaServiceTemplate serviceTemplate) {
+        if (serviceTemplate.getToscaTopologyTemplate() == null
+                || MapUtils.isEmpty(serviceTemplate.getToscaTopologyTemplate().getNodeTemplates())) {
+            return Map.of();
+        }
+        var list = serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().values();
+        return list.stream().collect(Collectors
+                .toMap(node -> new ToscaConceptIdentifier(node.getName(), node.getVersion()), Function.identity()));
+    }
+
+    private static List<ToscaNodeTemplate> getAutomationCompositionElementDefinitions(
+            Map<ToscaConceptIdentifier, ToscaNodeTemplate> map, ToscaNodeTemplate automationCompositionNodeTemplate) {
+
+        if (MapUtils.isEmpty(automationCompositionNodeTemplate.getProperties())) {
+            return Collections.emptyList();
+        }
+
+        @SuppressWarnings("unchecked")
+        var automationCompositionElements =
+                (List<Map<String, String>>) automationCompositionNodeTemplate.getProperties().get("elements");
+
+        if (CollectionUtils.isEmpty(automationCompositionElements)) {
+            return Collections.emptyList();
+        }
+
+        // @formatter:off
+        return automationCompositionElements
+                .stream()
+                .map(elementMap ->
+                    map.get(new ToscaConceptIdentifier(elementMap.get("name"), elementMap.get("version"))))
+                .collect(Collectors.toList());
+        // @formatter:on
+    }
+
+    /**
+     * Get the initial node types with common or instance properties.
+     *
+     * @param fullNodeTypes map of all the node types in the specified template
+     * @param common boolean to indicate whether common or instance properties are required
+     * @return node types map that only has common properties
+     */
+    private static Map<String, ToscaNodeType> getInitialNodeTypesMap(Map<String, ToscaNodeType> fullNodeTypes,
+            boolean common) {
+
+        var tempNodeTypesMap = new HashMap<String, ToscaNodeType>();
+
+        fullNodeTypes.forEach((key, nodeType) -> {
+            var tempToscaNodeType = new ToscaNodeType();
+            tempToscaNodeType.setName(key);
+
+            var resultantPropertyMap = findCommonOrInstancePropsInNodeTypes(nodeType, common);
+
+            if (!resultantPropertyMap.isEmpty()) {
+                tempToscaNodeType.setProperties(resultantPropertyMap);
+                tempNodeTypesMap.put(key, tempToscaNodeType);
+            }
+        });
+        return tempNodeTypesMap;
+    }
+
+    private static Map<String, ToscaProperty> findCommonOrInstancePropsInNodeTypes(ToscaNodeType nodeType,
+            boolean common) {
+
+        var tempCommonPropertyMap = new HashMap<String, ToscaProperty>();
+        var tempInstancePropertyMap = new HashMap<String, ToscaProperty>();
+
+        nodeType.getProperties().forEach((propKey, prop) -> {
+
+            if (prop.getMetadata() != null) {
+                prop.getMetadata().forEach((k, v) -> {
+                    if (k.equals("common") && v.equals("true") && common) {
+                        tempCommonPropertyMap.put(propKey, prop);
+                    } else if (k.equals("common") && v.equals("false") && !common) {
+                        tempInstancePropertyMap.put(propKey, prop);
+                    }
+
+                });
+            } else {
+                tempInstancePropertyMap.put(propKey, prop);
+            }
+        });
+
+        if (tempCommonPropertyMap.isEmpty() && !common) {
+            return tempInstancePropertyMap;
+        } else {
+            return tempCommonPropertyMap;
+        }
+    }
+
+    /**
+     * Get the node types derived from those that have common properties.
+     *
+     * @param initialNodeTypes map of all the node types in the specified template
+     * @param filteredNodeTypes map of all the node types that have common or instance properties
+     * @return all node types that have common properties including their children
+     * @throws PfModelException on errors getting node type with common properties
+     */
+    private static Map<String, ToscaNodeType> getFinalNodeTypesMap(Map<String, ToscaNodeType> initialNodeTypes,
+            Map<String, ToscaNodeType> filteredNodeTypes) {
+        for (var i = 0; i < initialNodeTypes.size(); i++) {
+            initialNodeTypes.forEach((key, nodeType) -> {
+                var tempToscaNodeType = new ToscaNodeType();
+                tempToscaNodeType.setName(key);
+
+                if (filteredNodeTypes.get(nodeType.getDerivedFrom()) != null) {
+                    tempToscaNodeType.setName(key);
+
+                    var finalProps = new HashMap<String, ToscaProperty>(
+                            filteredNodeTypes.get(nodeType.getDerivedFrom()).getProperties());
+
+                    tempToscaNodeType.setProperties(finalProps);
+                } else {
+                    return;
+                }
+                filteredNodeTypes.putIfAbsent(key, tempToscaNodeType);
+
+            });
+        }
+        return filteredNodeTypes;
+    }
+
+    /**
+     * Get the requested node types with common or instance properties.
+     *
+     * @param common boolean indicating common or instance properties
+     * @param serviceTemplate the ToscaServiceTemplate
+     * @return the node types with common or instance properties
+     */
+    public static Map<String, ToscaNodeType> getCommonOrInstancePropertiesFromNodeTypes(boolean common,
+            ToscaServiceTemplate serviceTemplate) {
+        var tempNodeTypesMap = getInitialNodeTypesMap(serviceTemplate.getNodeTypes(), common);
+
+        return getFinalNodeTypesMap(serviceTemplate.getNodeTypes(), tempNodeTypesMap);
+    }
 }
@@ -22,7 +22,6 @@ package org.onap.policy.clamp.models.acm.persistence.provider;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
@@ -30,18 +29,21 @@ import static org.mockito.Mockito.when;
 
 import java.util.List;
 import java.util.Optional;
+import java.util.UUID;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
+import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionDefinition;
+import org.onap.policy.clamp.models.acm.persistence.concepts.JpaAutomationCompositionDefinition;
+import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionDefinitionRepository;
 import org.onap.policy.clamp.models.acm.persistence.repository.ToscaServiceTemplateRepository;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardYamlCoder;
 import org.onap.policy.common.utils.resources.ResourceUtils;
-import org.onap.policy.models.base.PfConceptKey;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
 
-class ServiceTemplateProviderTest {
+class AcDefinitionProviderTest {
 
     private static final String TOSCA_SERVICE_TEMPLATE_YAML = "clamp/acm/pmsh/funtional-pmsh-usecase.yaml";
 
@@ -54,98 +56,70 @@ class ServiceTemplateProviderTest {
         inputServiceTemplate = getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML);
     }
 
-    @Test
-    void testGetCommonOrInstancePropertiesFromNodeTypes() throws PfModelException {
-        var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
-
-        var result = serviceTemplateProvider.getCommonOrInstancePropertiesFromNodeTypes(true, inputServiceTemplate);
-        assertNotNull(result);
-        assertThat(result).hasSize(6);
-    }
-
     @Test
     void testCreateServiceTemplate() throws PfModelException {
-        var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
+        var acmDefinitionRepository = mock(AutomationCompositionDefinitionRepository.class);
 
         var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new,
-            "toscaServiceTemplate");
-        when(serviceTemplateRepository.save(jpaServiceTemplate)).thenReturn(jpaServiceTemplate);
+                "toscaServiceTemplate");
+        var acmDefinition = new AutomationCompositionDefinition();
+        acmDefinition.setCompositionId(UUID.randomUUID());
+        acmDefinition.setServiceTemplate(jpaServiceTemplate.toAuthorative());
 
-        var result = serviceTemplateProvider.createServiceTemplate(inputServiceTemplate);
+        when(acmDefinitionRepository.save(any(JpaAutomationCompositionDefinition.class)))
+                .thenReturn(new JpaAutomationCompositionDefinition(acmDefinition));
 
-        assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative());
-    }
-
-    @Test
-    void testDeleteServiceTemplate() throws PfModelException {
-        var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new,
-            "toscaServiceTemplate");
         var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
-        when(serviceTemplateRepository
-            .findById(new PfConceptKey(inputServiceTemplate.getName(), inputServiceTemplate.getVersion())))
-            .thenReturn(Optional.of(jpaServiceTemplate));
-
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
-        var result = serviceTemplateProvider.deleteServiceTemplate(inputServiceTemplate.getName(),
-            inputServiceTemplate.getVersion());
+        var acDefinitionProvider = new AcDefinitionProvider(serviceTemplateRepository, acmDefinitionRepository);
+        var result = acDefinitionProvider.createAutomationCompositionDefinition(inputServiceTemplate);
 
-        assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative());
+        assertThat(result.getServiceTemplate()).isEqualTo(jpaServiceTemplate.toAuthorative());
     }
 
     @Test
-    void testDeleteServiceTemplateEmpty() throws PfModelException {
+    void testDeleteAcDefintion() throws PfModelException {
         var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new,
-            "toscaServiceTemplate");
-        var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
-        when(serviceTemplateRepository
-            .findById(new PfConceptKey(inputServiceTemplate.getName(), inputServiceTemplate.getVersion())))
-            .thenReturn(Optional.empty());
-
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
-        assertThatThrownBy(() -> serviceTemplateProvider.deleteServiceTemplate(inputServiceTemplate.getName(),
-            inputServiceTemplate.getVersion()))
-            .hasMessage("delete of serviceTemplate \"NULL:0.0.0\" failed, serviceTemplate does not exist");
-    }
+                "toscaServiceTemplate");
+        var acmDefinition = new AutomationCompositionDefinition();
+        acmDefinition.setCompositionId(UUID.randomUUID());
+        acmDefinition.setServiceTemplate(jpaServiceTemplate.toAuthorative());
 
-    @Test
-    void testGetServiceTemplateListEmpty() {
         var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
-        when(serviceTemplateRepository.findById(any())).thenReturn(Optional.empty());
+        var acmDefinitionRepository = mock(AutomationCompositionDefinitionRepository.class);
+        when(acmDefinitionRepository.findById(acmDefinition.getCompositionId().toString()))
+                .thenReturn(Optional.of(new JpaAutomationCompositionDefinition(acmDefinition)));
+
+        var acDefinitionProvider = new AcDefinitionProvider(serviceTemplateRepository, acmDefinitionRepository);
+        var result = acDefinitionProvider.deleteAcDefintion(acmDefinition.getCompositionId());
 
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
-        assertThatThrownBy(() -> serviceTemplateProvider.getToscaServiceTemplate("Name", "1.0.0"))
-            .hasMessage("Automation composition definitions not found");
+        assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative());
     }
 
     @Test
-    void testGetServiceTemplateList() throws PfModelException {
-        var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new,
-            "toscaServiceTemplate");
+    void testDeleteServiceTemplateEmpty() throws PfModelException {
         var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
-        when(serviceTemplateRepository
-            .findById(new PfConceptKey(inputServiceTemplate.getName(), inputServiceTemplate.getVersion())))
-            .thenReturn(Optional.of(jpaServiceTemplate));
-
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
-        var result = serviceTemplateProvider.getToscaServiceTemplate(inputServiceTemplate.getName(),
-            inputServiceTemplate.getVersion());
-
-        assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative());
+        when(serviceTemplateRepository.findAll()).thenReturn(List.of());
+
+        var compositionId = UUID.randomUUID();
+        var acmDefinitionRepository = mock(AutomationCompositionDefinitionRepository.class);
+        var acDefinitionProvider = new AcDefinitionProvider(serviceTemplateRepository, acmDefinitionRepository);
+        assertThatThrownBy(() -> acDefinitionProvider.deleteAcDefintion(compositionId))
+                .hasMessage("delete of Automation Composition Definition \"" + compositionId
+                        + "\" failed, Automation Composition Definition does not exist");
     }
 
     @Test
     void testGetServiceTemplate() throws PfModelException {
         var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new,
-            "toscaServiceTemplate");
+                "toscaServiceTemplate");
         var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class);
         when(serviceTemplateRepository.getFiltered(JpaToscaServiceTemplate.class, inputServiceTemplate.getName(),
-            inputServiceTemplate.getVersion())).thenReturn(List.of(jpaServiceTemplate));
+                inputServiceTemplate.getVersion())).thenReturn(List.of(jpaServiceTemplate));
 
-        var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository);
-        var result = serviceTemplateProvider.getServiceTemplateList(inputServiceTemplate.getName(),
-            inputServiceTemplate.getVersion());
+        var acmDefinitionRepository = mock(AutomationCompositionDefinitionRepository.class);
+        var acDefinitionProvider = new AcDefinitionProvider(serviceTemplateRepository, acmDefinitionRepository);
+        var result = acDefinitionProvider.getServiceTemplateList(inputServiceTemplate.getName(),
+                inputServiceTemplate.getVersion());
 
         assertThat(result).hasSize(1);
         assertThat(result.get(0)).isEqualTo(jpaServiceTemplate.toAuthorative());
index 0e68593..ccb4b83 100644 (file)
@@ -23,6 +23,7 @@ package org.onap.policy.clamp.models.acm.utils;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 
 import java.util.ArrayList;
@@ -34,6 +35,8 @@ import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantDefinition;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantUpdates;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantUtils;
+import org.onap.policy.common.utils.coder.StandardYamlCoder;
+import org.onap.policy.common.utils.resources.ResourceUtils;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
@@ -46,7 +49,9 @@ class AcmUtilsTest {
 
     private final ToscaConceptIdentifier id = new ToscaConceptIdentifier("id", "1.0.0");
     private final ToscaConceptIdentifier idNode =
-        new ToscaConceptIdentifier("org.onap.dcae.acm.DCAEMicroserviceAutomationCompositionParticipant", "0.0.0");
+            new ToscaConceptIdentifier("org.onap.dcae.acm.DCAEMicroserviceAutomationCompositionParticipant", "0.0.0");
+    private static final StandardYamlCoder YAML_TRANSLATOR = new StandardYamlCoder();
+    private static final String TOSCA_SERVICE_TEMPLATE_YAML = "clamp/acm/pmsh/funtional-pmsh-usecase.yaml";
 
     @Test
     void testCommonUtilsParticipantUpdate() {
@@ -71,7 +76,7 @@ class AcmUtilsTest {
     void testCommonUtilsServiceTemplate() {
         var acElement = new AutomationCompositionElement();
         var toscaServiceTemplate = getDummyToscaServiceTemplate();
-        AcmUtils.setServiceTemplatePolicyInfo(acElement, toscaServiceTemplate);
+        AcmUtils.setAcPolicyInfo(acElement, toscaServiceTemplate);
         assertEquals(getDummyToscaDataTypeMap(), acElement.getToscaServiceTemplateFragment().getDataTypes());
     }
 
@@ -87,7 +92,7 @@ class AcmUtilsTest {
 
         checkParticipantDefinitionUpdate(toscaServiceTemplate, participantDefinitionUpdates);
         assertEquals(idNode, participantDefinitionUpdates.get(0).getAutomationCompositionElementDefinitionList().get(0)
-            .getAcElementDefinitionId());
+                .getAcElementDefinitionId());
     }
 
     @Test
@@ -96,10 +101,20 @@ class AcmUtilsTest {
         toscaServiceTemplate.setPolicyTypes(null);
         toscaServiceTemplate.getToscaTopologyTemplate().setPolicies(null);
         AutomationCompositionElement acElement = new AutomationCompositionElement();
-        AcmUtils.setServiceTemplatePolicyInfo(new AutomationCompositionElement(), toscaServiceTemplate);
+        AcmUtils.setAcPolicyInfo(new AutomationCompositionElement(), toscaServiceTemplate);
         assertNull(acElement.getToscaServiceTemplateFragment());
     }
 
+    @Test
+    void testGetCommonOrInstancePropertiesFromNodeTypes() throws Exception {
+        var inputServiceTemplate = YAML_TRANSLATOR
+                .decode(ResourceUtils.getResourceAsStream(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class);
+
+        var result = AcmUtils.getCommonOrInstancePropertiesFromNodeTypes(true, inputServiceTemplate);
+        assertNotNull(result);
+        assertThat(result).hasSize(6);
+    }
+
     private ToscaServiceTemplate getDummyToscaServiceTemplate() {
         var toscaServiceTemplate = new ToscaServiceTemplate();
         var policyTypes = getDummyPolicyTypesMap();
@@ -146,14 +161,14 @@ class AcmUtilsTest {
     }
 
     private void checkParticipantDefinitionUpdate(ToscaServiceTemplate toscaServiceTemplate,
-        List<ParticipantDefinition> participantDefinitionUpdates) {
+            List<ParticipantDefinition> participantDefinitionUpdates) {
 
         for (Map.Entry<String, ToscaNodeTemplate> toscaInputEntry : toscaServiceTemplate.getToscaTopologyTemplate()
-            .getNodeTemplates().entrySet()) {
+                .getNodeTemplates().entrySet()) {
             if (ParticipantUtils.checkIfNodeTemplateIsAutomationCompositionElement(toscaInputEntry.getValue(),
-                toscaServiceTemplate)) {
+                    toscaServiceTemplate)) {
                 AcmUtils.prepareParticipantDefinitionUpdate(id, toscaInputEntry.getKey(), toscaInputEntry.getValue(),
-                    participantDefinitionUpdates, null);
+                        participantDefinitionUpdates, null);
             }
         }
     }
index 8efca97..c4c68f4 100644 (file)
@@ -3,7 +3,7 @@ spring:
     user:
       name: runtimeUser
       password: zb!XztG34
-  http:
+  mvc:
     converters:
       preferred-json-mapper: gson
   datasource:
index 55d7b0c..c256488 100644 (file)
 
 package org.onap.policy.clamp.acm.runtime.commissioning;
 
-import java.util.ArrayList;
-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.ws.rs.core.Response.Status;
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.collections4.MapUtils;
-import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.clamp.acm.runtime.supervision.SupervisionHandler;
+import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
 import org.onap.policy.clamp.models.acm.concepts.Participant;
 import org.onap.policy.clamp.models.acm.messages.rest.commissioning.CommissioningResponse;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
-import org.onap.policy.common.utils.coder.Coder;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
+import org.onap.policy.clamp.models.acm.utils.AcmUtils;
+import org.onap.policy.common.parameters.BeanValidationResult;
 import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
+import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplates;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -56,51 +49,33 @@ import org.springframework.transaction.annotation.Transactional;
 @Transactional
 public class CommissioningProvider {
     public static final String AUTOMATION_COMPOSITION_NODE_TYPE = "org.onap.policy.clamp.acm.AutomationComposition";
-    private static final String HYPHEN = "-";
 
-    private final ServiceTemplateProvider serviceTemplateProvider;
+    private final AcDefinitionProvider acDefinitionProvider;
     private final AutomationCompositionProvider acProvider;
-    private static final Coder CODER = new StandardCoder();
     private final ParticipantProvider participantProvider;
     private final SupervisionHandler supervisionHandler;
 
     /**
      * Create a commissioning provider.
      *
-     * @param serviceTemplateProvider the ServiceTemplate Provider
+     * @param acDefinitionProvider the ServiceTemplate Provider
      * @param acProvider the AutomationComposition Provider
      * @param supervisionHandler the Supervision Handler
      * @param participantProvider the Participant Provider
      */
-    public CommissioningProvider(ServiceTemplateProvider serviceTemplateProvider,
+    public CommissioningProvider(AcDefinitionProvider acDefinitionProvider,
             AutomationCompositionProvider acProvider, SupervisionHandler supervisionHandler,
             ParticipantProvider participantProvider) {
-        this.serviceTemplateProvider = serviceTemplateProvider;
+        this.acDefinitionProvider = acDefinitionProvider;
         this.acProvider = acProvider;
         this.supervisionHandler = supervisionHandler;
         this.participantProvider = participantProvider;
     }
 
-    /**
-     * Create automation compositions from a service template.
-     *
-     * @param serviceTemplate the service template
-     * @return the result of the commissioning operation
-     * @throws PfModelException on creation errors
-     */
-    public CommissioningResponse createAutomationCompositionDefinitions(ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-
-        if (verifyIfInstancePropertiesExists()) {
-            throw new PfModelException(Status.BAD_REQUEST,
-                    "Delete instances, to commission automation composition definitions");
-        }
-        serviceTemplate = serviceTemplateProvider.createServiceTemplate(serviceTemplate);
-        List<Participant> participantList = participantProvider.getParticipants();
-        if (!participantList.isEmpty()) {
-            supervisionHandler.handleSendCommissionMessage(serviceTemplate.getName(), serviceTemplate.getVersion());
-        }
+    private CommissioningResponse createCommissioningResponse(UUID compositionId,
+            ToscaServiceTemplate serviceTemplate) {
         var response = new CommissioningResponse();
+        response.setCompositionId(compositionId);
         // @formatter:off
         response.setAffectedAutomationCompositionDefinitions(
             serviceTemplate.getToscaTopologyTemplate().getNodeTemplates()
@@ -114,201 +89,117 @@ public class CommissioningProvider {
     }
 
     /**
-     * Delete the automation composition definition with the given name and version.
+     * Create automation compositions from a service template.
      *
-     * @param name the name of the automation composition definition to delete
-     * @param version the version of the automation composition to delete
-     * @return the result of the deletion
-     * @throws PfModelException on deletion errors
+     * @param serviceTemplate the service template
+     * @return the result of the commissioning operation
      */
-    public CommissioningResponse deleteAutomationCompositionDefinition(String name, String version)
-            throws PfModelException {
+    public CommissioningResponse createAutomationCompositionDefinitions(ToscaServiceTemplate serviceTemplate) {
 
-        if (verifyIfInstancePropertiesExists()) {
-            throw new PfModelException(Status.BAD_REQUEST,
+        if (verifyIfDefinitionExists()) {
+            throw new PfModelRuntimeException(Status.BAD_REQUEST,
                     "Delete instances, to commission automation composition definitions");
         }
-        List<Participant> participantList = participantProvider.getParticipants();
+        var acmDefinition = acDefinitionProvider.createAutomationCompositionDefinition(serviceTemplate);
+        serviceTemplate = acmDefinition.getServiceTemplate();
+        var participantList = participantProvider.getParticipants();
         if (!participantList.isEmpty()) {
-            supervisionHandler.handleSendDeCommissionMessage();
+            supervisionHandler.handleSendCommissionMessage(serviceTemplate.getName(), serviceTemplate.getVersion());
         }
-        serviceTemplateProvider.deleteServiceTemplate(name, version);
-        var response = new CommissioningResponse();
-        response.setAffectedAutomationCompositionDefinitions(List.of(new ToscaConceptIdentifier(name, version)));
-
-        return response;
+        return createCommissioningResponse(acmDefinition.getCompositionId(), serviceTemplate);
     }
 
     /**
-     * Get automation composition node templates.
+     * Update Composition Definition.
      *
-     * @param acName the name of the automation composition, null for all
-     * @param acVersion the version of the automation composition, null for all
-     * @return list of automation composition node templates
-     * @throws PfModelException on errors getting automation composition definitions
+     * @param compositionId The UUID of the automation composition definition to update
+     * @param serviceTemplate the service template
+     * @return the result of the commissioning operation
      */
-    @Transactional(readOnly = true)
-    public List<ToscaNodeTemplate> getAutomationCompositionDefinitions(String acName, String acVersion)
-            throws PfModelException {
+    public CommissioningResponse updateCompositionDefinition(UUID compositionId, ToscaServiceTemplate serviceTemplate) {
+
+        var automationCompositions = acProvider.getAutomationCompositions();
+        var result = new BeanValidationResult("AutomationCompositions", automationCompositions);
+        for (var automationComposition : automationCompositions) {
+            if (!AutomationCompositionState.UNINITIALISED.equals(automationComposition.getState())) {
+                throw new PfModelRuntimeException(Status.BAD_REQUEST,
+                        "There is an Automation Composition instantioation with state in "
+                                + automationComposition.getState());
+            }
+            result.addResult(AcmUtils.validateAutomationComposition(automationComposition, serviceTemplate));
+        }
+        if (!result.isValid()) {
+            throw new PfModelRuntimeException(Status.BAD_REQUEST, "Service template non valid: " + result.getMessage());
+        }
 
-        // @formatter:off
-        ToscaTypedEntityFilter<ToscaNodeTemplate> nodeTemplateFilter = ToscaTypedEntityFilter
-                .<ToscaNodeTemplate>builder()
-                .name(acName)
-                .version(acVersion)
-                .type(AUTOMATION_COMPOSITION_NODE_TYPE)
-                .build();
-        // @formatter:on
+        acDefinitionProvider.updateServiceTemplate(compositionId, serviceTemplate);
 
-        return acProvider.getFilteredNodeTemplates(nodeTemplateFilter);
+        return createCommissioningResponse(compositionId, serviceTemplate);
     }
 
     /**
-     * Get the automation composition elements from a automation composition node template.
+     * Delete the automation composition definition with the given name and version.
      *
-     * @param automationCompositionNodeTemplate the automation composition node template
-     * @return a list of the automation composition element node templates in a automation composition node template
-     * @throws PfModelException on errors get automation composition element node templates
+     * @param compositionId The UUID of the automation composition definition to delete
+     * @return the result of the deletion
      */
-    @Transactional(readOnly = true)
-    public List<ToscaNodeTemplate> getAutomationCompositionElementDefinitions(
-            ToscaNodeTemplate automationCompositionNodeTemplate) throws PfModelException {
-        if (!AUTOMATION_COMPOSITION_NODE_TYPE.equals(automationCompositionNodeTemplate.getType())) {
-            return Collections.emptyList();
-        }
+    public CommissioningResponse deleteAutomationCompositionDefinition(UUID compositionId) {
 
-        if (MapUtils.isEmpty(automationCompositionNodeTemplate.getProperties())) {
-            return Collections.emptyList();
+        if (verifyIfInstanceExists()) {
+            throw new PfModelRuntimeException(Status.BAD_REQUEST,
+                    "Delete instances, to commission automation composition definitions");
         }
-
-        @SuppressWarnings("unchecked")
-        List<Map<String, String>> automationCompositionElements =
-                (List<Map<String, String>>) automationCompositionNodeTemplate.getProperties().get("elements");
-
-        if (CollectionUtils.isEmpty(automationCompositionElements)) {
-            return Collections.emptyList();
+        List<Participant> participantList = participantProvider.getParticipants();
+        if (!participantList.isEmpty()) {
+            supervisionHandler.handleSendDeCommissionMessage();
         }
-
-        List<ToscaNodeTemplate> automationCompositionElementList = new ArrayList<>();
-        // @formatter:off
-        automationCompositionElementList.addAll(
-                automationCompositionElements
-                        .stream()
-                        .map(elementMap -> acProvider.getNodeTemplates(elementMap.get("name"),
-                                elementMap.get("version")))
-                        .flatMap(List::stream)
-                        .collect(Collectors.toList())
-        );
-        // @formatter:on
-
-        return automationCompositionElementList;
+        var serviceTemplate = acDefinitionProvider.deleteAcDefintion(compositionId);
+        return createCommissioningResponse(compositionId, serviceTemplate);
     }
 
     /**
-     * Get the requested automation composition definitions.
+     * Get automation composition definition.
      *
-     * @param name the name of the definition to get, null for all definitions
-     * @param version the version of the definition to get, null for all definitions
-     * @return the automation composition definitions
+     * @param acName the name of the automation composition, null for all
+     * @param acVersion the version of the automation composition, null for all
+     * @return automation composition definition
      * @throws PfModelException on errors getting automation composition definitions
      */
     @Transactional(readOnly = true)
-    public ToscaServiceTemplate getToscaServiceTemplate(String name, String version) throws PfModelException {
-        return serviceTemplateProvider.getToscaServiceTemplate(name, version);
-    }
+    public ToscaServiceTemplates getAutomationCompositionDefinitions(String acName, String acVersion) {
 
-    /**
-     * Get All the requested automation composition definitions.
-     *
-     * @return the automation composition definitions
-     * @throws PfModelException on errors getting automation composition definitions
-     */
-    @Transactional(readOnly = true)
-    public List<ToscaServiceTemplate> getAllToscaServiceTemplate() throws PfModelException {
-        return serviceTemplateProvider.getAllServiceTemplates();
+        var result = new ToscaServiceTemplates();
+        result.setServiceTemplates(acDefinitionProvider.getServiceTemplateList(acName, acVersion));
+        return result;
     }
 
     /**
-     * Get the tosca service template with only required sections.
+     * Get automation composition definition.
      *
-     * @param name the name of the template to get, null for all definitions
-     * @param version the version of the template to get, null for all definitions
-     * @param instanceName automation composition name
-     * @return the tosca service template
-     * @throws PfModelException on errors getting tosca service template
+     * @param compositionId the compositionId
+     * @return automation composition definition
      */
     @Transactional(readOnly = true)
-    public String getToscaServiceTemplateReduced(
-            final String name, final String version, final String instanceName)
-            throws PfModelException {
-
-        var serviceTemplateList = serviceTemplateProvider.getServiceTemplateList(name, version);
-
-        List<ToscaServiceTemplate> filteredServiceTemplateList =
-                filterToscaNodeTemplateInstance(serviceTemplateList, instanceName);
-
-        if (filteredServiceTemplateList.isEmpty()) {
-            throw new PfModelException(Status.BAD_REQUEST, "Invalid Service Template");
-        }
-
-        ToscaServiceTemplate fullTemplate = filteredServiceTemplateList.get(0);
-
-        var template = new HashMap<String, Object>();
-        template.put("tosca_definitions_version", fullTemplate.getToscaDefinitionsVersion());
-        template.put("data_types", fullTemplate.getDataTypes());
-        template.put("policy_types", fullTemplate.getPolicyTypes());
-        template.put("node_types", fullTemplate.getNodeTypes());
-        template.put("topology_template", fullTemplate.getToscaTopologyTemplate());
-
-        try {
-            return CODER.encode(template);
+    public ToscaServiceTemplate getAutomationCompositionDefinitions(UUID compositionId) {
 
-        } catch (CoderException e) {
-            throw new PfModelException(Status.BAD_REQUEST, "Converion to Json Schema failed", e);
-        }
+        return acDefinitionProvider.getAcDefinition(compositionId);
     }
 
     /**
-     * Filters service templates if is not an instantiation type.
+     * Validates to see if there is any instance saved.
      *
-     * @param serviceTemplates tosca service template
-     * @param instanceName     automation composition name
-     * @return List of tosca service templates
+     * @return true if exists instance
      */
-    private List<ToscaServiceTemplate> filterToscaNodeTemplateInstance(
-            List<ToscaServiceTemplate> serviceTemplates, String instanceName) {
-
-        List<ToscaServiceTemplate> toscaServiceTemplates = new ArrayList<>();
-
-        serviceTemplates.forEach(serviceTemplate -> {
-
-            Map<String, ToscaNodeTemplate> toscaNodeTemplates = new HashMap<>();
-
-            serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().forEach((key, nodeTemplate) -> {
-                if (StringUtils.isNotEmpty(instanceName) && nodeTemplate.getName().contains(instanceName)) {
-                    toscaNodeTemplates.put(key, nodeTemplate);
-                } else if (!nodeTemplate.getName().contains(HYPHEN)) {
-                    toscaNodeTemplates.put(key, nodeTemplate);
-                }
-            });
-
-            serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().clear();
-            serviceTemplate.getToscaTopologyTemplate().setNodeTemplates(toscaNodeTemplates);
-
-            toscaServiceTemplates.add(serviceTemplate);
-        });
-
-        return toscaServiceTemplates;
+    private boolean verifyIfInstanceExists() {
+        return !acProvider.getAutomationCompositions().isEmpty();
     }
 
     /**
-     * Validates to see if there is any instance properties saved.
+     * Validates to see if there is any instance saved.
      *
-     * @return true if exists instance properties
+     * @return true if exists instance
      */
-    private boolean verifyIfInstancePropertiesExists() {
-        return acProvider.getAllNodeTemplates().stream()
-                .anyMatch(nodeTemplate -> nodeTemplate.getKey().getName().contains(HYPHEN));
-
+    private boolean verifyIfDefinitionExists() {
+        return !acDefinitionProvider.getAllServiceTemplates().isEmpty();
     }
 }
index 18fd1f9..df1f0ea 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021-2022 Nordix Foundation.
  * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,30 +25,27 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.function.Function;
-import java.util.function.UnaryOperator;
 import java.util.stream.Collectors;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
 import lombok.AllArgsConstructor;
-import org.onap.policy.clamp.acm.runtime.commissioning.CommissioningProvider;
 import org.onap.policy.clamp.acm.runtime.supervision.SupervisionHandler;
 import org.onap.policy.clamp.common.acm.exception.AutomationCompositionException;
 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
-import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
 import org.onap.policy.clamp.models.acm.concepts.Participant;
 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationCommand;
 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationResponse;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
+import org.onap.policy.clamp.models.acm.utils.AcmUtils;
 import org.onap.policy.common.parameters.BeanValidationResult;
 import org.onap.policy.common.parameters.ObjectValidationResult;
-import org.onap.policy.common.parameters.ValidationResult;
 import org.onap.policy.common.parameters.ValidationStatus;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -62,9 +59,9 @@ public class AutomationCompositionInstantiationProvider {
     private static final String AUTOMATION_COMPOSITION_NODE_ELEMENT_TYPE = "AutomationCompositionElement";
 
     private final AutomationCompositionProvider automationCompositionProvider;
-    private final CommissioningProvider commissioningProvider;
     private final SupervisionHandler supervisionHandler;
     private final ParticipantProvider participantProvider;
+    private final AcDefinitionProvider acDefinitionProvider;
     private static final String ENTRY = "entry ";
 
     /**
@@ -126,66 +123,24 @@ public class AutomationCompositionInstantiationProvider {
      * @return the result of validation
      * @throws PfModelException if automationCompositions is not valid
      */
-    private BeanValidationResult validateAutomationCompositions(AutomationCompositions automationCompositions)
-        throws PfModelException {
+    private BeanValidationResult validateAutomationCompositions(AutomationCompositions automationCompositions) {
 
         var result = new BeanValidationResult("AutomationCompositions", automationCompositions);
+        var serviceTemplates = acDefinitionProvider.getAllServiceTemplates();
+        if (serviceTemplates.isEmpty()) {
+            result.addResult(new ObjectValidationResult("ServiceTemplate", "", ValidationStatus.INVALID,
+                    "Commissioned automation composition definition not found"));
+            return result;
+        }
 
-        for (AutomationComposition automationComposition : automationCompositions.getAutomationCompositionList()) {
-            var subResult = new BeanValidationResult(ENTRY + automationComposition.getDefinition().getName(),
-                automationComposition);
-
-            List<ToscaNodeTemplate> toscaNodeTemplates = commissioningProvider.getAutomationCompositionDefinitions(
-                automationComposition.getDefinition().getName(), automationComposition.getDefinition().getVersion());
-
-            if (toscaNodeTemplates.isEmpty()) {
-                subResult.addResult(
-                    new ObjectValidationResult("AutomationComposition", automationComposition.getDefinition().getName(),
-                        ValidationStatus.INVALID, "Commissioned automation composition definition not found"));
-            } else if (toscaNodeTemplates.size() > 1) {
-                subResult.addResult(
-                    new ObjectValidationResult("AutomationComposition", automationComposition.getDefinition().getName(),
-                        ValidationStatus.INVALID, "Commissioned automation composition definition not valid"));
-            } else {
-
-                List<ToscaNodeTemplate> acElementDefinitions =
-                    commissioningProvider.getAutomationCompositionElementDefinitions(toscaNodeTemplates.get(0));
-
-                // @formatter:off
-                Map<String, ToscaConceptIdentifier> definitions = acElementDefinitions
-                        .stream()
-                        .map(nodeTemplate -> nodeTemplate.getKey().asIdentifier())
-                        .collect(Collectors.toMap(ToscaConceptIdentifier::getName, UnaryOperator.identity()));
-                // @formatter:on
+        var serviceTemplate = acDefinitionProvider.getAllServiceTemplates().get(0);
 
-                for (AutomationCompositionElement element : automationComposition.getElements().values()) {
-                    subResult.addResult(validateDefinition(definitions, element.getDefinition()));
-                }
-            }
-            result.addResult(subResult);
+        for (var automationComposition : automationCompositions.getAutomationCompositionList()) {
+            result.addResult(AcmUtils.validateAutomationComposition(automationComposition, serviceTemplate));
         }
         return result;
     }
 
-    /**
-     * Validate ToscaConceptIdentifier, checking if exist in ToscaConceptIdentifiers map.
-     *
-     * @param definitions map of all ToscaConceptIdentifiers
-     * @param definition ToscaConceptIdentifier to validate
-     * @return the validation result
-     */
-    private ValidationResult validateDefinition(Map<String, ToscaConceptIdentifier> definitions,
-        ToscaConceptIdentifier definition) {
-        var result = new BeanValidationResult(ENTRY + definition.getName(), definition);
-        ToscaConceptIdentifier identifier = definitions.get(definition.getName());
-        if (identifier == null) {
-            result.setResult(ValidationStatus.INVALID, "Not found");
-        } else if (!identifier.equals(definition)) {
-            result.setResult(ValidationStatus.INVALID, "Version not matching");
-        }
-        return (result.isClean() ? null : result);
-    }
-
     /**
      * Delete the automation composition with the given name and version.
      *
index fef1e6d..5a24db9 100644 (file)
 
 package org.onap.policy.clamp.acm.runtime.main.rest;
 
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import io.swagger.annotations.Authorization;
-import io.swagger.annotations.Extension;
-import io.swagger.annotations.ExtensionProperty;
-import io.swagger.annotations.ResponseHeader;
-import java.util.List;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.enums.ParameterIn;
 import java.util.UUID;
 import lombok.RequiredArgsConstructor;
 import org.onap.policy.clamp.acm.runtime.commissioning.CommissioningProvider;
 import org.onap.policy.clamp.acm.runtime.main.web.AbstractRestController;
 import org.onap.policy.clamp.models.acm.messages.rest.commissioning.CommissioningResponse;
 import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplates;
 import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestHeader;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -52,262 +47,118 @@ import org.springframework.web.bind.annotation.RestController;
  */
 @RestController
 @RequiredArgsConstructor
-public class CommissioningController extends AbstractRestController {
-
-    private static final String TAGS = "Clamp Automation Composition Commissioning API";
+public class CommissioningController extends AbstractRestController implements AutomationCompositionDefinitionApi {
 
     private final CommissioningProvider provider;
 
     /**
      * Creates a automation composition definition.
      *
-     * @param requestId request ID used in ONAP logging
      * @param body the body of automation composition following TOSCA definition
+     * @param requestId request ID used in ONAP logging
      * @return a response
-     * @throws PfModelException on errors creating a automation composition definition
      */
+    @Override
     // @formatter:off
     @PostMapping(value = "/commission",
             consumes = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML},
             produces = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML})
-    @ApiOperation(
-        value = "Commissions automation composition definitions",
-        notes = "Commissions automation composition definitions, returning commissioned definition IDs",
-        response = CommissioningResponse.class,
-        tags = {TAGS},
-        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
-        responseHeaders = {
-            @ResponseHeader(
-                name = VERSION_MINOR_NAME,
-                description = VERSION_MINOR_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(
-                name = VERSION_PATCH_NAME,
-                description = VERSION_PATCH_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(
-                name = VERSION_LATEST_NAME,
-                description = VERSION_LATEST_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(
-                name = REQUEST_ID_NAME,
-                description = REQUEST_ID_HDR_DESCRIPTION,
-                response = UUID.class)
-        },
-        extensions = {
-            @Extension
-                (
-                    name = EXTENSION_NAME,
-                    properties = {
-                        @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
-                        @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
-                    }
-                )
-        }
-    )
-    @ApiResponses(
-            value = {
-                @ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE),
-                @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE),
-                @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)
-            }
-    )
     // @formatter:on
-    public ResponseEntity<CommissioningResponse> create(
-        @RequestHeader(name = REQUEST_ID_NAME, required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
-        @ApiParam(
-            value = "Entity Body of Automation Composition",
-            required = true) @RequestBody ToscaServiceTemplate body)
-        throws PfModelException {
+    public ResponseEntity<CommissioningResponse> createCompositionDefinitions(
+            @Parameter(
+                    description = "Entity Body of Automation Composition",
+                    required = true) @RequestBody ToscaServiceTemplate body,
+            @RequestHeader(name = REQUEST_ID_NAME, required = false) @Parameter(
+                    description = REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
 
-        return ResponseEntity.ok().body(provider.createAutomationCompositionDefinitions(body));
+        var response = provider.createAutomationCompositionDefinitions(body);
+        return ResponseEntity.created(createUri("/commission/" + response.getCompositionId())).body(response);
     }
 
     /**
      * Deletes a automation composition definition.
      *
      * @param requestId request ID used in ONAP logging
-     * @param name the name of the automation composition definition to delete
-     * @param version the version of the automation composition definition to delete
+     * @param compositionId The UUID of the automation composition definition to delete
      * @return a response
-     * @throws PfModelException on errors deleting a automation composition definition
      */
+    @Override
     // @formatter:off
-    @DeleteMapping(value = "/commission",
+    @DeleteMapping(value = "/commission/{compositionId}",
             produces = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML})
-    @ApiOperation(value = "Delete a commissioned automation composition",
-        notes = "Deletes a Commissioned Automation Composition, returning optional error details",
-        response = CommissioningResponse.class,
-        tags = {TAGS},
-        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
-        responseHeaders = {
-            @ResponseHeader(
-                name = VERSION_MINOR_NAME,
-                description = VERSION_MINOR_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(
-                name = VERSION_PATCH_NAME,
-                description = VERSION_PATCH_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(
-                name = VERSION_LATEST_NAME,
-                description = VERSION_LATEST_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(
-                name = REQUEST_ID_NAME,
-                description = REQUEST_ID_HDR_DESCRIPTION,
-                response = UUID.class)},
-        extensions = {
-            @Extension
-                (
-                    name = EXTENSION_NAME,
-                    properties = {
-                        @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
-                        @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
-                    }
-                )
-        }
-    )
-    @ApiResponses(
-        value = {
-            @ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE),
-            @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE),
-            @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)
-        }
-    )
     // @formatter:on
-    public ResponseEntity<CommissioningResponse> delete(
-        @RequestHeader(name = REQUEST_ID_NAME, required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
-        @ApiParam(value = "Automation composition  definition name", required = true) @RequestParam(
-            value = "name") String name,
-        @ApiParam(
-            value = "Automation composition  definition version",
-            required = true) @RequestParam("version") String version)
-        throws PfModelException {
+    public ResponseEntity<CommissioningResponse> deleteCompositionDefinition(
+            @Parameter(
+                    in = ParameterIn.PATH,
+                    description = "The UUID of the automation composition definition to delete",
+                    required = true) @PathVariable("compositionId") UUID compositionId,
+            @RequestHeader(name = REQUEST_ID_NAME, required = false) @Parameter(
+                    description = REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
 
-        return ResponseEntity.ok().body(provider.deleteAutomationCompositionDefinition(name, version));
+        return ResponseEntity.ok().body(provider.deleteAutomationCompositionDefinition(compositionId));
     }
 
     /**
      * Queries details of all or specific automation composition definitions.
      *
-     * @param requestId request ID used in ONAP logging
      * @param name the name of the automation composition definition to get, null for all definitions
      * @param version the version of the automation composition definition to get, null for all definitions
+     * @param requestId request ID used in ONAP logging
      * @return the automation composition definitions
      * @throws PfModelException on errors getting details of all or specific automation composition definitions
      */
+    @Override
     // @formatter:off
     @GetMapping(value = "/commission",
             produces = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML})
-    @ApiOperation(value = "Query details of the requested commissioned automation composition definitions",
-        notes = "Queries details of the requested commissioned automation composition definitions, "
-            + "returning all automation composition details",
-        response = ToscaNodeTemplate.class,
-        tags = {TAGS},
-        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
-        responseHeaders = {
-            @ResponseHeader(
-                name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION,
-                response = UUID.class)},
-        extensions = {
-            @Extension
-                (
-                    name = EXTENSION_NAME,
-                    properties = {
-                        @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
-                        @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
-                    }
-                )
-            }
-    )
-    @ApiResponses(
-        value = {
-            @ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE),
-            @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE),
-            @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)
-        }
-    )
     // @formatter:on
-    public ResponseEntity<List<ToscaNodeTemplate>> query(
-        @RequestHeader(name = REQUEST_ID_NAME, required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
-        @ApiParam(value = "Automation composition  definition name", required = false) @RequestParam(
-            value = "name",
-            required = false) String name,
-        @ApiParam(value = "Automation composition  definition version", required = false) @RequestParam(
-            value = "version",
-            required = false) String version)
-        throws PfModelException {
+    public ResponseEntity<ToscaServiceTemplates> queryCompositionDefinitions(
+
+            @Parameter(description = "Automation composition  definition name", required = false) @RequestParam(
+                    value = "name",
+                    required = false) String name,
+            @Parameter(description = "Automation composition  definition version", required = false) @RequestParam(
+                    value = "version",
+                    required = false) String version,
+            @RequestHeader(name = REQUEST_ID_NAME, required = false) @Parameter(
+                    description = REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
 
         return ResponseEntity.ok().body(provider.getAutomationCompositionDefinitions(name, version));
     }
 
-    /**
-     * Retrieves the Tosca Service Template.
-     *
-     * @param requestId request ID used in ONAP logging
-     * @param name the name of the tosca service template to retrieve
-     * @param version the version of the tosca service template to get
-     * @return the specified tosca service template
-     * @throws PfModelException on errors getting the Tosca Service Template
-     */
     // @formatter:off
-    @GetMapping(value = "/commission/toscaservicetemplate",
+    @Override
+    @GetMapping(value = "/commission/{compositionId}",
             produces = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML})
-    @ApiOperation(value = "Query details of the requested tosca service templates",
-        notes = "Queries details of the requested commissioned tosca service template, "
-            + "returning all tosca service template details",
-        response = ToscaServiceTemplate.class,
-        tags = {TAGS},
-        authorizations = @Authorization(value = AUTHORIZATION_TYPE),
-        responseHeaders = {
-            @ResponseHeader(
-                name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION,
-                response = String.class),
-            @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION,
-                response = UUID.class)},
-        extensions = {
-            @Extension
-                (
-                    name = EXTENSION_NAME,
-                    properties = {
-                        @ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION),
-                        @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)
-                    }
-                )
-        }
-    )
-    @ApiResponses(
-        value = {
-            @ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE),
-            @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE),
-            @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)
-        }
-    )
     // @formatter:on
-    public ResponseEntity<String> queryToscaServiceTemplate(
-        @RequestHeader(name = REQUEST_ID_NAME, required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
-        @ApiParam(value = "Tosca service template name", required = false) @RequestParam(
-            value = "name",
-            required = false) String name,
-        @ApiParam(value = "Tosca service template version", required = false) @RequestParam(
-            value = "version",
-            required = false) String version,
-        @ApiParam(value = "Automation composition name", required = false) @RequestParam(
-                value = "instanceName",
-                required = false) String instanceName)
-        throws PfModelException {
+    public ResponseEntity<ToscaServiceTemplate> getCompositionDefinition(
+            @Parameter(
+                    in = ParameterIn.PATH,
+                    description = "The UUID of the automation composition definition to get",
+                    required = true) @PathVariable("compositionId") UUID compositionId,
+            @RequestHeader(name = REQUEST_ID_NAME, required = false) @Parameter(
+                    description = REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+
+        return ResponseEntity.ok().body(provider.getAutomationCompositionDefinitions(compositionId));
+    }
 
-        return ResponseEntity.ok().body(provider.getToscaServiceTemplateReduced(name, version, instanceName));
+    // @formatter:off
+    @Override
+    @PutMapping(value = "/commission/{compositionId}",
+            consumes = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML},
+            produces = {MediaType.APPLICATION_JSON_VALUE, APPLICATION_YAML})
+    // @formatter:on
+    public ResponseEntity<CommissioningResponse> updateCompositionDefinition(
+            @Parameter(
+                    in = ParameterIn.PATH,
+                    description = "The UUID of the automation composition definition to update",
+                    required = true) @PathVariable("compositionId") UUID compositionId,
+            @Parameter(
+                    in = ParameterIn.DEFAULT,
+                    description = "Serialised instance of.",
+                    required = true) @RequestBody ToscaServiceTemplate body,
+            @RequestHeader(name = REQUEST_ID_NAME, required = false) @Parameter(
+                    description = REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+        return ResponseEntity.ok().body(provider.updateCompositionDefinition(compositionId, body));
     }
 }
index 5751116..61522dd 100644 (file)
@@ -27,7 +27,11 @@ import io.swagger.annotations.SecurityDefinition;
 import io.swagger.annotations.SwaggerDefinition;
 import io.swagger.annotations.Tag;
 import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
 import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.policy.clamp.common.acm.exception.AutomationCompositionRuntimeException;
 import org.springframework.web.bind.annotation.RequestMapping;
 
 /**
@@ -89,4 +93,12 @@ public abstract class AbstractRestController {
      */
     protected AbstractRestController() {
     }
+
+    protected URI createUri(String str) {
+        try {
+            return new URI(str);
+        } catch (URISyntaxException e) {
+            throw new AutomationCompositionRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
+        }
+    }
 }
index 219383a..479d6cf 100644 (file)
@@ -27,7 +27,6 @@ import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
 import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
 import lombok.AllArgsConstructor;
 import org.apache.commons.collections4.CollectionUtils;
 import org.onap.policy.clamp.acm.runtime.supervision.comm.AutomationCompositionStateChangePublisher;
@@ -49,13 +48,11 @@ import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMe
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantRegister;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantStatus;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantUpdateAck;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
 import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
@@ -81,7 +78,7 @@ public class SupervisionHandler {
 
     private final AutomationCompositionProvider automationCompositionProvider;
     private final ParticipantProvider participantProvider;
-    private final ServiceTemplateProvider serviceTemplateProvider;
+    private final AcDefinitionProvider acDefinitionProvider;
 
     // Publishers for participant communication
     private final AutomationCompositionUpdatePublisher automationCompositionUpdatePublisher;
@@ -448,12 +445,7 @@ public class SupervisionHandler {
     }
 
     private int getFirstStartPhase(AutomationComposition automationComposition) {
-        ToscaServiceTemplate toscaServiceTemplate = null;
-        try {
-            toscaServiceTemplate = serviceTemplateProvider.getAllServiceTemplates().get(0);
-        } catch (PfModelException e) {
-            throw new PfModelRuntimeException(Status.BAD_REQUEST, "Canont load ToscaServiceTemplate from DB", e);
-        }
+        var toscaServiceTemplate = acDefinitionProvider.getAllServiceTemplates().get(0);
         return ParticipantUtils.getFirstStartPhase(automationComposition, toscaServiceTemplate);
     }
 
index ce7195d..5f3bfb2 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021-2022 Nordix Foundation.
  * ================================================================================
  * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
@@ -36,9 +36,9 @@ import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
 import org.onap.policy.clamp.models.acm.concepts.Participant;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantHealthStatus;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantUtils;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
@@ -62,7 +62,7 @@ public class SupervisionScanner {
     private final Map<ToscaConceptIdentifier, Integer> phaseMap = new HashMap<>();
 
     private final AutomationCompositionProvider automationCompositionProvider;
-    private final ServiceTemplateProvider serviceTemplateProvider;
+    private final AcDefinitionProvider acDefinitionProvider;
     private final AutomationCompositionStateChangePublisher automationCompositionStateChangePublisher;
     private final AutomationCompositionUpdatePublisher automationCompositionUpdatePublisher;
     private final ParticipantProvider participantProvider;
@@ -73,7 +73,7 @@ public class SupervisionScanner {
      * Constructor for instantiating SupervisionScanner.
      *
      * @param automationCompositionProvider the provider to use to read automation compositions from the database
-     * @param serviceTemplateProvider the Policy Models Provider
+     * @param acDefinitionProvider the Policy Models Provider
      * @param automationCompositionStateChangePublisher the AutomationComposition StateChange Publisher
      * @param automationCompositionUpdatePublisher the AutomationCompositionUpdate Publisher
      * @param participantProvider the Participant Provider
@@ -82,13 +82,13 @@ public class SupervisionScanner {
      * @param acRuntimeParameterGroup the parameters for the automation composition runtime
      */
     public SupervisionScanner(final AutomationCompositionProvider automationCompositionProvider,
-        ServiceTemplateProvider serviceTemplateProvider,
+        AcDefinitionProvider acDefinitionProvider,
         final AutomationCompositionStateChangePublisher automationCompositionStateChangePublisher,
         AutomationCompositionUpdatePublisher automationCompositionUpdatePublisher,
         ParticipantProvider participantProvider, ParticipantStatusReqPublisher participantStatusReqPublisher,
         ParticipantUpdatePublisher participantUpdatePublisher, final AcRuntimeParameterGroup acRuntimeParameterGroup) {
         this.automationCompositionProvider = automationCompositionProvider;
-        this.serviceTemplateProvider = serviceTemplateProvider;
+        this.acDefinitionProvider = acDefinitionProvider;
         this.automationCompositionStateChangePublisher = automationCompositionStateChangePublisher;
         this.automationCompositionUpdatePublisher = automationCompositionUpdatePublisher;
         this.participantProvider = participantProvider;
@@ -130,7 +130,7 @@ public class SupervisionScanner {
         }
 
         try {
-            var list = serviceTemplateProvider.getAllServiceTemplates();
+            var list = acDefinitionProvider.getAllServiceTemplates();
             if (list != null && !list.isEmpty()) {
                 ToscaServiceTemplate toscaServiceTemplate = list.get(0);
 
index 56da7e5..9beef51 100644 (file)
@@ -32,10 +32,8 @@ import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantUpdates;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.AutomationCompositionUpdate;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
-import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
@@ -48,7 +46,7 @@ import org.springframework.stereotype.Component;
 public class AutomationCompositionUpdatePublisher extends AbstractParticipantPublisher<AutomationCompositionUpdate> {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(AutomationCompositionUpdatePublisher.class);
-    private final ServiceTemplateProvider serviceTemplateProvider;
+    private final AcDefinitionProvider acDefinitionProvider;
 
     /**
      * Send AutomationCompositionUpdate to Participant.
@@ -75,17 +73,11 @@ public class AutomationCompositionUpdatePublisher extends AbstractParticipantPub
         automationCompositionUpdateMsg.setAutomationCompositionId(automationComposition.getKey().asIdentifier());
         automationCompositionUpdateMsg.setMessageId(UUID.randomUUID());
         automationCompositionUpdateMsg.setTimestamp(Instant.now());
-        ToscaServiceTemplate toscaServiceTemplate;
-        try {
-            toscaServiceTemplate = serviceTemplateProvider.getAllServiceTemplates().get(0);
-        } catch (PfModelException pfme) {
-            LOGGER.warn("Get of tosca service template failed, cannot send participantupdate", pfme);
-            return;
-        }
+        var toscaServiceTemplate = acDefinitionProvider.getAllServiceTemplates().get(0);
 
         List<ParticipantUpdates> participantUpdates = new ArrayList<>();
         for (AutomationCompositionElement element : automationComposition.getElements().values()) {
-            AcmUtils.setServiceTemplatePolicyInfo(element, toscaServiceTemplate);
+            AcmUtils.setAcPolicyInfo(element, toscaServiceTemplate);
             AcmUtils.prepareParticipantUpdate(element, participantUpdates);
         }
         automationCompositionUpdateMsg.setParticipantUpdatesList(participantUpdates);
index 27e8156..fa5e423 100644 (file)
@@ -26,17 +26,13 @@ import io.micrometer.core.annotation.Timed;
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
 import lombok.AllArgsConstructor;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantDefinition;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantUtils;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantUpdate;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
-import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
@@ -50,7 +46,7 @@ public class ParticipantUpdatePublisher extends AbstractParticipantPublisher<Par
 
     private static final Logger LOGGER = LoggerFactory.getLogger(ParticipantUpdatePublisher.class);
 
-    private final ServiceTemplateProvider serviceTemplateProvider;
+    private final AcDefinitionProvider acDefinitionProvider;
 
     /**
      * Send ParticipantUpdate to all Participants.
@@ -80,31 +76,22 @@ public class ParticipantUpdatePublisher extends AbstractParticipantPublisher<Par
         message.setParticipantId(participantId);
         message.setTimestamp(Instant.now());
 
-        ToscaServiceTemplate toscaServiceTemplate = null;
-        Map<String, ToscaNodeType> commonPropertiesMap = null;
-        try {
-            var list = serviceTemplateProvider.getServiceTemplateList(name, version);
-            if (!list.isEmpty()) {
-                toscaServiceTemplate = list.get(0);
-                commonPropertiesMap =
-                        serviceTemplateProvider.getCommonOrInstancePropertiesFromNodeTypes(true, toscaServiceTemplate);
-            } else {
-                LOGGER.warn("No tosca service template found, cannot send participantupdate {} {}", name, version);
-                return false;
-            }
-        } catch (PfModelException pfme) {
-            LOGGER.warn("Get of tosca service template failed, cannot send participantupdate", pfme);
+        var list = acDefinitionProvider.getServiceTemplateList(name, version);
+        if (list.isEmpty()) {
+            LOGGER.warn("No tosca service template found, cannot send participantupdate {} {}", name, version);
             return false;
         }
+        var toscaServiceTemplate = list.get(0);
+        var commonPropertiesMap = AcmUtils.getCommonOrInstancePropertiesFromNodeTypes(true, toscaServiceTemplate);
 
         List<ParticipantDefinition> participantDefinitionUpdates = new ArrayList<>();
         for (var toscaInputEntry : toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates().entrySet()) {
             if (ParticipantUtils.checkIfNodeTemplateIsAutomationCompositionElement(toscaInputEntry.getValue(),
                     toscaServiceTemplate)) {
                 AcmUtils.prepareParticipantDefinitionUpdate(
-                    ParticipantUtils.findParticipantType(toscaInputEntry.getValue().getProperties()),
-                    toscaInputEntry.getKey(), toscaInputEntry.getValue(),
-                    participantDefinitionUpdates, commonPropertiesMap);
+                        ParticipantUtils.findParticipantType(toscaInputEntry.getValue().getProperties()),
+                        toscaInputEntry.getKey(), toscaInputEntry.getValue(), participantDefinitionUpdates,
+                        commonPropertiesMap);
             }
         }
 
index 6dbaa3a..df1310d 100644 (file)
@@ -3,7 +3,7 @@ spring:
     user:
       name: runtimeUser
       password: zb!XztG34
-  http:
+  mvc:
     converters:
       preferred-json-mapper: gson
   datasource:
index 4058c68..dabb053 100644 (file)
@@ -22,7 +22,6 @@
 package org.onap.policy.clamp.acm.runtime.commissioning;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -30,23 +29,18 @@ import static org.onap.policy.clamp.acm.runtime.util.CommonTestData.TOSCA_SERVIC
 import static org.onap.policy.clamp.acm.runtime.util.CommonTestData.TOSCA_ST_TEMPLATE_YAML;
 
 import java.util.List;
-import java.util.Map;
-import java.util.Objects;
+import java.util.UUID;
 import org.junit.jupiter.api.Test;
 import org.onap.policy.clamp.acm.runtime.instantiation.InstantiationUtils;
+import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionDefinition;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
-import org.onap.policy.common.utils.coder.Coder;
-import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 
 class CommissioningProviderTest {
 
-    private static final Coder CODER = new StandardCoder();
-
     /**
      * Test the fetching of automation composition definitions (ToscaServiceTemplates).
      *
@@ -56,18 +50,17 @@ class CommissioningProviderTest {
     void testGetAutomationCompositionDefinitions() throws Exception {
         var acProvider = mock(AutomationCompositionProvider.class);
         var participantProvider = mock(ParticipantProvider.class);
-        var serviceTemplateProvider = mock(ServiceTemplateProvider.class);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
 
-        CommissioningProvider provider =
-                new CommissioningProvider(serviceTemplateProvider, acProvider, null, participantProvider);
+        var provider = new CommissioningProvider(acDefinitionProvider, acProvider, null, participantProvider);
 
-        List<ToscaNodeTemplate> listOfTemplates = provider.getAutomationCompositionDefinitions(null, null);
-        assertThat(listOfTemplates).isEmpty();
+        var serviceTemplates = provider.getAutomationCompositionDefinitions(null, null);
+        assertThat(serviceTemplates.getServiceTemplates()).isEmpty();
 
-        when(acProvider.getFilteredNodeTemplates(any()))
-                .thenReturn(List.of(new ToscaNodeTemplate(), new ToscaNodeTemplate()));
-        listOfTemplates = provider.getAutomationCompositionDefinitions(null, null);
-        assertThat(listOfTemplates).hasSize(2);
+        when(acDefinitionProvider.getServiceTemplateList(null, null))
+                .thenReturn(List.of(new ToscaServiceTemplate()));
+        serviceTemplates = provider.getAutomationCompositionDefinitions(null, null);
+        assertThat(serviceTemplates.getServiceTemplates()).hasSize(1);
     }
 
     /**
@@ -77,29 +70,21 @@ class CommissioningProviderTest {
      */
     @Test
     void testCreateAutomationCompositionDefinitions() throws Exception {
-        var serviceTemplateProvider = mock(ServiceTemplateProvider.class);
-        var acProvider = mock(AutomationCompositionProvider.class);
-        var participantProvider = mock(ParticipantProvider.class);
-
-        CommissioningProvider provider =
-                new CommissioningProvider(serviceTemplateProvider, acProvider, null, participantProvider);
-
-        List<ToscaNodeTemplate> listOfTemplates = provider.getAutomationCompositionDefinitions(null, null);
-        assertThat(listOfTemplates).isEmpty();
-
-        ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML);
-        when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate);
+        var serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML);
+        var acmDefinition = new AutomationCompositionDefinition();
+        acmDefinition.setCompositionId(UUID.randomUUID());
+        acmDefinition.setServiceTemplate(serviceTemplate);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
+        when(acDefinitionProvider.createAutomationCompositionDefinition(serviceTemplate)).thenReturn(acmDefinition);
 
         // Response should return the number of node templates present in the service template
+        var acProvider = mock(AutomationCompositionProvider.class);
+        var participantProvider = mock(ParticipantProvider.class);
+        var provider = new CommissioningProvider(acDefinitionProvider, acProvider, null, participantProvider);
         List<ToscaConceptIdentifier> affectedDefinitions = provider
                 .createAutomationCompositionDefinitions(serviceTemplate).getAffectedAutomationCompositionDefinitions();
+        verify(acDefinitionProvider).createAutomationCompositionDefinition(serviceTemplate);
         assertThat(affectedDefinitions).hasSize(13);
-
-        when(acProvider.getFilteredNodeTemplates(any()))
-                .thenReturn(List.of(new ToscaNodeTemplate(), new ToscaNodeTemplate()));
-
-        listOfTemplates = provider.getAutomationCompositionDefinitions(null, null);
-        assertThat(listOfTemplates).hasSize(2);
     }
 
     /**
@@ -108,56 +93,18 @@ class CommissioningProviderTest {
      *
      */
     @Test
-    void testGetToscaServiceTemplate() throws Exception {
-        var serviceTemplateProvider = mock(ServiceTemplateProvider.class);
+    void testGetToscaServiceTemplateList() throws Exception {
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
         var acProvider = mock(AutomationCompositionProvider.class);
         var participantProvider = mock(ParticipantProvider.class);
 
-        CommissioningProvider provider =
-                new CommissioningProvider(serviceTemplateProvider, acProvider, null, participantProvider);
+        var provider =
+                new CommissioningProvider(acDefinitionProvider, acProvider, null, participantProvider);
         ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_ST_TEMPLATE_YAML);
-        when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate);
-
-        provider.createAutomationCompositionDefinitions(serviceTemplate);
-        verify(serviceTemplateProvider).createServiceTemplate(serviceTemplate);
-
-        when(serviceTemplateProvider.getToscaServiceTemplate(null, null)).thenReturn(serviceTemplate);
+        when(acDefinitionProvider.getServiceTemplateList(null, null)).thenReturn(List.of(serviceTemplate));
 
-        ToscaServiceTemplate returnedServiceTemplate = provider.getToscaServiceTemplate(null, null);
+        var returnedServiceTemplate = provider.getAutomationCompositionDefinitions(null, null);
         assertThat(returnedServiceTemplate).isNotNull();
-
-        Map<String, ToscaNodeTemplate> nodeTemplates =
-                returnedServiceTemplate.getToscaTopologyTemplate().getNodeTemplates();
-
-        assertThat(nodeTemplates).hasSize(7);
-    }
-
-    /**
-     * Test the fetching of a reduced ToscaServiceTemplate with only some of the objects from the full template.
-     * The reduced template does not contain: DataTypesAsMap or PolicyTypesAsMap.
-     *
-     */
-    @Test
-    void testGetToscaServiceTemplateReduced() throws Exception {
-        var serviceTemplateProvider = mock(ServiceTemplateProvider.class);
-        var acProvider = mock(AutomationCompositionProvider.class);
-        var participantProvider = mock(ParticipantProvider.class);
-
-        CommissioningProvider provider =
-                new CommissioningProvider(serviceTemplateProvider, acProvider, null, participantProvider);
-        ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_ST_TEMPLATE_YAML);
-        when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate);
-
-        provider.createAutomationCompositionDefinitions(serviceTemplate);
-
-        when(serviceTemplateProvider.getServiceTemplateList(any(), any()))
-                .thenReturn(List.of(Objects.requireNonNull(serviceTemplate)));
-
-        String returnedServiceTemplate = provider
-                .getToscaServiceTemplateReduced(null, null, null);
-        assertThat(returnedServiceTemplate).isNotNull();
-        ToscaServiceTemplate parsedServiceTemplate = CODER.decode(returnedServiceTemplate, ToscaServiceTemplate.class);
-
-        assertThat(parsedServiceTemplate.getToscaTopologyTemplate().getNodeTemplates()).hasSize(7);
+        assertThat(returnedServiceTemplate.getServiceTemplates()).isNotEmpty();
     }
 }
index f34e5ef..0ded4ec 100644 (file)
@@ -27,9 +27,10 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.onap.policy.clamp.acm.runtime.util.CommonTestData.TOSCA_SERVICE_TEMPLATE_YAML;
-import static org.onap.policy.clamp.acm.runtime.util.CommonTestData.TOSCA_ST_TEMPLATE_YAML;
 
+import java.util.HashMap;
 import java.util.List;
+import java.util.UUID;
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.client.Invocation;
 import javax.ws.rs.core.Response;
@@ -43,7 +44,9 @@ import org.junit.jupiter.api.parallel.ExecutionMode;
 import org.onap.policy.clamp.acm.runtime.instantiation.InstantiationUtils;
 import org.onap.policy.clamp.acm.runtime.util.rest.CommonRestController;
 import org.onap.policy.clamp.models.acm.messages.rest.commissioning.CommissioningResponse;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
@@ -60,10 +63,10 @@ class CommissioningControllerTest extends CommonRestController {
 
     private static final String COMMISSIONING_ENDPOINT = "commission";
     private static ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
-    private static ToscaServiceTemplate commonPropertiesServiceTemplate = new ToscaServiceTemplate();
+    private UUID compositionId;
 
     @Autowired
-    private ServiceTemplateProvider serviceTemplateProvider;
+    private AcDefinitionProvider acDefinitionProvider;
 
     @LocalServerPort
     private int randomServerPort;
@@ -74,7 +77,6 @@ class CommissioningControllerTest extends CommonRestController {
     @BeforeAll
     public static void setUpBeforeClass() {
         serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML);
-        commonPropertiesServiceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_ST_TEMPLATE_YAML);
     }
 
     @BeforeEach
@@ -102,49 +104,17 @@ class CommissioningControllerTest extends CommonRestController {
         assertUnauthorizedGet(COMMISSIONING_ENDPOINT);
     }
 
-    @Test
-    void testUnauthorizedQueryElements() {
-        assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/elements");
-    }
-
     @Test
     void testUnauthorizedDelete() {
         assertUnauthorizedDelete(COMMISSIONING_ENDPOINT);
     }
 
-    @Test
-    void testUnauthorizedQueryToscaServiceTemplate() {
-        assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/toscaservicetemplate");
-    }
-
-    @Test
-    void testUnauthorizedQueryToscaServiceTemplateSchema() {
-        assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/toscaServiceTemplateSchema");
-    }
-
-    @Test
-    void testUnauthorizedQueryToscaServiceCommonOrInstanceProperties() {
-        assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/getCommonOrInstanceProperties");
-    }
-
-    @Test
-    void testQueryToscaServiceTemplate() throws Exception {
-        createFullEntryInDbWithCommonProps();
-
-        Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/toscaservicetemplate");
-        Response rawresp = invocationBuilder.buildGet().invoke();
-        assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
-        ToscaServiceTemplate template = rawresp.readEntity(ToscaServiceTemplate.class);
-        assertNotNull(template);
-        assertThat(template.getNodeTypes()).hasSize(7);
-    }
-
     @Test
     void testCreateBadRequest() {
         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
         Response resp = invocationBuilder.post(Entity.json("NotToscaServiceTempalte"));
 
-        assertThat(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).isEqualTo(resp.getStatus());
+        assertThat(Response.Status.BAD_REQUEST.getStatusCode()).isEqualTo(resp.getStatus());
         CommissioningResponse commissioningResponse = resp.readEntity(CommissioningResponse.class);
         assertThat(commissioningResponse.getErrorDetails()).isNotNull();
         assertThat(commissioningResponse.getAffectedAutomationCompositionDefinitions()).isNull();
@@ -154,9 +124,41 @@ class CommissioningControllerTest extends CommonRestController {
     void testCreate() {
         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
         Response resp = invocationBuilder.post(Entity.json(serviceTemplate));
-        assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+        assertEquals(Response.Status.CREATED.getStatusCode(), resp.getStatus());
         CommissioningResponse commissioningResponse = resp.readEntity(CommissioningResponse.class);
+        compositionId = commissioningResponse.getCompositionId();
+        assertNotNull(commissioningResponse);
+        assertNull(commissioningResponse.getErrorDetails());
+        // Response should return the number of node templates present in the service template
+        assertThat(commissioningResponse.getAffectedAutomationCompositionDefinitions()).hasSize(13);
+        for (String nodeTemplateName : serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().keySet()) {
+            assertTrue(commissioningResponse.getAffectedAutomationCompositionDefinitions().stream()
+                    .anyMatch(ac -> ac.getName().equals(nodeTemplateName)));
+        }
+    }
 
+    @Test
+    void testUpdate() {
+        var invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
+        var resp = invocationBuilder.post(Entity.json(serviceTemplate));
+        assertEquals(Response.Status.CREATED.getStatusCode(), resp.getStatus());
+        var commissioningResponse = resp.readEntity(CommissioningResponse.class);
+        compositionId = commissioningResponse.getCompositionId();
+
+        var toscaDataType = new ToscaDataType();
+        toscaDataType.setName("org.onap.datatypes.policy.clamp.Configuration");
+        toscaDataType.setDerivedFrom("tosca.datatypes.Root");
+        toscaDataType.setProperties(new HashMap<>());
+        var toscaProperty = new ToscaProperty();
+        toscaProperty.setName("configurationEntityId");
+        toscaProperty.setType("onap.datatypes.ToscaConceptIdentifier");
+        toscaDataType.getProperties().put(toscaProperty.getName(), toscaProperty);
+
+        serviceTemplate.getDataTypes().put(toscaDataType.getName(), toscaDataType);
+        invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/" + compositionId);
+        resp = invocationBuilder.put(Entity.json(serviceTemplate));
+        assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+        commissioningResponse = resp.readEntity(CommissioningResponse.class);
         assertNotNull(commissioningResponse);
         assertNull(commissioningResponse.getErrorDetails());
         // Response should return the number of node templates present in the service template
@@ -165,6 +167,12 @@ class CommissioningControllerTest extends CommonRestController {
             assertTrue(commissioningResponse.getAffectedAutomationCompositionDefinitions().stream()
                     .anyMatch(ac -> ac.getName().equals(nodeTemplateName)));
         }
+
+        invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/" + compositionId);
+        resp = invocationBuilder.buildGet().invoke();
+        assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+        var entity = resp.readEntity(ToscaServiceTemplate.class);
+        assertThat(entity.getDataTypes()).containsKey(toscaDataType.getName());
     }
 
     @Test
@@ -174,8 +182,8 @@ class CommissioningControllerTest extends CommonRestController {
         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "?name=noResultWithThisName");
         Response rawresp = invocationBuilder.buildGet().invoke();
         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
-        List<?> entityList = rawresp.readEntity(List.class);
-        assertThat(entityList).isEmpty();
+        var entityList = rawresp.readEntity(ToscaServiceTemplate.class);
+        assertThat(entityList.getNodeTypes()).isNull();
     }
 
     @Test
@@ -185,50 +193,44 @@ class CommissioningControllerTest extends CommonRestController {
         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
         Response rawresp = invocationBuilder.buildGet().invoke();
         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
-        List<?> entityList = rawresp.readEntity(List.class);
+        var entityList = rawresp.readEntity(ToscaServiceTemplate.class);
         assertNotNull(entityList);
-        assertThat(entityList).hasSize(2);
     }
 
     @Test
     void testDeleteBadRequest() throws Exception {
         createEntryInDB();
 
-        Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
+        Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/" + UUID.randomUUID());
         // Call delete with no info
         Response resp = invocationBuilder.delete();
-        assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
+        assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp.getStatus());
     }
 
     @Test
     void testDelete() throws Exception {
-        var serviceTemplateCreated = createEntryInDB();
+        createEntryInDB();
 
-        Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "?name="
-                + serviceTemplateCreated.getName() + "&version=" + serviceTemplateCreated.getVersion());
+        Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/" + compositionId);
         // Call delete with no info
         Response resp = invocationBuilder.delete();
         assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
 
-        List<ToscaServiceTemplate> templatesInDB = serviceTemplateProvider.getAllServiceTemplates();
+        List<ToscaServiceTemplate> templatesInDB = acDefinitionProvider.getAllServiceTemplates();
         assertThat(templatesInDB).isEmpty();
     }
 
-    private synchronized ToscaServiceTemplate createEntryInDB() throws Exception {
+    private synchronized void createEntryInDB() throws Exception {
         deleteEntryInDB();
-        return serviceTemplateProvider.createServiceTemplate(serviceTemplate);
+        var acmDefinition = acDefinitionProvider.createAutomationCompositionDefinition(serviceTemplate);
+        compositionId = acmDefinition.getCompositionId();
     }
 
     // Delete entries from the DB after relevant tests
     private synchronized void deleteEntryInDB() throws Exception {
-        var list = serviceTemplateProvider.getAllServiceTemplates();
+        var list = acDefinitionProvider.getAllServiceTemplates();
         if (!list.isEmpty()) {
-            serviceTemplateProvider.deleteServiceTemplate(list.get(0).getName(), list.get(0).getVersion());
+            acDefinitionProvider.deleteAcDefintion(compositionId);
         }
     }
-
-    private synchronized void createFullEntryInDbWithCommonProps() throws Exception {
-        deleteEntryInDB();
-        serviceTemplateProvider.createServiceTemplate(commonPropertiesServiceTemplate);
-    }
 }
index 016ec6c..040fabe 100644 (file)
@@ -23,16 +23,16 @@ package org.onap.policy.clamp.acm.runtime.instantiation;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
+import static org.onap.policy.clamp.acm.runtime.util.CommonTestData.TOSCA_SERVICE_TEMPLATE_YAML;
 
 import java.util.List;
 import java.util.Optional;
+import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
-import org.onap.policy.clamp.acm.runtime.commissioning.CommissioningProvider;
 import org.onap.policy.clamp.acm.runtime.supervision.SupervisionHandler;
 import org.onap.policy.clamp.acm.runtime.util.CommonTestData;
 import org.onap.policy.clamp.common.acm.exception.AutomationCompositionRuntimeException;
@@ -41,9 +41,12 @@ import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationCommand;
 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationResponse;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
+import org.onap.policy.clamp.models.acm.persistence.provider.ProviderUtils;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
 
 /**
  * Class to perform unit test of {@link AutomationCompositionInstantiationProvider}}.
@@ -51,34 +54,40 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
  */
 class AutomationCompositionInstantiationProviderTest {
     private static final String AC_INSTANTIATION_CREATE_JSON =
-        "src/test/resources/rest/acm/AutomationCompositions.json";
+            "src/test/resources/rest/acm/AutomationCompositions.json";
     private static final String AC_INSTANTIATION_UPDATE_JSON =
-        "src/test/resources/rest/acm/AutomationCompositionsUpdate.json";
+            "src/test/resources/rest/acm/AutomationCompositionsUpdate.json";
     private static final String AC_INSTANTIATION_CHANGE_STATE_JSON = "src/test/resources/rest/acm/PassiveCommand.json";
     private static final String AC_INSTANTIATION_DEFINITION_NAME_NOT_FOUND_JSON =
-        "src/test/resources/rest/acm/AutomationCompositionElementsNotFound.json";
+            "src/test/resources/rest/acm/AutomationCompositionElementsNotFound.json";
     private static final String AC_INSTANTIATION_AC_DEFINITION_NOT_FOUND_JSON =
-        "src/test/resources/rest/acm/AutomationCompositionsNotFound.json";
+            "src/test/resources/rest/acm/AutomationCompositionsNotFound.json";
     private static final String AUTOMATION_COMPOSITION_NOT_FOUND = "Automation composition not found";
     private static final String DELETE_BAD_REQUEST = "Automation composition state is still %s";
     private static final String ORDERED_STATE_INVALID = "ordered state invalid or not specified on command";
     private static final String AC_ELEMENT_NAME_NOT_FOUND =
-        "\"AutomationCompositions\" INVALID, item has status INVALID\n"
-            + " {2}\"entry org.onap.domain.pmsh.PMSHAutomationCompositionDefinition\" "
-            + "INVALID, item has status INVALID\n"
-            + " {4}\"entry org.onap.domain.pmsh.DCAEMicroservice\" INVALID, Not found\n"
-            + " {2}\"entry org.onap.domain.pmsh.PMSHAutomationCompositionDefinition\" "
-            + "INVALID, item has status INVALID\n"
-            + " {4}\"entry org.onap.domain.pmsh.DCAEMicroservice\" INVALID, Not found\n";
+            "\"AutomationCompositions\" INVALID, item has status INVALID\n"
+                    + " {2}\"entry org.onap.domain.pmsh.PMSHAutomationCompositionDefinition\" "
+                    + "INVALID, item has status INVALID\n"
+                    + " {4}\"entry org.onap.domain.pmsh.DCAEMicroservice\" INVALID, Not found\n"
+                    + " {2}\"entry org.onap.domain.pmsh.PMSHAutomationCompositionDefinition\" "
+                    + "INVALID, item has status INVALID\n"
+                    + " {4}\"entry org.onap.domain.pmsh.DCAEMicroservice\" INVALID, Not found\n";
 
     private static final String AC_DEFINITION_NOT_FOUND =
-        "\"AutomationCompositions\" INVALID, item has status INVALID\n"
-            + " {2}\"entry org.onap.domain.PMSHAutomationCompositionDefinition\" INVALID, item has status INVALID\n"
-            + " {4}item \"AutomationComposition\" value \"org.onap.domain.PMSHAutomationCompositionDefinition\""
-            + " INVALID, Commissioned automation composition definition not found\n"
-            + " {2}\"entry org.onap.domain.PMSHAutomationCompositionDefinition\" INVALID, item has status INVALID\n"
-            + " {4}item \"AutomationComposition\" value \"org.onap.domain.PMSHAutomationCompositionDefinition\""
-            + " INVALID, Commissioned automation composition definition not found\n";
+            "\"AutomationCompositions\" INVALID, item has status INVALID\n"
+                    + "  item \"ServiceTemplate\" value \"\" INVALID,"
+                    + " Commissioned automation composition definition not found\n";
+
+    private static ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
+
+    @BeforeAll
+    public static void setUpBeforeClass() {
+        serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML);
+        var jpa =
+                ProviderUtils.getJpaAndValidate(serviceTemplate, JpaToscaServiceTemplate::new, "toscaServiceTemplate");
+        serviceTemplate = jpa.toAuthorative();
+    }
 
     @Test
     void testInstantiationCrud() throws Exception {
@@ -86,51 +95,32 @@ class AutomationCompositionInstantiationProviderTest {
         var participants = CommonTestData.createParticipants();
         when(participantProvider.getParticipants()).thenReturn(participants);
 
-        var commissioningProvider = mock(CommissioningProvider.class);
-        var toscaNodeTemplate1 = new ToscaNodeTemplate();
-        toscaNodeTemplate1.setName("org.onap.domain.pmsh.PMSH_MonitoringPolicyAutomationCompositionElement");
-        toscaNodeTemplate1.setVersion("1.2.3");
-        when(commissioningProvider.getAutomationCompositionDefinitions(anyString(), anyString()))
-            .thenReturn(List.of(toscaNodeTemplate1));
-
-        var toscaNodeTemplate2 = new ToscaNodeTemplate();
-        toscaNodeTemplate2.setName("org.onap.domain.pmsh.PMSH_OperationalPolicyAutomationCompositionElement");
-        toscaNodeTemplate2.setVersion("1.2.3");
-        var toscaNodeTemplate3 = new ToscaNodeTemplate();
-        toscaNodeTemplate3.setName("org.onap.domain.pmsh.PMSH_CDS_AutomationCompositionElement");
-        toscaNodeTemplate3.setVersion("1.2.3");
-        var toscaNodeTemplate4 = new ToscaNodeTemplate();
-        toscaNodeTemplate4.setName("org.onap.domain.pmsh.PMSH_DCAEMicroservice");
-        toscaNodeTemplate4.setVersion("1.2.3");
-
-        when(commissioningProvider.getAutomationCompositionElementDefinitions(toscaNodeTemplate1))
-            .thenReturn(List.of(toscaNodeTemplate1, toscaNodeTemplate2, toscaNodeTemplate3, toscaNodeTemplate4));
-
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
+        when(acDefinitionProvider.getAllServiceTemplates()).thenReturn(List.of(serviceTemplate));
         var supervisionHandler = mock(SupervisionHandler.class);
         var acProvider = mock(AutomationCompositionProvider.class);
-        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
-        AutomationCompositions automationCompositionsCreate =
-            InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_CREATE_JSON, "Crud");
-        InstantiationResponse instantiationResponse =
-            instantiationProvider.createAutomationCompositions(automationCompositionsCreate);
+        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
+        var automationCompositionsCreate =
+                InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_CREATE_JSON, "Crud");
+        var instantiationResponse = instantiationProvider.createAutomationCompositions(automationCompositionsCreate);
         InstantiationUtils.assertInstantiationResponse(instantiationResponse, automationCompositionsCreate);
 
         verify(acProvider).saveAutomationCompositions(automationCompositionsCreate.getAutomationCompositionList());
 
         for (var automationComposition : automationCompositionsCreate.getAutomationCompositionList()) {
             when(acProvider.getAutomationCompositions(automationComposition.getName(),
-                automationComposition.getVersion())).thenReturn(List.of(automationComposition));
+                    automationComposition.getVersion())).thenReturn(List.of(automationComposition));
 
-            AutomationCompositions automationCompositionsGet = instantiationProvider
-                .getAutomationCompositions(automationComposition.getName(), automationComposition.getVersion());
+            var automationCompositionsGet = instantiationProvider
+                    .getAutomationCompositions(automationComposition.getName(), automationComposition.getVersion());
             assertThat(automationCompositionsGet.getAutomationCompositionList()).hasSize(1);
             assertThat(automationComposition)
-                .isEqualTo(automationCompositionsGet.getAutomationCompositionList().get(0));
+                    .isEqualTo(automationCompositionsGet.getAutomationCompositionList().get(0));
         }
 
-        AutomationCompositions automationCompositionsUpdate =
-            InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_UPDATE_JSON, "Crud");
+        var automationCompositionsUpdate =
+                InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_UPDATE_JSON, "Crud");
 
         instantiationResponse = instantiationProvider.updateAutomationCompositions(automationCompositionsUpdate);
         InstantiationUtils.assertInstantiationResponse(instantiationResponse, automationCompositionsUpdate);
@@ -139,33 +129,33 @@ class AutomationCompositionInstantiationProviderTest {
 
         for (var automationComposition : automationCompositionsUpdate.getAutomationCompositionList()) {
             when(acProvider.findAutomationComposition(automationComposition.getKey().asIdentifier()))
-                .thenReturn(Optional.of(automationComposition));
+                    .thenReturn(Optional.of(automationComposition));
             when(acProvider.findAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion())).thenReturn(Optional.of(automationComposition));
+                    automationComposition.getVersion())).thenReturn(Optional.of(automationComposition));
             when(acProvider.deleteAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion())).thenReturn(automationComposition);
+                    automationComposition.getVersion())).thenReturn(automationComposition);
         }
 
-        InstantiationCommand instantiationCommand =
-            InstantiationUtils.getInstantiationCommandFromResource(AC_INSTANTIATION_CHANGE_STATE_JSON, "Crud");
+        var instantiationCommand =
+                InstantiationUtils.getInstantiationCommandFromResource(AC_INSTANTIATION_CHANGE_STATE_JSON, "Crud");
         instantiationResponse = instantiationProvider.issueAutomationCompositionCommand(instantiationCommand);
         InstantiationUtils.assertInstantiationResponse(instantiationResponse, instantiationCommand);
 
         verify(supervisionHandler)
-            .triggerAutomationCompositionSupervision(instantiationCommand.getAutomationCompositionIdentifierList());
+                .triggerAutomationCompositionSupervision(instantiationCommand.getAutomationCompositionIdentifierList());
 
         // in order to delete a automationComposition the state must be UNINITIALISED
         automationCompositionsCreate.getAutomationCompositionList()
-            .forEach(ac -> ac.setState(AutomationCompositionState.UNINITIALISED));
+                .forEach(ac -> ac.setState(AutomationCompositionState.UNINITIALISED));
         instantiationProvider.updateAutomationCompositions(automationCompositionsCreate);
 
         for (AutomationComposition automationComposition : automationCompositionsCreate
-            .getAutomationCompositionList()) {
+                .getAutomationCompositionList()) {
             instantiationProvider.deleteAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion());
+                    automationComposition.getVersion());
 
             verify(acProvider).deleteAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion());
+                    automationComposition.getVersion());
         }
     }
 
@@ -173,19 +163,19 @@ class AutomationCompositionInstantiationProviderTest {
     void testInstantiationDelete() throws Exception {
 
         AutomationCompositions automationCompositions =
-            InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_CREATE_JSON, "Delete");
+                InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_CREATE_JSON, "Delete");
 
         AutomationComposition automationComposition0 = automationCompositions.getAutomationCompositionList().get(0);
         var participantProvider = Mockito.mock(ParticipantProvider.class);
         var acProvider = mock(AutomationCompositionProvider.class);
         var supervisionHandler = mock(SupervisionHandler.class);
-        var commissioningProvider = mock(CommissioningProvider.class);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
 
-        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
+        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
 
         assertThatThrownBy(() -> instantiationProvider.deleteAutomationComposition(automationComposition0.getName(),
-            automationComposition0.getVersion())).hasMessageMatching(AUTOMATION_COMPOSITION_NOT_FOUND);
+                automationComposition0.getVersion())).hasMessageMatching(AUTOMATION_COMPOSITION_NOT_FOUND);
 
         for (AutomationCompositionState state : AutomationCompositionState.values()) {
             if (!AutomationCompositionState.UNINITIALISED.equals(state)) {
@@ -196,147 +186,111 @@ class AutomationCompositionInstantiationProviderTest {
 
         for (AutomationComposition automationComposition : automationCompositions.getAutomationCompositionList()) {
             when(acProvider.findAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion())).thenReturn(Optional.of(automationComposition));
+                    automationComposition.getVersion())).thenReturn(Optional.of(automationComposition));
             when(acProvider.deleteAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion())).thenReturn(automationComposition);
+                    automationComposition.getVersion())).thenReturn(automationComposition);
 
             instantiationProvider.deleteAutomationComposition(automationComposition.getName(),
-                automationComposition.getVersion());
+                    automationComposition.getVersion());
         }
     }
 
     private void assertThatDeleteThrownBy(AutomationCompositions automationCompositions,
-        AutomationCompositionState state) throws Exception {
+            AutomationCompositionState state) throws Exception {
         AutomationComposition automationComposition = automationCompositions.getAutomationCompositionList().get(0);
         automationComposition.setState(state);
         var participantProvider = Mockito.mock(ParticipantProvider.class);
         var acProvider = mock(AutomationCompositionProvider.class);
         var supervisionHandler = mock(SupervisionHandler.class);
-        var commissioningProvider = mock(CommissioningProvider.class);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
 
-        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
+        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
 
         when(acProvider.findAutomationComposition(automationComposition.getName(), automationComposition.getVersion()))
-            .thenReturn(Optional.of(automationComposition));
+                .thenReturn(Optional.of(automationComposition));
 
         assertThatThrownBy(() -> instantiationProvider.deleteAutomationComposition(automationComposition.getName(),
-            automationComposition.getVersion())).hasMessageMatching(String.format(DELETE_BAD_REQUEST, state));
+                automationComposition.getVersion())).hasMessageMatching(String.format(DELETE_BAD_REQUEST, state));
     }
 
     @Test
     void testCreateAutomationCompositions_NoDuplicates() throws Exception {
-        var commissioningProvider = mock(CommissioningProvider.class);
-
-        var toscaNodeTemplate1 = new ToscaNodeTemplate();
-        toscaNodeTemplate1.setName("org.onap.domain.pmsh.PMSH_MonitoringPolicyAutomationCompositionElement");
-        toscaNodeTemplate1.setVersion("1.2.3");
-        when(commissioningProvider.getAutomationCompositionDefinitions(anyString(), anyString()))
-            .thenReturn(List.of(toscaNodeTemplate1));
-
-        var toscaNodeTemplate2 = new ToscaNodeTemplate();
-        toscaNodeTemplate2.setName("org.onap.domain.pmsh.PMSH_OperationalPolicyAutomationCompositionElement");
-        toscaNodeTemplate2.setVersion("1.2.3");
-        var toscaNodeTemplate3 = new ToscaNodeTemplate();
-        toscaNodeTemplate3.setName("org.onap.domain.pmsh.PMSH_CDS_AutomationCompositionElement");
-        toscaNodeTemplate3.setVersion("1.2.3");
-        var toscaNodeTemplate4 = new ToscaNodeTemplate();
-        toscaNodeTemplate4.setName("org.onap.domain.pmsh.PMSH_DCAEMicroservice");
-        toscaNodeTemplate4.setVersion("1.2.3");
-
-        when(commissioningProvider.getAutomationCompositionElementDefinitions(toscaNodeTemplate1))
-            .thenReturn(List.of(toscaNodeTemplate1, toscaNodeTemplate2, toscaNodeTemplate3, toscaNodeTemplate4));
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
+        when(acDefinitionProvider.getAllServiceTemplates()).thenReturn(List.of(serviceTemplate));
 
         AutomationCompositions automationCompositionsCreate =
-            InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_CREATE_JSON, "NoDuplicates");
+                InstantiationUtils.getAutomationCompositionsFromResource(AC_INSTANTIATION_CREATE_JSON, "NoDuplicates");
 
         var acProvider = mock(AutomationCompositionProvider.class);
         var participantProvider = Mockito.mock(ParticipantProvider.class);
         var supervisionHandler = mock(SupervisionHandler.class);
 
-        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
+        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
 
         InstantiationResponse instantiationResponse =
-            instantiationProvider.createAutomationCompositions(automationCompositionsCreate);
+                instantiationProvider.createAutomationCompositions(automationCompositionsCreate);
         InstantiationUtils.assertInstantiationResponse(instantiationResponse, automationCompositionsCreate);
 
         when(acProvider.findAutomationComposition(
-            automationCompositionsCreate.getAutomationCompositionList().get(0).getKey().asIdentifier()))
-                .thenReturn(Optional.of(automationCompositionsCreate.getAutomationCompositionList().get(0)));
+                automationCompositionsCreate.getAutomationCompositionList().get(0).getKey().asIdentifier()))
+                        .thenReturn(Optional.of(automationCompositionsCreate.getAutomationCompositionList().get(0)));
 
         assertThatThrownBy(() -> instantiationProvider.createAutomationCompositions(automationCompositionsCreate))
-            .hasMessageMatching(
-                automationCompositionsCreate.getAutomationCompositionList().get(0).getKey().asIdentifier()
-                    + " already defined");
+                .hasMessageMatching(
+                        automationCompositionsCreate.getAutomationCompositionList().get(0).getKey().asIdentifier()
+                                + " already defined");
     }
 
     @Test
     void testCreateAutomationCompositions_CommissionedAcElementNotFound() throws Exception {
-        var toscaNodeTemplate1 = new ToscaNodeTemplate();
-        toscaNodeTemplate1.setName("org.onap.domain.pmsh.PMSH_MonitoringPolicyAutomationCompositionElement");
-        toscaNodeTemplate1.setVersion("1.2.3");
-
-        var toscaNodeTemplate2 = new ToscaNodeTemplate();
-        toscaNodeTemplate2.setName("org.onap.domain.pmsh.PMSH_OperationalPolicyAutomationCompositionElement");
-        toscaNodeTemplate2.setVersion("1.2.3");
-        var toscaNodeTemplate3 = new ToscaNodeTemplate();
-        toscaNodeTemplate3.setName("org.onap.domain.pmsh.PMSH_CDS_AutomationCompositionElement");
-        toscaNodeTemplate3.setVersion("1.2.3");
-        var commissioningProvider = mock(CommissioningProvider.class);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
+        when(acDefinitionProvider.getAllServiceTemplates()).thenReturn(List.of(serviceTemplate));
         AutomationCompositions automationCompositions = InstantiationUtils.getAutomationCompositionsFromResource(
-            AC_INSTANTIATION_DEFINITION_NAME_NOT_FOUND_JSON, "AcElementNotFound");
-
-        when(commissioningProvider.getAutomationCompositionDefinitions(
-            automationCompositions.getAutomationCompositionList().get(0).getDefinition().getName(),
-            automationCompositions.getAutomationCompositionList().get(0).getDefinition().getVersion()))
-                .thenReturn(List.of(toscaNodeTemplate1));
-
-        when(commissioningProvider.getAutomationCompositionElementDefinitions(toscaNodeTemplate1))
-            .thenReturn(List.of(toscaNodeTemplate1, toscaNodeTemplate2, toscaNodeTemplate3));
+                AC_INSTANTIATION_DEFINITION_NAME_NOT_FOUND_JSON, "AcElementNotFound");
 
         var acProvider = mock(AutomationCompositionProvider.class);
         var participantProvider = mock(ParticipantProvider.class);
         var supervisionHandler = mock(SupervisionHandler.class);
-        var provider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
+        var provider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
 
         assertThatThrownBy(() -> provider.createAutomationCompositions(automationCompositions))
-            .hasMessageMatching(AC_ELEMENT_NAME_NOT_FOUND);
+                .hasMessageMatching(AC_ELEMENT_NAME_NOT_FOUND);
 
         assertThatThrownBy(() -> provider.updateAutomationCompositions(automationCompositions))
-            .hasMessageMatching(AC_ELEMENT_NAME_NOT_FOUND);
+                .hasMessageMatching(AC_ELEMENT_NAME_NOT_FOUND);
     }
 
     @Test
     void testCreateAutomationCompositions_CommissionedAcNotFound() throws Exception {
         AutomationCompositions automationCompositions = InstantiationUtils
-            .getAutomationCompositionsFromResource(AC_INSTANTIATION_AC_DEFINITION_NOT_FOUND_JSON, "AcNotFound");
+                .getAutomationCompositionsFromResource(AC_INSTANTIATION_AC_DEFINITION_NOT_FOUND_JSON, "AcNotFound");
 
         var participantProvider = Mockito.mock(ParticipantProvider.class);
         var acProvider = mock(AutomationCompositionProvider.class);
         var supervisionHandler = mock(SupervisionHandler.class);
-        var commissioningProvider = mock(CommissioningProvider.class);
-        var provider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
+        var provider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
 
         assertThatThrownBy(() -> provider.createAutomationCompositions(automationCompositions))
-            .hasMessageMatching(AC_DEFINITION_NOT_FOUND);
+                .hasMessageMatching(AC_DEFINITION_NOT_FOUND);
 
         assertThatThrownBy(() -> provider.updateAutomationCompositions(automationCompositions))
-            .hasMessageMatching(AC_DEFINITION_NOT_FOUND);
+                .hasMessageMatching(AC_DEFINITION_NOT_FOUND);
     }
 
     @Test
-    void testIssueAutomationCompositionCommand_OrderedStateInvalid()
-        throws AutomationCompositionRuntimeException {
+    void testIssueAutomationCompositionCommand_OrderedStateInvalid() throws AutomationCompositionRuntimeException {
         var participantProvider = Mockito.mock(ParticipantProvider.class);
         var acProvider = mock(AutomationCompositionProvider.class);
         var supervisionHandler = mock(SupervisionHandler.class);
-        var commissioningProvider = mock(CommissioningProvider.class);
-        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, commissioningProvider,
-            supervisionHandler, participantProvider);
+        var acDefinitionProvider = mock(AcDefinitionProvider.class);
+        var instantiationProvider = new AutomationCompositionInstantiationProvider(acProvider, supervisionHandler,
+                participantProvider, acDefinitionProvider);
         assertThatThrownBy(() -> instantiationProvider.issueAutomationCompositionCommand(new InstantiationCommand()))
-            .hasMessageMatching(ORDERED_STATE_INVALID);
+                .hasMessageMatching(ORDERED_STATE_INVALID);
     }
 }
index 7cdc8a9..2284121 100644 (file)
@@ -27,6 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.onap.policy.clamp.acm.runtime.util.CommonTestData.TOSCA_SERVICE_TEMPLATE_YAML;
 
+import java.util.UUID;
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.client.Invocation;
 import javax.ws.rs.core.Response;
@@ -44,8 +45,8 @@ import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationCommand;
 import org.onap.policy.clamp.models.acm.messages.rest.instantiation.InstantiationResponse;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
 import org.onap.policy.clamp.models.acm.persistence.repository.AutomationCompositionRepository;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
@@ -65,9 +66,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
 @ActiveProfiles("test")
 class InstantiationControllerTest extends CommonRestController {
 
-    private static final String ID_NAME = "PMSH_Test_Instance";
-    private static final String ID_VERSION = "1.2.3";
-
     private static final String AC_INSTANTIATION_CREATE_JSON =
         "src/test/resources/rest/acm/AutomationCompositions.json";
 
@@ -80,12 +78,13 @@ class InstantiationControllerTest extends CommonRestController {
     private static final String INSTANTIATION_COMMAND_ENDPOINT = "instantiation/command";
 
     private static ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
+    private UUID compositionId;
 
     @Autowired
     private AutomationCompositionRepository automationCompositionRepository;
 
     @Autowired
-    private ServiceTemplateProvider serviceTemplateProvider;
+    private AcDefinitionProvider acDefinitionProvider;
 
     @Autowired
     private AutomationCompositionInstantiationProvider instantiationProvider;
@@ -347,14 +346,15 @@ class InstantiationControllerTest extends CommonRestController {
 
     private synchronized void deleteEntryInDB() throws Exception {
         automationCompositionRepository.deleteAll();
-        var list = serviceTemplateProvider.getAllServiceTemplates();
+        var list = acDefinitionProvider.getAllServiceTemplates();
         if (!list.isEmpty()) {
-            serviceTemplateProvider.deleteServiceTemplate(list.get(0).getName(), list.get(0).getVersion());
+            acDefinitionProvider.deleteAcDefintion(compositionId);
         }
     }
 
     private synchronized void createEntryInDB() throws Exception {
         deleteEntryInDB();
-        serviceTemplateProvider.createServiceTemplate(serviceTemplate);
+        var acmDefinition = acDefinitionProvider.createAutomationCompositionDefinition(serviceTemplate);
+        compositionId = acmDefinition.getCompositionId();
     }
 }
index 7e9b102..e4d3821 100644 (file)
@@ -54,9 +54,9 @@ import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMe
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantRegister;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantStatus;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantUpdateAck;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@@ -119,15 +119,15 @@ class SupervisionHandlerTest {
             .thenReturn(Optional.of(automationComposition));
         when(automationCompositionProvider.getAutomationComposition(identifier)).thenReturn(automationComposition);
 
-        var serviceTemplateProvider = Mockito.mock(ServiceTemplateProvider.class);
-        when(serviceTemplateProvider.getAllServiceTemplates())
+        var acDefinitionProvider = Mockito.mock(AcDefinitionProvider.class);
+        when(acDefinitionProvider.getAllServiceTemplates())
             .thenReturn(List.of(Objects.requireNonNull(InstantiationUtils.getToscaServiceTemplate(
                     TOSCA_SERVICE_TEMPLATE_YAML))));
 
         var automationCompositionStateChangePublisher = mock(AutomationCompositionStateChangePublisher.class);
 
         var handler = new SupervisionHandler(automationCompositionProvider, mock(ParticipantProvider.class),
-            serviceTemplateProvider, mock(AutomationCompositionUpdatePublisher.class),
+            acDefinitionProvider, mock(AutomationCompositionUpdatePublisher.class),
             automationCompositionStateChangePublisher, mock(ParticipantRegisterAckPublisher.class),
             mock(ParticipantDeregisterAckPublisher.class), mock(ParticipantUpdatePublisher.class));
 
@@ -355,18 +355,18 @@ class SupervisionHandlerTest {
             .thenReturn(Optional.of(automationComposition));
         when(automationCompositionProvider.getAutomationComposition(identifier)).thenReturn(automationComposition);
 
-        var serviceTemplateProvider = Mockito.mock(ServiceTemplateProvider.class);
-        when(serviceTemplateProvider.getServiceTemplateList(any(), any()))
+        var acDefinitionProvider = Mockito.mock(AcDefinitionProvider.class);
+        when(acDefinitionProvider.getServiceTemplateList(any(), any()))
             .thenReturn(List.of(Objects.requireNonNull(InstantiationUtils.getToscaServiceTemplate(
                     TOSCA_SERVICE_TEMPLATE_YAML))));
-        when(serviceTemplateProvider.getAllServiceTemplates())
+        when(acDefinitionProvider.getAllServiceTemplates())
             .thenReturn(List.of(Objects.requireNonNull(InstantiationUtils.getToscaServiceTemplate(
                     TOSCA_SERVICE_TEMPLATE_YAML))));
 
         var automationCompositionStateChangePublisher = mock(AutomationCompositionStateChangePublisher.class);
 
         return new SupervisionHandler(automationCompositionProvider, participantProvider,
-            serviceTemplateProvider, automationCompositionUpdatePublisher, automationCompositionStateChangePublisher,
+            acDefinitionProvider, automationCompositionUpdatePublisher, automationCompositionStateChangePublisher,
             participantRegisterAckPublisher, participantDeregisterAckPublisher, participantUpdatePublisher);
 
     }
index cc3a95e..50d5246 100644 (file)
@@ -45,9 +45,9 @@ import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
 import org.onap.policy.clamp.models.acm.concepts.Participant;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantHealthStatus;
 import org.onap.policy.clamp.models.acm.concepts.ParticipantState;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@@ -57,7 +57,7 @@ class SupervisionScannerTest {
 
     private static final String AC_JSON = "src/test/resources/rest/acm/AutomationCompositionsSmoke.json";
 
-    private static final ServiceTemplateProvider serviceTemplateProvider = mock(ServiceTemplateProvider.class);
+    private static final AcDefinitionProvider acDefinitionProvider = mock(AcDefinitionProvider.class);
 
     private static final String PARTICIPANT_NAME = "Participant0";
     private static final String PARTICIPANT_VERSION = "1.0.0";
@@ -68,7 +68,7 @@ class SupervisionScannerTest {
     @BeforeAll
     public static void setUpBeforeAll() throws Exception {
         ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_ST_TEMPLATE_YAML);
-        when(serviceTemplateProvider.getAllServiceTemplates())
+        when(acDefinitionProvider.getAllServiceTemplates())
             .thenReturn(List.of(Objects.requireNonNull(serviceTemplate)));
     }
 
@@ -86,7 +86,7 @@ class SupervisionScannerTest {
             InstantiationUtils.getAutomationCompositionsFromResource(AC_JSON, "Crud").getAutomationCompositionList();
         when(automationCompositionProvider.getAutomationCompositions()).thenReturn(automationCompositions);
 
-        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, serviceTemplateProvider,
+        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, acDefinitionProvider,
             automationCompositionStateChangePublisher, automationCompositionUpdatePublisher, participantProvider,
             participantStatusReqPublisher, participantUpdatePublisher, acRuntimeParameterGroup);
         supervisionScanner.run(false);
@@ -110,7 +110,7 @@ class SupervisionScannerTest {
         var participantUpdatePublisher = mock(ParticipantUpdatePublisher.class);
         var acRuntimeParameterGroup = CommonTestData.geParameterGroup("dbScanner");
 
-        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, serviceTemplateProvider,
+        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, acDefinitionProvider,
             automationCompositionStateChangePublisher, automationCompositionUpdatePublisher, participantProvider,
             participantStatusReqPublisher, participantUpdatePublisher, acRuntimeParameterGroup);
         supervisionScanner.run(false);
@@ -136,7 +136,7 @@ class SupervisionScannerTest {
         var participantUpdatePublisher = mock(ParticipantUpdatePublisher.class);
         var acRuntimeParameterGroup = CommonTestData.geParameterGroup("dbScanner");
 
-        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, serviceTemplateProvider,
+        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, acDefinitionProvider,
             automationCompositionStateChangePublisher, automationCompositionUpdatePublisher, participantProvider,
             participantStatusReqPublisher, participantUpdatePublisher, acRuntimeParameterGroup);
 
@@ -173,7 +173,7 @@ class SupervisionScannerTest {
         var participantUpdatePublisher = mock(ParticipantUpdatePublisher.class);
         var acRuntimeParameterGroup = CommonTestData.geParameterGroup("dbScanner");
 
-        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, serviceTemplateProvider,
+        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, acDefinitionProvider,
             automationCompositionStateChangePublisher, automationCompositionUpdatePublisher, participantProvider,
             participantStatusReqPublisher, participantUpdatePublisher, acRuntimeParameterGroup);
 
@@ -207,7 +207,7 @@ class SupervisionScannerTest {
         var automationCompositionStateChangePublisher = mock(AutomationCompositionStateChangePublisher.class);
         var participantUpdatePublisher = mock(ParticipantUpdatePublisher.class);
 
-        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, serviceTemplateProvider,
+        var supervisionScanner = new SupervisionScanner(automationCompositionProvider, acDefinitionProvider,
             automationCompositionStateChangePublisher, automationCompositionUpdatePublisher, participantProvider,
             participantStatusReqPublisher, participantUpdatePublisher, acRuntimeParameterGroup);
 
index ad97201..11a0600 100644 (file)
@@ -43,9 +43,9 @@ import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantDe
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantDeregisterAck;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantRegisterAck;
 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantUpdateAck;
+import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
-import org.onap.policy.clamp.models.acm.persistence.provider.ServiceTemplateProvider;
 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 import org.onap.policy.common.endpoints.event.comm.TopicSink;
 import org.onap.policy.models.base.PfModelException;
@@ -68,14 +68,14 @@ class SupervisionMessagesTest extends CommonRestController {
     public static void setupDbProviderParameters() throws PfModelException {
         var acProvider = mock(AutomationCompositionProvider.class);
         var participantProvider = mock(ParticipantProvider.class);
-        var serviceTemplateProvider = Mockito.mock(ServiceTemplateProvider.class);
+        var acDefinitionProvider = Mockito.mock(AcDefinitionProvider.class);
         var automationCompositionUpdatePublisher = Mockito.mock(AutomationCompositionUpdatePublisher.class);
         var automationCompositionStateChangePublisher = Mockito.mock(AutomationCompositionStateChangePublisher.class);
         var participantRegisterAckPublisher = Mockito.mock(ParticipantRegisterAckPublisher.class);
         var participantDeregisterAckPublisher = Mockito.mock(ParticipantDeregisterAckPublisher.class);
         var participantUpdatePublisher = Mockito.mock(ParticipantUpdatePublisher.class);
         supervisionHandler = new SupervisionHandler(acProvider, participantProvider,
-            serviceTemplateProvider, automationCompositionUpdatePublisher, automationCompositionStateChangePublisher,
+            acDefinitionProvider, automationCompositionUpdatePublisher, automationCompositionStateChangePublisher,
             participantRegisterAckPublisher, participantDeregisterAckPublisher, participantUpdatePublisher);
     }
 
@@ -157,7 +157,7 @@ class SupervisionMessagesTest extends CommonRestController {
 
     @Test
     void testParticipantUpdatePublisherDecomisioning() {
-        var publisher = new ParticipantUpdatePublisher(mock(ServiceTemplateProvider.class));
+        var publisher = new ParticipantUpdatePublisher(mock(AcDefinitionProvider.class));
         var topicSink = mock(TopicSink.class);
         publisher.active(List.of(topicSink));
         publisher.sendDecomisioning();
@@ -166,7 +166,7 @@ class SupervisionMessagesTest extends CommonRestController {
 
     @Test
     void testParticipantUpdatePublisherComissioning() {
-        var publisher = new ParticipantUpdatePublisher(mock(ServiceTemplateProvider.class));
+        var publisher = new ParticipantUpdatePublisher(mock(AcDefinitionProvider.class));
         var topicSink = mock(TopicSink.class);
         publisher.active(List.of(topicSink));
         publisher.sendComissioningBroadcast("NAME", "1.0.0");