aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib
diff options
context:
space:
mode:
Diffstat (limited to 'openecomp-be/lib')
-rw-r--r--openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java380
-rw-r--r--openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java361
-rw-r--r--openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java2754
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java57
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java532
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java85
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java3
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java1748
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/DataModelUtilTest.java41
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java1592
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml232
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/CommonGlobalTypesServiceTemplate.yaml3
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/_index.yml37
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/artifacts.yml55
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/capabilities.yml230
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/data.yml191
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/groups.yml30
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/interfaces.yml61
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/nodes.yml371
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/policies.yml43
-rw-r--r--openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/relationships.yml106
21 files changed, 5113 insertions, 3799 deletions
diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java
index 639579ccd0..add04164c2 100644
--- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java
+++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * 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.
+ */
+
package org.openecomp.sdc.enrichment.impl.tosca;
import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.HIGH_AVAIL_MODE;
@@ -18,17 +34,16 @@ import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.datatypes.error.ErrorMessage;
import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
-import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
import org.onap.sdc.tosca.datatypes.model.NodeType;
import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
+import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
import org.openecomp.sdc.tosca.services.DataModelUtil;
import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
import org.openecomp.sdc.tosca.services.ToscaConstants;
import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
-import org.openecomp.sdc.versioning.dao.types.Version;
import java.util.ArrayList;
import java.util.HashMap;
@@ -37,236 +52,233 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import org.openecomp.sdc.versioning.dao.types.Version;
+
public class AbstractSubstituteToscaEnricher {
- private ToscaAnalyzerService toscaAnalyzerService ;
- private ComponentQuestionnaireData componentQuestionnaireData;
+ private ToscaAnalyzerService toscaAnalyzerService;
+ private ComponentQuestionnaireData componentQuestionnaireData;
- public Map<String,List<ErrorMessage>> enrich(ToscaServiceModel toscaModel, String vspId, Version
- version) {
- componentQuestionnaireData = getComponentQuestionnaireData();
- toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- Map<String, Map<String, Object>> componentProperties =
- componentQuestionnaireData.getPropertiesfromCompQuestionnaire(vspId, version);
+ public Map<String, List<ErrorMessage>> enrich(ToscaServiceModel toscaModel, String vspId, Version version) {
+ componentQuestionnaireData = getComponentQuestionnaireData();
+ toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- final Map<String, List<String>> sourceToTargetDependencies =
- componentQuestionnaireData.populateDependencies(vspId, version,
- componentQuestionnaireData.getSourceToTargetComponent());
+ Map<String, Map<String, Object>> componentProperties =
+ componentQuestionnaireData.getPropertiesfromCompQuestionnaire(vspId, version);
- Map<String, List<ErrorMessage>> errors = new HashMap<>();
+ final Map<String, List<String>> sourceToTargetDependencies = componentQuestionnaireData
+ .populateDependencies(vspId, version,
+ componentQuestionnaireData
+ .getSourceToTargetComponent());
+ Map<String, List<ErrorMessage>> errors = new HashMap<>();
- final ServiceTemplate serviceTemplate = toscaModel.getServiceTemplates()
- .get(toscaModel.getEntryDefinitionServiceTemplate());
+ final ServiceTemplate serviceTemplate =
+ toscaModel.getServiceTemplates().get(toscaModel.getEntryDefinitionServiceTemplate());
- if (serviceTemplate == null) return errors;
+ if (serviceTemplate == null) {
+ return errors;
+ }
- final Map<String, NodeTemplate> node_templates =
- serviceTemplate.getTopology_template().getNode_templates();
- if(node_templates == null) return errors;
+ final Map<String, NodeTemplate> node_templates = serviceTemplate.getTopology_template().getNode_templates();
+ if (node_templates == null) {
+ return errors;
+ }
- final Map<String, List<String>> componentDisplayNameToNodeTempalteIds =
- populateAllNodeTemplateIdForComponent(node_templates, serviceTemplate, toscaModel);
+ final Map<String, List<String>> componentDisplayNameToNodeTempalteIds =
+ populateAllNodeTemplateIdForComponent(node_templates, serviceTemplate, toscaModel);
- node_templates.keySet()
- .stream()
- .forEach(nodeTemplateId -> {
- final Optional<NodeTemplate> nodeTemplateById =
- toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId);
- final NodeTemplate nodeTemplate =
- nodeTemplateById.isPresent() ? nodeTemplateById.get() : null;
+ node_templates.keySet().stream().forEach(nodeTemplateId -> {
+ final Optional<NodeTemplate> nodeTemplateById =
+ toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId);
+ final NodeTemplate nodeTemplate = nodeTemplateById.isPresent() ? nodeTemplateById.get() : null;
- if (toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate,
- toscaModel)) {
+ if (toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate, toscaModel)) {
- String componentDisplayName = getComponentDisplayName(nodeTemplateId, nodeTemplate);
+ String componentDisplayName = getComponentDisplayName(nodeTemplateId, nodeTemplate);
- setProperty(nodeTemplate, VM_TYPE_TAG, componentDisplayName);
+ setProperty(nodeTemplate, VM_TYPE_TAG, componentDisplayName);
- if (componentProperties != null && componentProperties.containsKey
- (componentDisplayName)) {
- final String mandatory =
- getValueFromQuestionnaireDetails(componentProperties, componentDisplayName,
- MANDATORY);
+ if (componentProperties != null && componentProperties.containsKey(componentDisplayName)) {
+ final String mandatory =
+ getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, MANDATORY);
- boolean isServiceTemplateFilterNotExists = false;
- if (!StringUtils.isEmpty(mandatory)) {
- Map innerProps = (Map<String, Object>) nodeTemplate.getProperties()
- .get(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
+ boolean isServiceTemplateFilterNotExists = false;
+ if (!StringUtils.isEmpty(mandatory)) {
+ Map innerProps = (Map<String, Object>) nodeTemplate.getProperties()
+ .get(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
- if (innerProps == null) {
- innerProps = new HashMap<String, Object>();
- isServiceTemplateFilterNotExists = true;
- }
+ if (innerProps == null) {
+ innerProps = new HashMap<String, Object>();
+ isServiceTemplateFilterNotExists = true;
+ }
- innerProps.put(MANDATORY, getValue(mandatory));
+ innerProps.put(MANDATORY, getValue(mandatory));
- if(isServiceTemplateFilterNotExists)
- nodeTemplate.getProperties().put(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME,
- innerProps);
- }
+ if (isServiceTemplateFilterNotExists) {
+ nodeTemplate.getProperties().put(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
+ }
+ }
- setProperty(nodeTemplate, HIGH_AVAIL_MODE, getValueFromQuestionnaireDetails
- (componentProperties, componentDisplayName, HIGH_AVAIL_MODE));
+ setProperty(nodeTemplate, HIGH_AVAIL_MODE,
+ getValueFromQuestionnaireDetails(componentProperties, componentDisplayName,
+ HIGH_AVAIL_MODE));
- setProperty(nodeTemplate, VFC_NAMING_CODE, getValueFromQuestionnaireDetails
- (componentProperties, componentDisplayName, VFC_NAMING_CODE));
+ setProperty(nodeTemplate, VFC_NAMING_CODE,
+ getValueFromQuestionnaireDetails(componentProperties, componentDisplayName,
+ VFC_NAMING_CODE));
- setProperty(nodeTemplate, VFC_CODE, getValueFromQuestionnaireDetails
- (componentProperties, componentDisplayName, VFC_CODE));
+ setProperty(nodeTemplate, VFC_CODE,
+ getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, VFC_CODE));
- setProperty(nodeTemplate, VFC_FUNCTION, getValueFromQuestionnaireDetails
- (componentProperties, componentDisplayName, VFC_FUNCTION));
+ setProperty(nodeTemplate, VFC_FUNCTION,
+ getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, VFC_FUNCTION));
- if(componentProperties.get(componentDisplayName).get(MIN_INSTANCES) != null) {
- nodeTemplate.getProperties().put(MIN_INSTANCES,
- componentProperties.get(componentDisplayName).get(MIN_INSTANCES));
- }
+ if (componentProperties.get(componentDisplayName).get(MIN_INSTANCES) != null) {
+ nodeTemplate.getProperties().put(MIN_INSTANCES,
+ componentProperties.get(componentDisplayName).get(MIN_INSTANCES));
+ }
- if(componentProperties.get(componentDisplayName).get(MAX_INSTANCES) != null) {
- nodeTemplate.getProperties().put(MAX_INSTANCES,
- componentProperties.get(componentDisplayName).get(MAX_INSTANCES));
- }
- }
+ if (componentProperties.get(componentDisplayName).get(MAX_INSTANCES) != null) {
+ nodeTemplate.getProperties().put(MAX_INSTANCES,
+ componentProperties.get(componentDisplayName).get(MAX_INSTANCES));
+ }
+ }
- enrichRequirements(sourceToTargetDependencies, componentDisplayName, nodeTemplate,
- componentDisplayNameToNodeTempalteIds, serviceTemplate, toscaModel);
- }
+ enrichRequirements(sourceToTargetDependencies, componentDisplayName, nodeTemplate,
+ componentDisplayNameToNodeTempalteIds, serviceTemplate, toscaModel);
+ }
});
- return errors;
- }
+ return errors;
+ }
- private Map<String,List<String>> populateAllNodeTemplateIdForComponent(Map<String,
- NodeTemplate> node_templates, ServiceTemplate serviceTemplate, ToscaServiceModel
- toscaModel) {
+ private Map<String, List<String>> populateAllNodeTemplateIdForComponent(Map<String, NodeTemplate> node_templates,
+ ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaModel) {
- Map<String,List<String>> componentDisplayNameToNodeTempalteIds = new HashMap<String,
- List<String>>();
+ Map<String, List<String>> componentDisplayNameToNodeTempalteIds = new HashMap<>();
- //set dependency target
- node_templates.keySet()
- .stream()
- .forEach(nodeTemplateId -> {
+ //set dependency target
+ node_templates.keySet().stream().forEach(nodeTemplateId -> {
- final Optional<NodeTemplate> nodeTemplateById =
- toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId);
- final NodeTemplate nodeTemplate =
- nodeTemplateById.isPresent() ? nodeTemplateById.get() : null;
+ final Optional<NodeTemplate> nodeTemplateById =
+ toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId);
+ final NodeTemplate nodeTemplate = nodeTemplateById.isPresent() ? nodeTemplateById.get() : null;
- if (toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate,
- toscaModel)) {
+ if (toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate, toscaModel)) {
- String componentDisplayName = getComponentDisplayName(nodeTemplateId, nodeTemplate);
+ String componentDisplayName = getComponentDisplayName(nodeTemplateId, nodeTemplate);
- if (componentDisplayNameToNodeTempalteIds.containsKey(componentDisplayName)) {
- componentDisplayNameToNodeTempalteIds.get(componentDisplayName).add(nodeTemplateId);
- } else {
- List<String> nodeTemplateIds = new ArrayList<String>();
- nodeTemplateIds.add(nodeTemplateId);
- componentDisplayNameToNodeTempalteIds.put(componentDisplayName, nodeTemplateIds);
- }
+ if (componentDisplayNameToNodeTempalteIds.containsKey(componentDisplayName)) {
+ componentDisplayNameToNodeTempalteIds.get(componentDisplayName).add(nodeTemplateId);
+ } else {
+ List<String> nodeTemplateIds = new ArrayList<>();
+ nodeTemplateIds.add(nodeTemplateId);
+ componentDisplayNameToNodeTempalteIds.put(componentDisplayName, nodeTemplateIds);
+ }
- }
+ }
});
- return componentDisplayNameToNodeTempalteIds;
- }
-
- private void enrichRequirements(Map<String, List<String>> sourceToTargetDependencies,
- String componentDisplayName, NodeTemplate nodeTemplate,
- Map<String, List<String>> componentDisplayNameToNodeTempalteIds,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
- final List<String> targets = sourceToTargetDependencies.get(componentDisplayName);
- if (CollectionUtils.isEmpty(targets)) {
- return;
+ return componentDisplayNameToNodeTempalteIds;
}
- for (String target : targets) {
- List<String> targetNodeTemplateIds = componentDisplayNameToNodeTempalteIds.get(target);
- if (CollectionUtils.isEmpty(targetNodeTemplateIds)) {
- continue;
- }
- for (String targetNodeTemplateId : targetNodeTemplateIds) {
- Optional<String> dependencyRequirementKey =
- getDependencyRequirementKey(serviceTemplate, componentDisplayName, nodeTemplate, toscaServiceModel);
- if (dependencyRequirementKey.isPresent()) {
- RequirementAssignment requirementAssignment = new RequirementAssignment();
- requirementAssignment.setCapability(NATIVE_NODE);
- requirementAssignment.setRelationship(NATIVE_DEPENDS_ON);
- requirementAssignment.setNode(targetNodeTemplateId);
- DataModelUtil.addRequirementAssignment(nodeTemplate, dependencyRequirementKey.get(), requirementAssignment);
+ private void enrichRequirements(Map<String, List<String>> sourceToTargetDependencies, String componentDisplayName,
+ NodeTemplate nodeTemplate,
+ Map<String, List<String>> componentDisplayNameToNodeTempalteIds,
+ ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
+ final List<String> targets = sourceToTargetDependencies.get(componentDisplayName);
+ if (CollectionUtils.isEmpty(targets)) {
+ return;
+ }
+
+ for (String target : targets) {
+ List<String> targetNodeTemplateIds = componentDisplayNameToNodeTempalteIds.get(target);
+ if (CollectionUtils.isEmpty(targetNodeTemplateIds)) {
+ continue;
+ }
+ for (String targetNodeTemplateId : targetNodeTemplateIds) {
+ Optional<String> dependencyRequirementKey =
+ getDependencyRequirementKey(serviceTemplate, componentDisplayName, nodeTemplate,
+ toscaServiceModel);
+ if (dependencyRequirementKey.isPresent()) {
+ RequirementAssignment requirementAssignment = new RequirementAssignment();
+ requirementAssignment.setCapability(NATIVE_NODE);
+ requirementAssignment.setRelationship(NATIVE_DEPENDS_ON);
+ requirementAssignment.setNode(targetNodeTemplateId);
+ DataModelUtil.addRequirementAssignment(nodeTemplate, dependencyRequirementKey.get(),
+ requirementAssignment);
+ }
+ }
}
- }
}
- }
-
- private Optional<String> getDependencyRequirementKey(ServiceTemplate serviceTemplate,
- String componentDisplayName,
- NodeTemplate nodeTemplate,
- ToscaServiceModel toscaServiceModel) {
- String nodeType = nodeTemplate.getType();
- NodeType flatNodeType = (NodeType) toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType, serviceTemplate, toscaServiceModel);
- List<Map<String, RequirementDefinition>> flatNodeTypeRequirements = flatNodeType.getRequirements();
- if (Objects.isNull(flatNodeTypeRequirements)) {
- return Optional.empty() ;
+
+ private Optional<String> getDependencyRequirementKey(ServiceTemplate serviceTemplate, String componentDisplayName,
+ NodeTemplate nodeTemplate,
+ ToscaServiceModel toscaServiceModel) {
+ String nodeType = nodeTemplate.getType();
+ NodeType flatNodeType = (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType,
+ serviceTemplate, toscaServiceModel).getFlatEntity();
+ List<Map<String, RequirementDefinition>> flatNodeTypeRequirements = flatNodeType.getRequirements();
+ if (Objects.isNull(flatNodeTypeRequirements)) {
+ return Optional.empty();
+ }
+ for (Map<String, RequirementDefinition> requirementDefinitionMap : flatNodeTypeRequirements) {
+ String requirementKey = requirementDefinitionMap.keySet().iterator().next();
+ String expectedKey = ToscaConstants.DEPENDS_ON_REQUIREMENT_ID + "_" + componentDisplayName;
+ if (requirementKey.equals(expectedKey)) {
+ return Optional.of(requirementKey);
+ }
+ }
+ return Optional.empty();
}
- for (Map<String, RequirementDefinition> requirementDefinitionMap : flatNodeTypeRequirements) {
- String requirementKey = requirementDefinitionMap.keySet().iterator().next();
- String expectedKey = ToscaConstants.DEPENDS_ON_REQUIREMENT_ID + "_" + componentDisplayName;
- if (requirementKey.equals(expectedKey)) {
- return Optional.of(requirementKey);
- }
+
+ private String getComponentDisplayName(String nodeTemplateId, NodeTemplate nodeTemplate) {
+ String componentDisplayName;
+ if (nodeTemplateId.contains(ABSTRACT_NODE_TEMPLATE_ID_PREFIX)) {
+ String removedPrefix = nodeTemplateId.split(ABSTRACT_NODE_TEMPLATE_ID_PREFIX)[1];
+ final String[] removedSuffix = removedPrefix.split("_\\d");
+ componentDisplayName = removedSuffix[0];
+ } else {
+ final String type = nodeTemplate.getType();
+ final String[] splitted = type.split("\\.");
+ componentDisplayName = splitted[splitted.length - 1];
+
+ }
+ return componentDisplayName;
}
- return Optional.empty();
- }
-
- private String getComponentDisplayName(String nodeTemplateId, NodeTemplate nodeTemplate) {
- String componentDisplayName = null;
- if (nodeTemplateId.contains(ABSTRACT_NODE_TEMPLATE_ID_PREFIX)) {
- String removedPrefix = nodeTemplateId.split(ABSTRACT_NODE_TEMPLATE_ID_PREFIX)[1];
- final String[] removedSuffix = removedPrefix.split("_\\d");
- componentDisplayName = removedSuffix[0];
- } else {
- final String type = nodeTemplate.getType();
- final String[] splitted = type.split("\\.");
- componentDisplayName = splitted[splitted.length - 1];
+ private String getValueFromQuestionnaireDetails(Map<String, Map<String, Object>> componentTypetoParams,
+ String componentDisplayName, String propertyName) {
+ return (String) componentTypetoParams.get(componentDisplayName).get(propertyName);
}
- return componentDisplayName;
- }
-
- private String getValueFromQuestionnaireDetails(
- Map<String, Map<String, Object>> componentTypetoParams, String componentDisplayName, String
- propertyName) {
- return (String) componentTypetoParams.get(componentDisplayName).get(propertyName);
- }
-
- private void setProperty(NodeTemplate nodeTemplate, String key, String value) {
- if (!StringUtils.isEmpty(value)) {
- //YamlUtil throws IllegalStateException("duplicate key: " + key) if key is already present.
- // So first removing and then populating same key with new updated value
- nodeTemplate.getProperties().remove(key);
- nodeTemplate.getProperties().put(key, value);
+
+ private void setProperty(NodeTemplate nodeTemplate, String key, String value) {
+ if (!StringUtils.isEmpty(value)) {
+ //YamlUtil throws IllegalStateException("duplicate key: " + key) if key is already present.
+ // So first removing and then populating same key with new updated value
+ nodeTemplate.getProperties().remove(key);
+ nodeTemplate.getProperties().put(key, value);
+ }
}
- }
-
- private Boolean getValue(String value) {
- String returnValue = null;
- switch (value) {
- case "YES" :
- return true;
- case "NO" :
- return false;
- default: return null;
+
+ private Boolean getValue(String value) {
+ String returnValue = null;
+ switch (value) {
+ case "YES":
+ return true;
+ case "NO":
+ return false;
+ default:
+ return null;
+ }
}
- }
- private ComponentQuestionnaireData getComponentQuestionnaireData() {
- if (componentQuestionnaireData == null) {
- componentQuestionnaireData = new ComponentQuestionnaireData();
+ private ComponentQuestionnaireData getComponentQuestionnaireData() {
+ if (componentQuestionnaireData == null) {
+ componentQuestionnaireData = new ComponentQuestionnaireData();
+ }
+ return componentQuestionnaireData;
}
- return componentQuestionnaireData;
- }
}
diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java
index 9ea8ba752a..1501fa1c9f 100644
--- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java
+++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java
@@ -29,198 +29,191 @@ import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNode
*/
public class GeneratorUtils {
- private GeneratorUtils() {
- // prevent instantiation
- }
-
- //TODO : Read from configuration
- private static final List<String> SUPPORTED_CAPABILITIES = Arrays.asList("host", "os", "endpoint", "scalable");
- private static final List<String> SUPPORTED_REQUIREMENTS = Collections.singletonList("link");
-
- /**
- * Add service template to tosca service model.
- *
- * @param toscaServiceModel the tosca service model
- * @param serviceTemplate the service template
- */
- public static void addServiceTemplateToToscaServiceModel(ToscaServiceModel toscaServiceModel,
- ServiceTemplate serviceTemplate) {
-
- String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate);
- Map<String, ServiceTemplate> serviceTemplates = toscaServiceModel.getServiceTemplates();
- if (!serviceTemplates.containsKey(serviceTemplateFileName)) {
- ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
- }
- toscaServiceModel.setServiceTemplates(serviceTemplates);
- }
-
- /**
- * Gets substitution node type exposed connection points.
- *
- * @param substitutionNodeType the substitution node type
- * @param substitutionServiceTemplate the substitution service template
- * @param toscaServiceModel the tosca service model
- * @return the substitution node type exposed connection points
- */
- public static Map<String, Map<String, List<String>>>
- getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
- ServiceTemplate substitutionServiceTemplate,
- ToscaServiceModel toscaServiceModel) {
-
- Map<String, NodeTemplate> nodeTemplates =
- substitutionServiceTemplate.getTopology_template().getNode_templates();
- String nodeTemplateId;
- NodeTemplate nodeTemplate;
- String nodeType;
- Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
- if (nodeTemplates == null) {
- return substitutionMapping;
+ private GeneratorUtils() {
+ // prevent instantiation
}
- try {
- Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
- Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
- substitutionMapping.put("capability", capabilitySubstitutionMapping);
- substitutionMapping.put("requirement", requirementSubstitutionMapping);
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
- List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
- new HashMap<>();
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
- Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
-
- ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
- nodeTemplateId = entry.getKey();
- nodeTemplate = entry.getValue();
- nodeType = nodeTemplate.getType();
- NodeType flatNodeType = (NodeType) toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType, substitutionServiceTemplate,
- toscaServiceModel);
- // get requirements
- nodeTypeRequirementsDefinition =
- getNodeTypeRequirements(flatNodeType, nodeTemplateId, substitutionServiceTemplate,
- requirementSubstitutionMapping);
- nodeTemplateRequirementsAssignment =
- DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
- fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
- //set substitution node type requirements
- exposedRequirementsDefinition =
- toscaAnalyzerService.calculateExposedRequirements(nodeTypeRequirementsDefinition,
- nodeTemplateRequirementsAssignment);
-
-
- //Filter unsupported requirements
- Iterator<Map<String, RequirementDefinition>> iterator =
- exposedRequirementsDefinition.iterator();
- while (iterator.hasNext()) {
- Map<String, RequirementDefinition> requirementDefinitionMap = iterator.next();
- for (Map.Entry<String, RequirementDefinition> requirementDefinitionEntry :
- requirementDefinitionMap.entrySet()) {
- String requirementKey = requirementDefinitionEntry.getKey();
- if (!SUPPORTED_REQUIREMENTS.contains(requirementKey)) {
- iterator.remove();
- }
- }
+ //TODO : Read from configuration
+ private static final List<String> SUPPORTED_CAPABILITIES = Arrays.asList("host", "os", "endpoint", "scalable");
+ private static final List<String> SUPPORTED_REQUIREMENTS = Collections.singletonList("link");
+
+ /**
+ * Add service template to tosca service model.
+ *
+ * @param toscaServiceModel the tosca service model
+ * @param serviceTemplate the service template
+ */
+ public static void addServiceTemplateToToscaServiceModel(ToscaServiceModel toscaServiceModel,
+ ServiceTemplate serviceTemplate) {
+
+ String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate);
+ Map<String, ServiceTemplate> serviceTemplates = toscaServiceModel.getServiceTemplates();
+ if (!serviceTemplates.containsKey(serviceTemplateFileName)) {
+ ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
}
- addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
- nodeTemplateId);
- //get capabilities
- addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
- capabilitySubstitutionMapping, nodeType,
- nodeTemplateId, substitutionServiceTemplate, toscaServiceModel);
- }
-
- exposedCapabilitiesDefinition =
- toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
- fullFilledRequirementsDefinition);
-
- //Filter unsupported capabilities
- Iterator<Map.Entry<String, CapabilityDefinition>> iterator = exposedCapabilitiesDefinition
- .entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry<String, CapabilityDefinition> capabilityDefinitionEntry = iterator.next();
- //Expected Capability is of the format <capabilityId>_<componentName>
- String capabilityKey = capabilityDefinitionEntry.getKey().split("_")[0];
- if (!SUPPORTED_CAPABILITIES.contains(capabilityKey)) {
- iterator.remove();
+ toscaServiceModel.setServiceTemplates(serviceTemplates);
+ }
+
+ /**
+ * Gets substitution node type exposed connection points.
+ *
+ * @param substitutionNodeType the substitution node type
+ * @param substitutionServiceTemplate the substitution service template
+ * @param toscaServiceModel the tosca service model
+ * @return the substitution node type exposed connection points
+ */
+ public static Map<String, Map<String, List<String>>> getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
+ ServiceTemplate substitutionServiceTemplate,
+ ToscaServiceModel toscaServiceModel) {
+
+ Map<String, NodeTemplate> nodeTemplates =
+ substitutionServiceTemplate.getTopology_template().getNode_templates();
+ String nodeTemplateId;
+ NodeTemplate nodeTemplate;
+ String nodeType;
+ Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
+ if (nodeTemplates == null) {
+ return substitutionMapping;
}
- }
- DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
- } catch (Exception ex) {
- return null;
+ try {
+ Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
+ Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
+ substitutionMapping.put("capability", capabilitySubstitutionMapping);
+ substitutionMapping.put("requirement", requirementSubstitutionMapping);
+ List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
+ List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
+ Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
+ Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
+
+ ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
+ for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
+ nodeTemplateId = entry.getKey();
+ nodeTemplate = entry.getValue();
+ nodeType = nodeTemplate.getType();
+ NodeType flatNodeType = (NodeType) toscaAnalyzerService
+ .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType,
+ substitutionServiceTemplate, toscaServiceModel)
+ .getFlatEntity();
+ // get requirements
+ nodeTypeRequirementsDefinition =
+ getNodeTypeRequirements(flatNodeType, nodeTemplateId, substitutionServiceTemplate,
+ requirementSubstitutionMapping);
+ nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
+ fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
+ //set substitution node type requirements
+ exposedRequirementsDefinition = toscaAnalyzerService
+ .calculateExposedRequirements(nodeTypeRequirementsDefinition,
+ nodeTemplateRequirementsAssignment);
+
+
+ //Filter unsupported requirements
+ Iterator<Map<String, RequirementDefinition>> iterator = exposedRequirementsDefinition.iterator();
+ while (iterator.hasNext()) {
+ Map<String, RequirementDefinition> requirementDefinitionMap = iterator.next();
+ for (Map.Entry<String, RequirementDefinition> requirementDefinitionEntry : requirementDefinitionMap
+ .entrySet()) {
+ String requirementKey = requirementDefinitionEntry.getKey();
+ if (!SUPPORTED_REQUIREMENTS.contains(requirementKey)) {
+ iterator.remove();
+ }
+ }
+ }
+ addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
+ nodeTemplateId);
+ //get capabilities
+ addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping,
+ nodeType, nodeTemplateId, substitutionServiceTemplate, toscaServiceModel);
+ }
+
+ exposedCapabilitiesDefinition = toscaAnalyzerService
+ .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
+ fullFilledRequirementsDefinition);
+
+ //Filter unsupported capabilities
+ Iterator<Map.Entry<String, CapabilityDefinition>> iterator =
+ exposedCapabilitiesDefinition.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry<String, CapabilityDefinition> capabilityDefinitionEntry = iterator.next();
+ //Expected Capability is of the format <capabilityId>_<componentName>
+ String capabilityKey = capabilityDefinitionEntry.getKey().split("_")[0];
+ if (!SUPPORTED_CAPABILITIES.contains(capabilityKey)) {
+ iterator.remove();
+ }
+ }
+
+ DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
+ } catch (Exception ex) {
+ return null;
+ }
+ return substitutionMapping;
}
- return substitutionMapping;
- }
-
- /**
- * Gets node type requirements.
- *
- * @param flatNodeType the flat node type
- * @param templateName the template name
- * @param serviceTemplate the service template
- * @param requirementSubstitutionMapping the requirement substitution mapping
- * @return the node type requirements
- */
- public static List<Map<String, RequirementDefinition>> getNodeTypeRequirements(
- NodeType flatNodeType,
- String templateName,
- ServiceTemplate serviceTemplate,
- Map<String, List<String>> requirementSubstitutionMapping) {
- List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
- List<String> requirementMapping;
- if (flatNodeType.getRequirements() != null) {
- for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
- for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
- .entrySet()) {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil
- .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
- RequirementDefinition.class);
- if (requirementNodeEntryValue.getOccurrences() == null) {
- requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
- }
- Map<String, RequirementDefinition> requirementDef = new HashMap<>();
- requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
- DataModelUtil.addRequirementToList(requirementList, requirementDef);
- requirementMapping = new ArrayList<>();
- requirementMapping.add(templateName);
- requirementMapping.add(requirementNodeEntry.getKey());
- requirementSubstitutionMapping
- .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping);
- if (requirementNodeEntryValue.getNode() == null) {
- requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
- }
+
+ /**
+ * Gets node type requirements.
+ *
+ * @param flatNodeType the flat node type
+ * @param templateName the template name
+ * @param serviceTemplate the service template
+ * @param requirementSubstitutionMapping the requirement substitution mapping
+ * @return the node type requirements
+ */
+ public static List<Map<String, RequirementDefinition>> getNodeTypeRequirements(NodeType flatNodeType,
+ String templateName,
+ ServiceTemplate serviceTemplate,
+ Map<String, List<String>> requirementSubstitutionMapping) {
+ List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
+ List<String> requirementMapping;
+ if (flatNodeType.getRequirements() != null) {
+ for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
+ for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap.entrySet()) {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil.yamlToObject(
+ toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
+ RequirementDefinition.class);
+ if (requirementNodeEntryValue.getOccurrences() == null) {
+ requirementNodeEntryValue.setOccurrences(new Object[] {1, 1});
+ }
+ Map<String, RequirementDefinition> requirementDef = new HashMap<>();
+ requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
+ DataModelUtil.addRequirementToList(requirementList, requirementDef);
+ requirementMapping = new ArrayList<>();
+ requirementMapping.add(templateName);
+ requirementMapping.add(requirementNodeEntry.getKey());
+ requirementSubstitutionMapping
+ .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping);
+ if (requirementNodeEntryValue.getNode() == null) {
+ requirementNodeEntryValue.setOccurrences(new Object[] {1, 1});
+ }
+ }
+ }
}
- }
+ return requirementList;
}
- return requirementList;
- }
-
- private static void addNodeTypeCapabilitiesToSubMapping(
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
- Map<String, List<String>> capabilitySubstitutionMapping, String type, String templateName,
- ServiceTemplate substitutionServiceTemplate, ToscaServiceModel toscaServiceModel) {
- ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- NodeType flatNodeType = (NodeType) toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE, type, substitutionServiceTemplate,
- toscaServiceModel);
- String capabilityKey;
- List<String> capabilityMapping;
- if (flatNodeType.getCapabilities() != null) {
- for (Map.Entry<String, CapabilityDefinition> capabilityNodeEntry : flatNodeType
- .getCapabilities()
- .entrySet()) {
- capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName;
- nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
- capabilityMapping = new ArrayList<>();
- capabilityMapping.add(templateName);
- capabilityMapping.add(capabilityNodeEntry.getKey());
- capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
- }
+
+ private static void addNodeTypeCapabilitiesToSubMapping(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
+ Map<String, List<String>> capabilitySubstitutionMapping,
+ String type, String templateName,
+ ServiceTemplate substitutionServiceTemplate,
+ ToscaServiceModel toscaServiceModel) {
+ ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
+ NodeType flatNodeType = (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, type,
+ substitutionServiceTemplate, toscaServiceModel).getFlatEntity();
+ String capabilityKey;
+ List<String> capabilityMapping;
+ if (flatNodeType.getCapabilities() != null) {
+ for (Map.Entry<String, CapabilityDefinition> capabilityNodeEntry : flatNodeType.getCapabilities()
+ .entrySet()) {
+ capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName;
+ nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
+ capabilityMapping = new ArrayList<>();
+ capabilityMapping.add(templateName);
+ capabilityMapping.add(capabilityNodeEntry.getKey());
+ capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
+ }
+ }
}
- }
}
diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java
index 33afabc3a5..d8e81422a3 100644
--- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java
+++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java
@@ -105,281 +105,263 @@ import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatT
*/
public class HeatToToscaUtil {
- private static final Logger LOGGER = LoggerFactory.getLogger(HeatToToscaUtil.class);
- private static final String FQ_NAME = "fq_name";
- private static final String GET_PARAM = "get_param";
- private static final String GET_ATTR = "get_attr";
- private static final String GET_RESOURCE = "get_resource";
- private static final String UNDERSCORE = "_";
- private static final String WORDS_REGEX = "(\\w+)";
- private static final String PORT_RESOURCE_ID_REGEX_SUFFIX = "(_\\d+)*";
- private static final String PORT_RESOURCE_ID_REGEX_PREFIX =
- WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX;
- private static final String PORT_INT_RESOURCE_ID_REGEX_PREFIX = PORT_RESOURCE_ID_REGEX_PREFIX
- + UNDERSCORE + "int_"+ WORDS_REGEX + UNDERSCORE;
- private static final String SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX =
- PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "subint_"+ WORDS_REGEX + UNDERSCORE;
- private static final String SUB_INTERFACE_REGEX = WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX
- + "_subint_(\\w_+)*vmi" + PORT_RESOURCE_ID_REGEX_SUFFIX;
-
- /**
- * Load and translate template data translator output.
- *
- * @param fileNameContentMap the file name content map
- * @return the translator output
- */
- public static TranslatorOutput loadAndTranslateTemplateData(
- FileContentHandler fileNameContentMap) {
- HeatToToscaTranslator heatToToscaTranslator =
- HeatToToscaTranslatorFactory.getInstance().createInterface();
-
- try (InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME)) {
- heatToToscaTranslator
- .addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
- } catch (IOException e) {
- throw new RuntimeException("Failed to read manifest", e);
- }
-
- fileNameContentMap.getFileList().stream()
- .filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))).forEach(
- fileName -> heatToToscaTranslator
- .addFile(fileName, FileUtils.toByteArray
- (fileNameContentMap.getFileContent(fileName))));
-
- Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate();
- if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) {
- TranslatorOutput translatorOutput = new TranslatorOutput();
- translatorOutput.setErrorMessages(errors);
- return translatorOutput;
- }
-
- try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) {
- heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
- return heatToToscaTranslator.translate();
- } catch (IOException e) {
- // rethrow as a RuntimeException to keep the signature backward compatible
- throw new RuntimeException("Failed to read Heat template tree", e);
- }
- }
-
-
- private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) {
- HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap);
- heatTreeManager.createTree();
- HeatStructureTree tree = heatTreeManager.getTree();
- ValidationStructureList validationStructureList = new ValidationStructureList(tree);
- return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON);
- }
-
- /**
- * Build list of files to search optional.
- *
- * @param heatFileName the heat file name
- * @param filesDataList the files data list
- * @param types the types
- * @return the optional
- */
- public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName,
- List<FileData> filesDataList,
- FileData.Type... types) {
- List<FileData> list = new ArrayList<>(filesDataList);
- Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList);
- if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) {
- list.addAll(resourceFileData.get().getData());
- }
- return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
- }
-
- /**
- * Gets filtered list of file data by types.
- *
- * @param filesToSearch the files to search
- * @param types the types
- * @return the filtered list of file data by types
- */
- public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch,
- FileData.Type... types) {
- return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types))
- .collect(Collectors.toList());
- }
-
- /**
- * Gets file data from the list according to the input heat file name.
- *
- * @param heatFileName the heat file name
- * @param fileDataList the file data list
- * @return the file data
- */
- public static Optional<FileData> getFileData(String heatFileName,
- Collection<FileData> fileDataList) {
- for (FileData file : fileDataList) {
- if (file.getFile().equals(heatFileName)) {
- return Optional.of(file);
- }
- }
- return Optional.empty();
- }
-
- /**
- * Gets file data which is supported by the translator, from the context according the input heat
- * file name.
- *
- * @param heatFileName the heat file name
- * @param context the translation context
- * @return the file data
- */
- public static FileData getFileData(String heatFileName, TranslationContext context) {
- List<FileData> fileDataList = context.getManifest().getContent().getData();
- for (FileData fileData : fileDataList) {
- if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType())
- && fileData.getFile().equals(heatFileName)) {
- return fileData;
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(HeatToToscaUtil.class);
+ private static final String FQ_NAME = "fq_name";
+ private static final String GET_PARAM = "get_param";
+ private static final String GET_ATTR = "get_attr";
+ private static final String GET_RESOURCE = "get_resource";
+ private static final String UNDERSCORE = "_";
+ private static final String WORDS_REGEX = "(\\w+)";
+ private static final String PORT_RESOURCE_ID_REGEX_SUFFIX = "(_\\d+)*";
+ private static final String PORT_RESOURCE_ID_REGEX_PREFIX = WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX;
+ private static final String PORT_INT_RESOURCE_ID_REGEX_PREFIX =
+ PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "int_" + WORDS_REGEX + UNDERSCORE;
+ private static final String SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX =
+ PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "subint_" + WORDS_REGEX + UNDERSCORE;
+ private static final String SUB_INTERFACE_REGEX =
+ WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX + "_subint_(\\w_+)*vmi" + PORT_RESOURCE_ID_REGEX_SUFFIX;
+
+ /**
+ * Load and translate template data translator output.
+ *
+ * @param fileNameContentMap the file name content map
+ * @return the translator output
+ */
+ public static TranslatorOutput loadAndTranslateTemplateData(FileContentHandler fileNameContentMap) {
+ HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
+
+ try (InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME)) {
+ heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to read manifest", e);
+ }
+
+ fileNameContentMap.getFileList().stream().filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME)))
+ .forEach(fileName -> heatToToscaTranslator.addFile(fileName,
+ FileUtils.toByteArray(fileNameContentMap.getFileContent(fileName))));
+
+ Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate();
+ if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) {
+ TranslatorOutput translatorOutput = new TranslatorOutput();
+ translatorOutput.setErrorMessages(errors);
+ return translatorOutput;
+ }
+
+ try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) {
+ heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
+ return heatToToscaTranslator.translate();
+ } catch (IOException e) {
+ // rethrow as a RuntimeException to keep the signature backward compatible
+ throw new RuntimeException("Failed to read Heat template tree", e);
+ }
}
- return null;
- }
- static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList,
- Set<FileData.Type> typeFilter,
- TranslationContext translationContext) {
- FileDataCollection fileDataCollection = new FileDataCollection();
- Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter);
- Set<String> referenced = new HashSet<>();
- for (FileData fileData : filteredFiles.values()) {
- String fileName = fileData.getFile();
+ private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) {
+ HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap);
+ heatTreeManager.createTree();
+ HeatStructureTree tree = heatTreeManager.getTree();
+ ValidationStructureList validationStructureList = new ValidationStructureList(tree);
+ return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON);
+ }
+
+ /**
+ * Build list of files to search optional.
+ *
+ * @param heatFileName the heat file name
+ * @param filesDataList the files data list
+ * @param types the types
+ * @return the optional
+ */
+ public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName, List<FileData> filesDataList,
+ FileData.Type... types) {
+ List<FileData> list = new ArrayList<>(filesDataList);
+ Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList);
+ if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) {
+ list.addAll(resourceFileData.get().getData());
+ }
+ return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
+ }
+
+ /**
+ * Gets filtered list of file data by types.
+ *
+ * @param filesToSearch the files to search
+ * @param types the types
+ * @return the filtered list of file data by types
+ */
+ public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch,
+ FileData.Type... types) {
+ return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types)).collect(Collectors.toList());
+ }
+
+ /**
+ * Gets file data from the list according to the input heat file name.
+ *
+ * @param heatFileName the heat file name
+ * @param fileDataList the file data list
+ * @return the file data
+ */
+ public static Optional<FileData> getFileData(String heatFileName, Collection<FileData> fileDataList) {
+ for (FileData file : fileDataList) {
+ if (file.getFile().equals(heatFileName)) {
+ return Optional.of(file);
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Gets file data which is supported by the translator, from the context according the input heat
+ * file name.
+ *
+ * @param heatFileName the heat file name
+ * @param context the translation context
+ * @return the file data
+ */
+ public static FileData getFileData(String heatFileName, TranslationContext context) {
+ List<FileData> fileDataList = context.getManifest().getContent().getData();
+ for (FileData fileData : fileDataList) {
+ if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) && fileData.getFile()
+ .equals(heatFileName)) {
+ return fileData;
+ }
+ }
+ return null;
+ }
+
+ static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList, Set<FileData.Type> typeFilter,
+ TranslationContext translationContext) {
+ FileDataCollection fileDataCollection = new FileDataCollection();
+ Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter);
+ Set<String> referenced = new HashSet<>();
+
+ for (FileData fileData : filteredFiles.values()) {
+ String fileName = fileData.getFile();
+
+ if (FileData.isHeatFile(fileData.getType())) {
+ if (fileData.getBase() != null && fileData.getBase()) {
+ fileDataCollection.addBaseFiles(fileData);
+ }
+ HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil().yamlToObject(
+ translationContext.getFileContent(fileName), HeatOrchestrationTemplate.class);
+ if (MapUtils.isNotEmpty(heatOrchestrationTemplate.getResources())) {
+ applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext, fileDataCollection,
+ filteredFiles, referenced);
+ }
+
+ } else {
+ fileDataCollection.addArtifactFiles(fileData);
+ filteredFiles.remove(fileData.getFile());
+ }
+ }
- if (FileData.isHeatFile(fileData.getType())) {
- if (fileData.getBase() != null && fileData.getBase()) {
- fileDataCollection.addBaseFiles(fileData);
+ referenced.forEach(filteredFiles::remove);
+ if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
+ for (FileData fileData : fileDataCollection.getBaseFile()) {
+ filteredFiles.remove(fileData.getFile());
+ }
}
- HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil()
- .yamlToObject(translationContext.getFileContent(fileName),
- HeatOrchestrationTemplate.class);
- if (MapUtils.isNotEmpty(heatOrchestrationTemplate.getResources())) {
- applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext,
- fileDataCollection, filteredFiles, referenced);
+ fileDataCollection.setAddOnFiles(filteredFiles.values());
+ return fileDataCollection;
+ }
+
+ private static void applyFilterOnFileCollection(HeatOrchestrationTemplate heatOrchestrationTemplate,
+ TranslationContext translationContext,
+ FileDataCollection fileDataCollection,
+ Map<String, FileData> filteredFiles,
+ Set<String> referenced) {
+ List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values());
+
+ for (Resource resource : heatOrchestrationTemplate.getResources().values()) {
+ if (filenames.contains(resource.getType())) {
+ handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced, resource.getType());
+ } else if (resource.getType().equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
+ handleResourceGrpNestedFile(resource, translationContext, fileDataCollection, filteredFiles, filenames,
+ referenced);
+ }
}
+ }
- } else {
- fileDataCollection.addArtifactFiles(fileData);
- filteredFiles.remove(fileData.getFile());
- }
+ private static void handleResourceGrpNestedFile(Resource resource, TranslationContext translationContext,
+ FileDataCollection fileDataCollection,
+ Map<String, FileData> filteredFiles, List<String> filenames,
+ Set<String> referenced) {
+ Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
+ Object innerTypeDef = ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
+ if (innerTypeDef instanceof String) {
+ String internalResourceType = (String) innerTypeDef;
+ if (filenames.contains(internalResourceType)) {
+ handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced,
+ internalResourceType);
+ }
+ }
}
- referenced.forEach(filteredFiles::remove);
- if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
- for (FileData fileData : fileDataCollection.getBaseFile()) {
- filteredFiles.remove(fileData.getFile());
- }
+ private static void handleNestedFile(TranslationContext translationContext, FileDataCollection fileDataCollection,
+ Map<String, FileData> filteredFiles, Set<String> referenced,
+ String nestedFileName) {
+ referenced.add(nestedFileName);
+ fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
+ translationContext.getNestedHeatsFiles().add(nestedFileName);
}
- fileDataCollection.setAddOnFiles(filteredFiles.values());
- return fileDataCollection;
- }
-
- private static void applyFilterOnFileCollection(
- HeatOrchestrationTemplate heatOrchestrationTemplate,
- TranslationContext translationContext,
- FileDataCollection fileDataCollection, Map<String, FileData> filteredFiles,
- Set<String> referenced) {
- List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values());
-
- for (Resource resource : heatOrchestrationTemplate.getResources().values()) {
- if (filenames.contains(resource.getType())) {
- handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced,
- resource.getType());
- } else if (resource.getType()
- .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
- handleResourceGrpNestedFile(resource, translationContext, fileDataCollection,
- filteredFiles, filenames, referenced);
- }
+
+ private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList,
+ Set<FileData.Type> typesToGet) {
+ Map<String, FileData> filtered = new HashMap<>();
+ fileDataList.stream().filter(file -> typesToGet.contains(file.getType()))
+ .forEach(file -> filtered.put(file.getFile(), file));
+ return filtered;
}
- }
-
- private static void handleResourceGrpNestedFile(Resource resource,
- TranslationContext translationContext,
- FileDataCollection fileDataCollection,
- Map<String, FileData> filteredFiles,
- List<String> filenames,
- Set<String> referenced) {
- Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
- Object innerTypeDef = ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
- if (innerTypeDef instanceof String) {
- String internalResourceType = (String) innerTypeDef;
- if (filenames.contains(internalResourceType)) {
- handleNestedFile(translationContext, fileDataCollection, filteredFiles,
- referenced, internalResourceType);
- }
+
+ private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
+ return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
}
- }
-
- private static void handleNestedFile(TranslationContext translationContext,
- FileDataCollection fileDataCollection,
- Map<String, FileData> filteredFiles, Set<String> referenced,
- String nestedFileName) {
- referenced.add(nestedFileName);
- fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
- translationContext.getNestedHeatsFiles().add(nestedFileName);
- }
-
- private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList,
- Set<FileData.Type> typesToGet) {
- Map<String, FileData> filtered = new HashMap<>();
- fileDataList.stream().filter(file -> typesToGet.contains(file.getType()))
- .forEach(file -> filtered.put(file.getFile(), file));
- return filtered;
- }
-
- private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
- return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
- }
-
- /**
- * Extract attached resource id optional.
- *
- * @param translateTo the translate to
- * @param propertyName the property name
- * @return the optional
- */
- public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo,
- String propertyName) {
- Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
- if (propertyValue == null) {
- return Optional.empty();
- }
- return extractAttachedResourceId(translateTo.getHeatFileName(),
- translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue);
- }
-
- /**
- * Extract attached resource id optional.
- *
- * @param heatFileName the heat file name
- * @param heatOrchestrationTemplate the heat orchestration template
- * @param context the context
- * @param propertyValue the property value
- * @return the optional
- */
- public static Optional<AttachedResourceId> extractAttachedResourceId(
- String heatFileName,
- HeatOrchestrationTemplate heatOrchestrationTemplate,
- TranslationContext context,
- Object propertyValue) {
-
- Object entity;
- Object translatedId;
-
- if (Objects.isNull(propertyValue)) {
- return Optional.empty();
- }
-
- ReferenceType referenceType = ReferenceType.OTHER;
- if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
- Map<String, Object> propMap = (Map) propertyValue;
- Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
- entity = entry.getValue();
- String key = entry.getKey();
- referenceType = getReferenceTypeFromAttachedResouce(key);
+
+ /**
+ * Extract attached resource id optional.
+ *
+ * @param translateTo the translate to
+ * @param propertyName the property name
+ * @return the optional
+ */
+ public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo, String propertyName) {
+ Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
+ if (propertyValue == null) {
+ return Optional.empty();
+ }
+ return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(),
+ translateTo.getContext(), propertyValue);
+ }
+
+ /**
+ * Extract attached resource id optional.
+ *
+ * @param heatFileName the heat file name
+ * @param heatOrchestrationTemplate the heat orchestration template
+ * @param context the context
+ * @param propertyValue the property value
+ * @return the optional
+ */
+ public static Optional<AttachedResourceId> extractAttachedResourceId(String heatFileName,
+ HeatOrchestrationTemplate heatOrchestrationTemplate,
+ TranslationContext context,
+ Object propertyValue) {
+
+ Object entity;
+ Object translatedId;
+
+ if (Objects.isNull(propertyValue)) {
+ return Optional.empty();
+ }
+
+ ReferenceType referenceType = ReferenceType.OTHER;
+ if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
+ Map<String, Object> propMap = (Map) propertyValue;
+ Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
+ entity = entry.getValue();
+ String key = entry.getKey();
+ referenceType = getReferenceTypeFromAttachedResouce(key);
if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
translatedId = null;
@@ -394,1206 +376,1116 @@ public class HeatToToscaUtil {
translatedId = null;
}
- } else {
- translatedId = propertyValue;
- entity = propertyValue;
- }
-
- return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
- }
-
- private static ReferenceType getReferenceTypeFromAttachedResouce(String key) {
- ReferenceType referenceType;
- switch (key) {
- case GET_RESOURCE:
- referenceType = ReferenceType.GET_RESOURCE;
- break;
- case GET_PARAM:
- referenceType = ReferenceType.GET_PARAM;
- break;
- case GET_ATTR:
- referenceType = ReferenceType.GET_ATTR;
- break;
- default:
- referenceType = ReferenceType.OTHER;
- break;
- }
-
- return referenceType;
- }
-
- /**
- * Gets contrail attached heat resource id.
- *
- * @param attachedResource the attached resource
- * @return the contrail attached heat resource id
- */
- public static Optional<String> getContrailAttachedHeatResourceId(
- AttachedResourceId attachedResource) {
- if (attachedResource == null) {
- return Optional.empty();
- }
-
- if (attachedResource.isGetResource()) {
- return Optional.of((String) attachedResource.getEntityId());
- }
-
- if (attachedResource.isGetAttr()) {
- return getResourceId(attachedResource.getEntityId());
- }
- return Optional.empty();
- }
-
- /**
- * Extract property optional.
- *
- * @param propertyValue the property value
- * @return the optional
- */
- private static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
- Object attachedPropertyVal;
- if (Objects.isNull(propertyValue)) {
- return Optional.empty();
- }
-
- ReferenceType referenceType = ReferenceType.OTHER;
- if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
- Map<String, Object> propMap = (Map) propertyValue;
- Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
- attachedPropertyVal = entry.getValue();
- String key = entry.getKey();
- switch (key) {
- case GET_RESOURCE:
- referenceType = ReferenceType.GET_RESOURCE;
- break;
- case GET_PARAM:
- referenceType = ReferenceType.GET_PARAM;
- break;
- case GET_ATTR:
- referenceType = ReferenceType.GET_ATTR;
- break;
- default:
- break;
- }
+ } else {
+ translatedId = propertyValue;
+ entity = propertyValue;
+ }
+
+ return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
+ }
+
+ private static ReferenceType getReferenceTypeFromAttachedResouce(String key) {
+ ReferenceType referenceType;
+ switch (key) {
+ case GET_RESOURCE:
+ referenceType = ReferenceType.GET_RESOURCE;
+ break;
+ case GET_PARAM:
+ referenceType = ReferenceType.GET_PARAM;
+ break;
+ case GET_ATTR:
+ referenceType = ReferenceType.GET_ATTR;
+ break;
+ default:
+ referenceType = ReferenceType.OTHER;
+ break;
+ }
+
+ return referenceType;
+ }
+
+ /**
+ * Gets contrail attached heat resource id.
+ *
+ * @param attachedResource the attached resource
+ * @return the contrail attached heat resource id
+ */
+ public static Optional<String> getContrailAttachedHeatResourceId(AttachedResourceId attachedResource) {
+ if (attachedResource == null) {
+ return Optional.empty();
+ }
+
+ if (attachedResource.isGetResource()) {
+ return Optional.of((String) attachedResource.getEntityId());
+ }
+
+ if (attachedResource.isGetAttr()) {
+ return getResourceId(attachedResource.getEntityId());
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Extract property optional.
+ *
+ * @param propertyValue the property value
+ * @return the optional
+ */
+ private static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
+ Object attachedPropertyVal;
+ if (Objects.isNull(propertyValue)) {
+ return Optional.empty();
+ }
- } else {
- attachedPropertyVal = propertyValue;
- }
- return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
- }
-
- /**
- * Map boolean.
- *
- * @param nodeTemplate the node template
- * @param propertyKey the property key
- */
- public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
- Object value = nodeTemplate.getProperties().get(propertyKey);
- if (value != null && !(value instanceof Map)) {
- nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
- }
- }
-
- /**
- * Map boolean list.
- *
- * @param nodeTemplate the node template
- * @param propertyListKey the property list key
- */
- public static void mapBooleanList(NodeTemplate nodeTemplate, String propertyListKey) {
- Object listValue = nodeTemplate.getProperties().get(propertyListKey);
- if (listValue instanceof List) {
- List booleanList = (List) listValue;
- for (int i = 0; i < booleanList.size(); i++) {
- Object value = booleanList.get(i);
+ ReferenceType referenceType = ReferenceType.OTHER;
+ if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
+ Map<String, Object> propMap = (Map) propertyValue;
+ Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
+ attachedPropertyVal = entry.getValue();
+ String key = entry.getKey();
+ switch (key) {
+ case GET_RESOURCE:
+ referenceType = ReferenceType.GET_RESOURCE;
+ break;
+ case GET_PARAM:
+ referenceType = ReferenceType.GET_PARAM;
+ break;
+ case GET_ATTR:
+ referenceType = ReferenceType.GET_ATTR;
+ break;
+ default:
+ break;
+ }
+
+ } else {
+ attachedPropertyVal = propertyValue;
+ }
+ return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
+ }
+
+ /**
+ * Map boolean.
+ *
+ * @param nodeTemplate the node template
+ * @param propertyKey the property key
+ */
+ public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
+ Object value = nodeTemplate.getProperties().get(propertyKey);
if (value != null && !(value instanceof Map)) {
- booleanList.set(i, HeatBoolean.eval(value));
+ nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
}
- }
}
- }
-
-
- /**
- * Is yml file type boolean.
- *
- * @param filename the filename
- * @return the boolean
- */
- public static boolean isYmlFileType(String filename) {
- String extension = FilenameUtils.getExtension(filename);
- return "yaml".equalsIgnoreCase(extension)
- || "yml".equalsIgnoreCase(extension);
- }
-
- /**
- * Is nested resource boolean.
- *
- * @param resource the resource
- * @return the boolean
- */
- public static boolean isNestedResource(Resource resource) {
- String resourceType = resource.getType();
-
- if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
- Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
- if (!(((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) instanceof
- String)) {
- //currently only resource group which is poinitng to nested heat file is supported
- //dynamic type is currently not supported
+
+ /**
+ * Map boolean list.
+ *
+ * @param nodeTemplate the node template
+ * @param propertyListKey the property list key
+ */
+ public static void mapBooleanList(NodeTemplate nodeTemplate, String propertyListKey) {
+ Object listValue = nodeTemplate.getProperties().get(propertyListKey);
+ if (listValue instanceof List) {
+ List booleanList = (List) listValue;
+ for (int i = 0; i < booleanList.size(); i++) {
+ Object value = booleanList.get(i);
+ if (value != null && !(value instanceof Map)) {
+ booleanList.set(i, HeatBoolean.eval(value));
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Is yml file type boolean.
+ *
+ * @param filename the filename
+ * @return the boolean
+ */
+ public static boolean isYmlFileType(String filename) {
+ String extension = FilenameUtils.getExtension(filename);
+ return "yaml".equalsIgnoreCase(extension) || "yml".equalsIgnoreCase(extension);
+ }
+
+ /**
+ * Is nested resource boolean.
+ *
+ * @param resource the resource
+ * @return the boolean
+ */
+ public static boolean isNestedResource(Resource resource) {
+ String resourceType = resource.getType();
+
+ if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
+ Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
+ if (!(((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) instanceof String)) {
+ //currently only resource group which is poinitng to nested heat file is supported
+ //dynamic type is currently not supported
+ return false;
+ }
+ String internalResourceType =
+ (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
+ if (isYamlFile(internalResourceType)) {
+ return true;
+ }
+ } else if (isYamlFile(resourceType)) {
+ return true;
+ }
return false;
- }
- String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants
- .RESOURCE_DEF_TYPE_PROPERTY_NAME);
- if (isYamlFile(internalResourceType)) {
- return true;
- }
- } else if (isYamlFile(resourceType)) {
- return true;
- }
- return false;
- }
-
- /**
- * Checks if the current HEAT resource if of type sub interface.
- *
- * @param resource the resource
- * @return true if the resource is of sub interface type and false otherwise
- */
- public static boolean isSubInterfaceResource(Resource resource, TranslationContext context) {
- if (!ToggleableFeature.VLAN_TAGGING.isActive()) {
- //Remove this once feature is stable and moved to production
- return false;
- }
- //Check if resource group is a nested resource
- if (!isNestedResource(resource)) {
- return false;
- }
- Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
- return nestedHeatFileName.filter(fileName ->
- isNestedVlanResource(fileName, context)).isPresent();
- }
-
- private static boolean isNestedVlanResource(String nestedHeatFileName,
- TranslationContext translationContext) {
- HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
- .yamlToObject(translationContext.getFileContent(nestedHeatFileName),
- HeatOrchestrationTemplate.class);
- return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())
- && nestedHeatOrchestrationTemplate.getResources().values().stream()
- .anyMatch(new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource);
- }
-
- public static Optional<String> getSubInterfaceParentPortNodeTemplateId(
- TranslateTo subInterfaceTo) {
- String subInterfaceResourceType = getSubInterfaceResourceType(subInterfaceTo.getResource());
- HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
- .yamlToObject(subInterfaceTo.getContext().getFileContent(subInterfaceResourceType),
- HeatOrchestrationTemplate.class);
- if (Objects.isNull(nestedHeatOrchestrationTemplate.getResources())) {
- return Optional.empty();
- }
- for (Map.Entry<String, Resource> resourceEntry : nestedHeatOrchestrationTemplate
- .getResources().entrySet()) {
- Resource resource = resourceEntry.getValue();
- if (isVmiRefsPropertyExists(resource)) {
- Object toscaPropertyValue =
- TranslatorHeatToToscaPropertyConverter
- .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(),
- resourceEntry.getKey(), HeatConstants.VMI_REFS_PROPERTY_NAME,
- resource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME),
- resource.getType(), subInterfaceResourceType, nestedHeatOrchestrationTemplate,
- null, subInterfaceTo.getContext());
- return getParentNodeTemplateIdFromPropertyValue(toscaPropertyValue, subInterfaceTo);
- }
}
- return Optional.empty();
- }
-
- private static boolean isVmiRefsPropertyExists(Resource resource) {
- return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE
- .getHeatResource().equals(resource.getType())
- && MapUtils.isNotEmpty(resource.getProperties())
- && resource.getProperties().containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME);
- }
-
- public static String getSubInterfaceResourceType(Resource resource) {
- if (!HeatToToscaUtil.isYamlFile(resource.getType())) {
- return ((Map) resource.getProperties()
- .get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
- .get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME)
- .toString();
- }
- return resource.getType();
- }
-
- private static Optional<String> getParentNodeTemplateIdFromPropertyValue(
- Object toscaPropertyValue,
- TranslateTo subInterfaceTo) {
- if (toscaPropertyValue instanceof List
- && ((List) toscaPropertyValue).get(0) instanceof Map) {
- Resource subInterfaceResource = subInterfaceTo.getResource();
- Map<String, String> toscaPropertyValueMap = (Map) ((List) toscaPropertyValue).get(0);
- String parentPortPropertyInput = toscaPropertyValueMap.get(ToscaFunctions.GET_INPUT
- .getDisplayName());
- Map<String, Object> resourceDefPropertiesMap;
- if (!isYamlFile(subInterfaceResource.getType())) {
- resourceDefPropertiesMap = (Map) ((Map) subInterfaceResource
- .getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
- .get(HeatConstants.RESOURCE_DEF_PROPERTIES);
- } else {
- resourceDefPropertiesMap = subInterfaceResource.getProperties();
- }
- Object parentPortObj = resourceDefPropertiesMap.get(parentPortPropertyInput);
- if (parentPortObj instanceof Map) {
- Map<String, String> parentPortPropertyValue = (Map) parentPortObj;
- if (parentPortPropertyValue.keySet().contains(ResourceReferenceFunctions
- .GET_RESOURCE.getFunction())) {
- return ResourceTranslationBase.getResourceTranslatedId(subInterfaceTo.getHeatFileName(),
- subInterfaceTo.getHeatOrchestrationTemplate(),
- parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()),
- subInterfaceTo.getContext());
+
+ /**
+ * Checks if the current HEAT resource if of type sub interface.
+ *
+ * @param resource the resource
+ * @return true if the resource is of sub interface type and false otherwise
+ */
+ public static boolean isSubInterfaceResource(Resource resource, TranslationContext context) {
+ if (!ToggleableFeature.VLAN_TAGGING.isActive()) {
+ //Remove this once feature is stable and moved to production
+ return false;
}
- }
+ //Check if resource group is a nested resource
+ if (!isNestedResource(resource)) {
+ return false;
+ }
+ Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
+ return nestedHeatFileName.filter(fileName -> isNestedVlanResource(fileName, context)).isPresent();
}
- return Optional.empty();
- }
-
- /**
- * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at
- * least one or more compute nodes).
- *
- * @param resource the resource
- * @param context the context
- * @return true if the resource represents a VFC and false otherwise.
- */
- public static boolean isNestedVfcResource(Resource resource, TranslationContext context) {
- Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
- HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
- .yamlToObject(context.getFileContent(nestedHeatFileName.get()),
- HeatOrchestrationTemplate.class);
- if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) {
- for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) {
- if (ConsolidationDataUtil
- .isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) {
- return true;
+
+ private static boolean isNestedVlanResource(String nestedHeatFileName, TranslationContext translationContext) {
+ HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
+ translationContext.getFileContent(nestedHeatFileName), HeatOrchestrationTemplate.class);
+ return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources()) && nestedHeatOrchestrationTemplate
+ .getResources().values()
+ .stream().anyMatch(
+ new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource);
+ }
+
+ public static Optional<String> getSubInterfaceParentPortNodeTemplateId(TranslateTo subInterfaceTo) {
+ String subInterfaceResourceType = getSubInterfaceResourceType(subInterfaceTo.getResource());
+ HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
+ subInterfaceTo.getContext().getFileContent(subInterfaceResourceType), HeatOrchestrationTemplate.class);
+ if (Objects.isNull(nestedHeatOrchestrationTemplate.getResources())) {
+ return Optional.empty();
}
- }
+ for (Map.Entry<String, Resource> resourceEntry : nestedHeatOrchestrationTemplate.getResources().entrySet()) {
+ Resource resource = resourceEntry.getValue();
+ if (isVmiRefsPropertyExists(resource)) {
+ Object toscaPropertyValue = TranslatorHeatToToscaPropertyConverter
+ .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(),
+ resourceEntry.getKey(),
+ HeatConstants.VMI_REFS_PROPERTY_NAME,
+ resource.getProperties()
+ .get(HeatConstants.VMI_REFS_PROPERTY_NAME),
+ resource.getType(), subInterfaceResourceType,
+ nestedHeatOrchestrationTemplate, null,
+ subInterfaceTo.getContext());
+ return getParentNodeTemplateIdFromPropertyValue(toscaPropertyValue, subInterfaceTo);
+ }
+ }
+ return Optional.empty();
}
- return false;
- }
-
- /**
- * Get nested heat file name in case of nested resource.
- *
- * @param resource the resource
- * @return the nested heat file name
- */
- private static Optional<String> getNestedHeatFileName(Resource resource) {
- if (!isNestedResource(resource)) {
- return Optional.empty();
- }
-
- String resourceType = resource.getType();
-
- if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
- Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
- String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants
- .RESOURCE_DEF_TYPE_PROPERTY_NAME);
- return Optional.of(internalResourceType);
- }
- return Optional.of(resourceType);
- }
-
- /**
- * Gets nested file.
- *
- * @param resource the resource
- * @return the nested file
- */
- public static Optional<String> getNestedFile(Resource resource) {
- if (!isNestedResource(resource)) {
- return Optional.empty();
- }
- String resourceType = resource.getType();
- if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
- Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
- String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants
- .RESOURCE_DEF_TYPE_PROPERTY_NAME);
- return Optional.of(internalResourceType);
- } else {
- return Optional.of(resourceType);
- }
- }
-
- public static boolean isYamlFile(String fileName) {
- return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
- }
-
- /**
- * Gets resource.
- *
- * @param heatOrchestrationTemplate the heat orchestration template
- * @param resourceId the resource id
- * @param heatFileName the heat file name
- * @return the resource
- */
- public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate,
- String resourceId, String heatFileName) {
- Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
- if (resource == null) {
- throw new CoreException(
- new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
- }
- return resource;
- }
-
-
- /**
- * Get resource type.
- *
- * @param resourceId the resource id
- * @param heatOrchestrationTemplate heat orchestration template
- * @param heatFileName heat file name
- * @return resource type
- */
- public static String getResourceType(String resourceId,
- HeatOrchestrationTemplate heatOrchestrationTemplate,
- String heatFileName) {
- return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName)
- .getType();
- }
-
- /**
- * Is heat file nested boolean.
- *
- * @param translateTo the translate to
- * @param heatFileName the heat file name
- * @return the boolean
- */
- public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
- return isHeatFileNested(translateTo.getContext(), heatFileName);
- }
-
- public static boolean isHeatFileNested(TranslationContext context, String heatFileName) {
- return context.getNestedHeatsFiles().contains(heatFileName);
- }
-
- /**
- * Extract contrail get resource attached heat resource id optional.
- *
- * @param propertyValue the property value
- * @return the optional
- */
- public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(
- Object propertyValue) {
- if (propertyValue instanceof Map) {
- if (((Map) propertyValue).containsKey(GET_ATTR)) {
- return getResourceId(((Map) propertyValue).get(GET_ATTR));
- } else if (((Map) propertyValue).containsKey(GET_RESOURCE)) {
- return getHeatResourceIdFromResource((Map) propertyValue);
- } else {
- Collection valCollection = ((Map) propertyValue).values();
- return evaluateHeatResourceId(valCollection);
- }
- } else if (propertyValue instanceof List) {
- return evaluateHeatResourceId((List) propertyValue);
- }
- return Optional.empty();
- }
-
- private static Optional<String> getResourceId(Object data) {
- if (data instanceof List && CollectionUtils.size(data) > 1
- && FQ_NAME.equals(((List) data).get(1))
- && ((List) data).get(0) instanceof String) {
- return Optional.of((String) ((List) data).get(0));
- } else {
- LOGGER.warn("invalid format of 'get_attr' function - " + data.toString());
- return Optional.empty();
- }
- }
-
- private static Optional<String> getHeatResourceIdFromResource(Map propertyValue) {
- Object value = propertyValue.get(GET_RESOURCE);
- if (value instanceof String) {
- return Optional.of((String) value);
- } else {
- LOGGER.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
- return Optional.empty();
- }
- }
-
- private static Optional<String> evaluateHeatResourceId(Collection propertyValue) {
- for (Object prop : propertyValue) {
- Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
- if (ret.isPresent()) {
- return ret;
- }
+
+ private static boolean isVmiRefsPropertyExists(Resource resource) {
+ return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()
+ .equals(resource.getType())
+ && MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey(
+ HeatConstants.VMI_REFS_PROPERTY_NAME);
}
- return Optional.empty();
- }
-
- /**
- * Gets tosca service model.
- *
- * @param context translation context
- * @return the tosca service model
- */
- public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
- Map<String, String> metadata = new HashMap<>();
- metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
- return getToscaServiceModel(context, metadata);
- }
-
- /**
- * Gets tosca service model.
- *
- * @param context translation context
- * @param entryDefinitionMetadata template name of the entry definition servie template
- * @return the tosca service model
- */
- private static ToscaServiceModel getToscaServiceModel(
- TranslationContext context,
- Map<String, String> entryDefinitionMetadata) {
- Map<String, ServiceTemplate> serviceTemplates =
- new HashMap<>(context.getGlobalServiceTemplates());
- Collection<ServiceTemplate> tmpServiceTemplates =
- context.getTranslatedServiceTemplates().values();
- for (ServiceTemplate serviceTemplate : tmpServiceTemplates) {
- ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
- }
- return new ToscaServiceModel(null, serviceTemplates,
- ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
- }
-
- /**
- * Gets service template from context.
- *
- * @param serviceTemplateFileName the service template file name
- * @param context the context
- * @return the service template from context
- */
- public static Optional<ServiceTemplate> getServiceTemplateFromContext(
- String serviceTemplateFileName, TranslationContext context) {
- for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
- if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
- return Optional.of(serviceTemplate);
- }
+
+ public static String getSubInterfaceResourceType(Resource resource) {
+ if (!HeatToToscaUtil.isYamlFile(resource.getType())) {
+ return ((Map) resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
+ .get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME).toString();
+ }
+ return resource.getType();
+ }
+
+ private static Optional<String> getParentNodeTemplateIdFromPropertyValue(Object toscaPropertyValue,
+ TranslateTo subInterfaceTo) {
+ if (toscaPropertyValue instanceof List && ((List) toscaPropertyValue).get(0) instanceof Map) {
+ Resource subInterfaceResource = subInterfaceTo.getResource();
+ Map<String, String> toscaPropertyValueMap = (Map) ((List) toscaPropertyValue).get(0);
+ String parentPortPropertyInput = toscaPropertyValueMap.get(ToscaFunctions.GET_INPUT.getDisplayName());
+ Map<String, Object> resourceDefPropertiesMap;
+ if (!isYamlFile(subInterfaceResource.getType())) {
+ resourceDefPropertiesMap =
+ (Map) ((Map) subInterfaceResource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
+ .get(HeatConstants.RESOURCE_DEF_PROPERTIES);
+ } else {
+ resourceDefPropertiesMap = subInterfaceResource.getProperties();
+ }
+ Object parentPortObj = resourceDefPropertiesMap.get(parentPortPropertyInput);
+ if (parentPortObj instanceof Map) {
+ Map<String, String> parentPortPropertyValue = (Map) parentPortObj;
+ if (parentPortPropertyValue.keySet().contains(ResourceReferenceFunctions.GET_RESOURCE.getFunction())) {
+ return ResourceTranslationBase.getResourceTranslatedId(subInterfaceTo.getHeatFileName(),
+ subInterfaceTo.getHeatOrchestrationTemplate(),
+ parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()),
+ subInterfaceTo.getContext());
+ }
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at
+ * least one or more compute nodes).
+ *
+ * @param resource the resource
+ * @param context the context
+ * @return true if the resource represents a VFC and false otherwise.
+ */
+ public static boolean isNestedVfcResource(Resource resource, TranslationContext context) {
+ Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
+ HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
+ context.getFileContent(nestedHeatFileName.get()), HeatOrchestrationTemplate.class);
+ if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) {
+ for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) {
+ if (ConsolidationDataUtil.isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
- return Optional.empty();
- }
-
- /**
- * Adding link requerment from port node template to network node template.
- *
- * @param portNodeTemplate port node template
- * @param networkTranslatedId network node template id
- */
- public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
- String networkTranslatedId) {
- RequirementAssignment requirement = new RequirementAssignment();
- requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE);
- requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO);
- requirement.setNode(networkTranslatedId);
- DataModelUtil.addRequirementAssignment(portNodeTemplate,
- ToscaConstants.LINK_REQUIREMENT_ID, requirement);
- return requirement;
- }
-
- /**
- * Adding binding requerment from sub interface node template to interface (port) node template.
- *
- * @param subInterfaceNodeTemplate sub interface template
- * @param interfaceTranslatedId interface node template id
- */
- public static void addBindingReqFromSubInterfaceToInterface(
- NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) {
- RequirementAssignment requirement = new RequirementAssignment();
- requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
- requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
- requirement.setNode(interfaceTranslatedId);
- DataModelUtil
- .addRequirementAssignment(subInterfaceNodeTemplate,
- ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
- }
-
- /**
- * Get property Parameter Name Value.
- *
- * @param property property
- * @return Parameter name in case the property include "get_param" function
- */
- public static Optional<String> getPropertyParameterNameValue(Object property) {
- if (Objects.isNull(property)) {
- return Optional.empty();
- }
- Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
- if (extractedProperty.isPresent()) {
- return getParameterName(extractedProperty.get());
- }
- return Optional.empty();
- }
-
- private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
- if (!extractedProperty.isGetParam()) {
- return Optional.empty();
- }
- Object getParamFuncValue = extractedProperty.getPropertyValue();
- if (getParamFuncValue instanceof String) {
- return Optional.of((String) getParamFuncValue);
- } else {
- return Optional.of((String) ((List) getParamFuncValue).get(0));
- }
- }
-
- public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
- String heatPropertyName) {
- return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
- }
-
- /**
- * Gets tosca property name.
- *
- * @param translateTo the translate to
- * @param heatPropertyName the heat property name
- * @return the tosca property name
- */
- public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
- return translateTo.getContext()
- .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
- }
-
- /**
- * Gets tosca attribute name.
- *
- * @param context the context
- * @param heatResourceType the heat resource type
- * @param heatAttrName the heat attr name
- * @return the tosca attribute name
- */
- public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
- String heatAttrName) {
- return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
- }
-
- /**
- * Gets tosca attribute name.
- *
- * @param translateTo the translate to
- * @param heatAttrName the heat attr name
- * @return the tosca attribute name
- */
- public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
- return translateTo.getContext()
- .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
- }
-
- /**
- * Create init substitution service template service template.
- *
- * @param templateName the template name
- * @return the service template
- */
- public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) {
- ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate();
- Map<String, String> templateMetadata = new HashMap<>();
- templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
- nestedSubstitutionServiceTemplate.setMetadata(templateMetadata);
- nestedSubstitutionServiceTemplate
- .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
- nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate());
- List<Map<String, Import>> globalTypesImportList =
- GlobalTypesGenerator.getGlobalTypesImportList();
- globalTypesImportList.addAll(
- HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
- nestedSubstitutionServiceTemplate.setImports(globalTypesImportList);
- return nestedSubstitutionServiceTemplate;
- }
-
- /**
- * Create init global substitution service template service template.
- *
- * @return the service template
- */
- private static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() {
- ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate();
- Map<String, String> templateMetadata = new HashMap<>();
- templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME,
- Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
- globalSubstitutionServiceTemplate.setMetadata(templateMetadata);
- globalSubstitutionServiceTemplate
- .setImports(GlobalTypesGenerator.getGlobalTypesImportList());
- globalSubstitutionServiceTemplate
- .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
- return globalSubstitutionServiceTemplate;
- }
-
- /**
- * Create substitution node type node type.
- *
- * @param substitutionServiceTemplate the substitution service template
- * @return the node type
- */
- public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
- NodeType substitutionNodeType = new NodeType();
- substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
- substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
- substitutionNodeType
- .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
- substitutionNodeType
- .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
- return substitutionNodeType;
- }
-
- private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
- ServiceTemplate substitutionServiceTemplate) {
- Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
- Map<String, ParameterDefinition> properties =
- substitutionServiceTemplate.getTopology_template().getInputs();
- if (properties == null) {
- return null;
- }
-
- PropertyDefinition propertyDefinition;
- String toscaPropertyName;
- for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
- toscaPropertyName = entry.getKey();
- propertyDefinition = new PropertyDefinition();
- ParameterDefinition parameterDefinition =
- substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
- propertyDefinition.setType(parameterDefinition.getType());
- propertyDefinition.setDescription(parameterDefinition.getDescription());
- propertyDefinition.setRequired(parameterDefinition.getRequired());
- propertyDefinition.set_default(parameterDefinition.get_default());
- propertyDefinition.setConstraints(parameterDefinition.getConstraints());
- propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
- propertyDefinition.setStatus(parameterDefinition.getStatus());
- substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
- }
- return substitutionNodeTypeProperties;
- }
-
- private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
- ServiceTemplate substitutionServiceTemplate) {
- Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
- Map<String, ParameterDefinition> attributes =
- substitutionServiceTemplate.getTopology_template().getOutputs();
- if (attributes == null) {
- return null;
- }
- AttributeDefinition attributeDefinition;
- String toscaAttributeName;
-
- for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
- attributeDefinition = new AttributeDefinition();
- toscaAttributeName = entry.getKey();
- ParameterDefinition parameterDefinition =
- substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
- if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
- attributeDefinition.setType(parameterDefinition.getType());
- } else {
- attributeDefinition.setType(PropertyType.STRING.getDisplayName());
- }
- attributeDefinition.setDescription(parameterDefinition.getDescription());
- attributeDefinition.set_default(parameterDefinition.get_default());
- attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
- attributeDefinition.setStatus(parameterDefinition.getStatus());
- substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
- }
- return substitutionNodeTypeAttributes;
- }
-
- /**
- * .
- * Create and add substitution mapping to the nested substitution service template, and update
- * the subtitution node type accordingly with the exposed requerments and capabilities
- *
- * @param context the translation context
- * @param substitutionNodeTypeKey the substitution node type key
- * @param nestedSubstitutionServiceTemplate the nested substitution service template
- * @param substitutionNodeType the substitution node type
- */
- public static void handleSubstitutionMapping(
- TranslationContext context,
- String substitutionNodeTypeKey,
- ServiceTemplate nestedSubstitutionServiceTemplate,
- NodeType substitutionNodeType) {
- Map<String, Map<String, List<String>>> substitutionMapping =
- getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType,
- nestedSubstitutionServiceTemplate, context);
- //add substitution mapping after capability and requirement expose calculation
- nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(
- DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeKey,
- substitutionNodeType, substitutionMapping));
- }
-
- /**
- * Gets node type with flat hierarchy.
- *
- * @param nodeTypeId the node type id
- * @param serviceTemplate the service template
- * @param context the context
- * @return the node type with flat hierarchy
- */
- public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId,
- ServiceTemplate serviceTemplate,
- TranslationContext context) {
- ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- ToscaServiceModel toscaServiceModel = HeatToToscaUtil
- .getToscaServiceModel(context, serviceTemplate.getMetadata());
- return (NodeType) toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel);
- }
-
- /**
- * Create substitution node template node template.
- *
- * @param translateTo the translate to
- * @param templateName the template name
- * @param substitutionNodeTypeKey the substitution node type key
- * @return the node template
- */
- public NodeTemplate createSubstitutionNodeTemplate(TranslateTo translateTo, String templateName,
- String substitutionNodeTypeKey) {
- NodeTemplate substitutionNodeTemplate = new NodeTemplate();
- List<String> directiveList = new ArrayList<>();
- directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
- substitutionNodeTemplate.setDirectives(directiveList);
- substitutionNodeTemplate.setType(substitutionNodeTypeKey);
- substitutionNodeTemplate.setProperties(
- managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
- templateName));
- return substitutionNodeTemplate;
- }
-
- /**
- * Create abstract substitution node template.
- *
- * @param translateTo the translate to
- * @param templateName the template name
- * @param substitutionNodeTypeKey the substitution node type key
- * @return the abstract substitute node template
- */
- public static NodeTemplate createAbstractSubstitutionNodeTemplate(
- TranslateTo translateTo,
- String templateName,
- String substitutionNodeTypeKey) {
- NodeTemplate substitutionNodeTemplate = new NodeTemplate();
- List<String> directiveList = new ArrayList<>();
- directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
- substitutionNodeTemplate.setDirectives(directiveList);
- substitutionNodeTemplate.setType(substitutionNodeTypeKey);
- substitutionNodeTemplate.setProperties(
- managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
- templateName));
- return substitutionNodeTemplate;
- }
-
-
- /**
- * Checks if the source and target resource is a valid candidate for adding tosca dependency
- * relationship.
- *
- * @param sourceResource the source resource
- * @param targetResource the target resource
- * @param dependencyEntity the dependency entity
- * @return true if the candidate resources are a valid combination for the dependency relationship
- * and false otherwise
- */
- public static boolean isValidDependsOnCandidate(Resource sourceResource,
- Resource targetResource,
- ConsolidationEntityType dependencyEntity,
- TranslationContext context) {
- dependencyEntity.setEntityType(sourceResource, targetResource, context);
- ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
- ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
-
- return ConsolidationTypesConnectivity
- .isDependsOnRelationshipValid(sourceEntityType, targetEntityType);
- }
-
- private static Map<String, Object> managerSubstitutionNodeTemplateProperties(
- TranslateTo translateTo,
- Template template,
- String templateName) {
- Map<String, Object> substitutionProperties = new HashMap<>();
- Map<String, Object> heatProperties = translateTo.getResource().getProperties();
- if (Objects.nonNull(heatProperties)) {
- for (Map.Entry<String, Object> entry : heatProperties.entrySet()) {
- Object property = TranslatorHeatToToscaPropertyConverter
- .getToscaPropertyValue(translateTo.getServiceTemplate(),
- translateTo.getTranslatedId(), entry.getKey(),
- entry.getValue(), null, translateTo.getHeatFileName(),
- translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext());
- substitutionProperties.put(entry.getKey(), property);
- }
+
+ /**
+ * Get nested heat file name in case of nested resource.
+ *
+ * @param resource the resource
+ * @return the nested heat file name
+ */
+ private static Optional<String> getNestedHeatFileName(Resource resource) {
+ if (!isNestedResource(resource)) {
+ return Optional.empty();
+ }
+
+ String resourceType = resource.getType();
+
+ if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
+ Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
+ String internalResourceType =
+ (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
+ return Optional.of(internalResourceType);
+ }
+ return Optional.of(resourceType);
+ }
+
+ /**
+ * Gets nested file.
+ *
+ * @param resource the resource
+ * @return the nested file
+ */
+ public static Optional<String> getNestedFile(Resource resource) {
+ if (!isNestedResource(resource)) {
+ return Optional.empty();
+ }
+ String resourceType = resource.getType();
+ if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
+ Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
+ String internalResourceType =
+ (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
+ return Optional.of(internalResourceType);
+ } else {
+ return Optional.of(resourceType);
+ }
+ }
+
+ public static boolean isYamlFile(String fileName) {
+ return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
}
- return addAbstractSubstitutionProperty(templateName, substitutionProperties);
- }
-
- private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
- Map<String, Object>
- substitutionProperties) {
- Map<String, Object> innerProps = new HashMap<>();
- innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME,
- ToscaUtil.getServiceTemplateFileName(templateName));
- substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
- return substitutionProperties;
- }
-
- private static Map<String, Map<String, List<String>>>
- getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
- ServiceTemplate substitutionServiceTemplate,
- TranslationContext context) {
- Map<String, NodeTemplate> nodeTemplates =
- substitutionServiceTemplate.getTopology_template().getNode_templates();
- String nodeTemplateId;
- NodeTemplate nodeTemplate;
- String nodeType;
- Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
- if (nodeTemplates == null) {
- return substitutionMapping;
- }
-
- Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
- Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
- substitutionMapping.put("capability", capabilitySubstitutionMapping);
- substitutionMapping.put("requirement", requirementSubstitutionMapping);
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
- List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
- new HashMap<>();
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
- Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
- ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
-
- for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
- nodeTemplateId = entry.getKey();
- nodeTemplate = entry.getValue();
- nodeType = nodeTemplate.getType();
-
- // get requirements
- nodeTypeRequirementsDefinition =
- getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate,
- requirementSubstitutionMapping, context);
- nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
- fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
- //set substitution node type requirements
- exposedRequirementsDefinition =
- toscaAnalyzerService.calculateExposedRequirements(nodeTypeRequirementsDefinition,
- nodeTemplateRequirementsAssignment);
- DataModelUtil
- .addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
- nodeTemplateId);
-
- //get capabilities
- addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
- capabilitySubstitutionMapping, nodeType,
- nodeTemplateId, substitutionServiceTemplate, context);
- }
-
- exposedCapabilitiesDefinition =
- toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
- fullFilledRequirementsDefinition);
- DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
- return substitutionMapping;
- }
-
- private static void addNodeTypeCapabilitiesToSubMapping(
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
- Map<String, List<String>> capabilitySubstitutionMapping, String type, String templateName,
- ServiceTemplate serviceTemplate, TranslationContext context) {
- NodeType flatNodeType =
- getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
-
- if (flatNodeType.getCapabilities() != null) {
- flatNodeType.getCapabilities()
- .entrySet()
- .stream()
- .forEach(capabilityNodeEntry ->
- addCapabilityToSubMapping(
- templateName, capabilityNodeEntry, nodeTypeCapabilitiesDefinition,
- capabilitySubstitutionMapping));
- }
- }
-
- public static boolean shouldAnnotationsToBeAdded() {
- return ToggleableFeature.ANNOTATIONS.isActive();
- }
-
- private static void addCapabilityToSubMapping(String templateName,
- Map.Entry<String, CapabilityDefinition> capabilityNodeEntry,
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
- Map<String, List<String>> capabilitySubstitutionMapping) {
- String capabilityKey;
- List<String> capabilityMapping;
- capabilityKey = capabilityNodeEntry.getKey() + UNDERSCORE + templateName;
- nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
- capabilityMapping = new ArrayList<>();
- capabilityMapping.add(templateName);
- capabilityMapping.add(capabilityNodeEntry.getKey());
- capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
- }
-
- private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(
- String type,
- String templateName,
- ServiceTemplate serviceTemplate,
- Map<String, List<String>> requirementSubstitutionMapping,
- TranslationContext context) {
- List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
- NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
- List<String> requirementMapping;
-
- if (flatNodeType.getRequirements() == null) {
- return requirementList;
- }
-
- for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
- for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
- .entrySet()) {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil
- .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
- RequirementDefinition.class);
- if (Objects.isNull(requirementNodeEntryValue.getOccurrences())) {
- requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
- }
- Map<String, RequirementDefinition> requirementDef = new HashMap<>();
- requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
- DataModelUtil.addRequirementToList(requirementList, requirementDef);
- requirementMapping = new ArrayList<>();
- requirementMapping.add(templateName);
- requirementMapping.add(requirementNodeEntry.getKey());
- requirementSubstitutionMapping
- .put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping);
- if (Objects.isNull(requirementNodeEntryValue.getNode())) {
- requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
+
+ /**
+ * Gets resource.
+ *
+ * @param heatOrchestrationTemplate the heat orchestration template
+ * @param resourceId the resource id
+ * @param heatFileName the heat file name
+ * @return the resource
+ */
+ public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId,
+ String heatFileName) {
+ Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
+ if (resource == null) {
+ throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
}
- }
+ return resource;
+ }
+
+
+ /**
+ * Get resource type.
+ *
+ * @param resourceId the resource id
+ * @param heatOrchestrationTemplate heat orchestration template
+ * @param heatFileName heat file name
+ * @return resource type
+ */
+ public static String getResourceType(String resourceId, HeatOrchestrationTemplate heatOrchestrationTemplate,
+ String heatFileName) {
+ return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName).getType();
+ }
+
+ /**
+ * Is heat file nested boolean.
+ *
+ * @param translateTo the translate to
+ * @param heatFileName the heat file name
+ * @return the boolean
+ */
+ public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
+ return isHeatFileNested(translateTo.getContext(), heatFileName);
+ }
+
+ public static boolean isHeatFileNested(TranslationContext context, String heatFileName) {
+ return context.getNestedHeatsFiles().contains(heatFileName);
+ }
+
+ /**
+ * Extract contrail get resource attached heat resource id optional.
+ *
+ * @param propertyValue the property value
+ * @return the optional
+ */
+ public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(Object propertyValue) {
+ if (propertyValue instanceof Map) {
+ if (((Map) propertyValue).containsKey(GET_ATTR)) {
+ return getResourceId(((Map) propertyValue).get(GET_ATTR));
+ } else if (((Map) propertyValue).containsKey(GET_RESOURCE)) {
+ return getHeatResourceIdFromResource((Map) propertyValue);
+ } else {
+ Collection valCollection = ((Map) propertyValue).values();
+ return evaluateHeatResourceId(valCollection);
+ }
+ } else if (propertyValue instanceof List) {
+ return evaluateHeatResourceId((List) propertyValue);
+ }
+ return Optional.empty();
}
- return requirementList;
- }
-
- /**
- * Fetch global substitution service template service template.
- *
- * @param serviceTemplate the service template
- * @param context the context
- * @return the service template
- */
- public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(
- ServiceTemplate serviceTemplate,
- TranslationContext context) {
- ServiceTemplate globalSubstitutionServiceTemplate =
- context.getTranslatedServiceTemplates()
- .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
- if (globalSubstitutionServiceTemplate == null) {
- globalSubstitutionServiceTemplate =
- HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate();
- context.getTranslatedServiceTemplates()
- .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME,
- globalSubstitutionServiceTemplate);
- }
- boolean isImportAddedToServiceTemplate =
- DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants
- .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
- if (!isImportAddedToServiceTemplate) {
- serviceTemplate.getImports()
- .addAll(
- HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
- }
- return globalSubstitutionServiceTemplate;
- }
-
- public static List<Map<String, Import>> createImportList(String templateName) {
- List<Map<String, Import>> imports = new ArrayList<>();
- Map<String, Import> importsMap = new HashMap<>();
- importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName));
- imports.add(importsMap);
- return imports;
- }
-
- /**
- * Create service template import import.
- *
- * @param serviceTemplate the service template
- * @return the import
- */
- public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
- Import serviceTemplateImport = new Import();
- serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
- return serviceTemplateImport;
- }
-
- /**
- * Create service template import import.
- *
- * @param metadataTemplateName the service template name
- * @return the import
- */
- private static Import createServiceTemplateImport(String metadataTemplateName) {
- Import serviceTemplateImport = new Import();
- serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
- return serviceTemplateImport;
- }
-
- public static ToscaServiceModel createToscaServiceModel(ServiceTemplate
- entryDefinitionServiceTemplate,
- TranslationContext translationContext) {
- return new ToscaServiceModel(getCsarArtifactFiles(translationContext),
- getServiceTemplates(translationContext),
- ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
- }
-
- private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
- FileContentHandler artifactFiles = new FileContentHandler();
- artifactFiles.setFiles(translationContext.getFiles());
- artifactFiles.setFiles(translationContext.getExternalArtifacts());
-
- HeatTreeManager heatTreeManager =
- HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles());
- heatTreeManager.createTree();
- ValidationStructureList validationStructureList =
- new ValidationStructureList(heatTreeManager.getTree());
- byte[] validationStructureFile =
- FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON);
- artifactFiles.addFile("HEAT.meta", validationStructureFile);
- return artifactFiles;
- }
-
-
- private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext
- translationContext) {
- List<ServiceTemplate> serviceTemplates = new ArrayList<>();
- serviceTemplates.addAll(GlobalTypesGenerator
- .getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP).values());
- serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values());
- Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>();
-
- for (ServiceTemplate template : serviceTemplates) {
- serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
- }
- return serviceTemplatesMap;
- }
-
- public static String getNestedResourceTypePrefix(TranslateTo translateTo) {
- if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext())
- && isSubInterfaceBoundToPort(translateTo)) {
- return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX;
- }
- return ToscaNodeType.NESTED_HEAT_RESOURCE_TYPE_PREFIX;
- }
-
- private static boolean isSubInterfaceBoundToPort(TranslateTo translateTo) {
- return HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(translateTo).isPresent();
- }
-
- //Method evaluate the network role from sub interface node template id, designed considering
- // only single sub interface present in nested file else it will return null
- public static Optional<String> getNetworkRoleFromSubInterfaceId(Resource resource,
- TranslationContext translationContext) {
- Optional<String> networkRole = Optional.empty();
- Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
-
- if (!nestedHeatFileName.isPresent()) {
- return networkRole;
- }
-
- HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
- .yamlToObject(translationContext.getFileContent(nestedHeatFileName.get()),
- HeatOrchestrationTemplate.class);
-
- if (MapUtils.isNotEmpty(nestedHeatOrchestrationTemplate.getResources())) {
- ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper =
- new ContrailV2VirtualMachineInterfaceHelper();
- Optional<Map.Entry<String, Resource>> vlanSubInterfaceResource =
- nestedHeatOrchestrationTemplate
- .getResources().entrySet().stream()
- .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper
- .isVlanSubInterfaceResource(resourceEntry.getValue()))
- .findFirst();
- if (vlanSubInterfaceResource.isPresent()) {
- Map.Entry<String, Resource> vlanSubInterfaceResourceEntry = vlanSubInterfaceResource.get();
- networkRole = extractNetworkRoleFromSubInterfaceId(vlanSubInterfaceResourceEntry.getKey(),
- vlanSubInterfaceResourceEntry.getValue().getType());
- }
+
+ private static Optional<String> getResourceId(Object data) {
+ if (data instanceof List && CollectionUtils.size(data) > 1 && FQ_NAME.equals(((List) data).get(1))
+ && ((List) data).get(0) instanceof String) {
+ return Optional.of((String) ((List) data).get(0));
+ } else {
+ LOGGER.warn("invalid format of 'get_attr' function - " + data.toString());
+ return Optional.empty();
+ }
}
- return networkRole;
- }
- public static Optional<String> evaluateNetworkRoleFromResourceId(String resourceId,
- String resourceType) {
- Optional<PortType> portType = getPortType(resourceType);
- if (portType.isPresent()) {
- String portResourceIdRegex =
- PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + WORDS_REGEX + UNDERSCORE
- + portType.get().getPortTypeName() + PORT_RESOURCE_ID_REGEX_SUFFIX;
- String portIntResourceIdRegex =
- PORT_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
- + PORT_RESOURCE_ID_REGEX_SUFFIX;
+ private static Optional<String> getHeatResourceIdFromResource(Map propertyValue) {
+ Object value = propertyValue.get(GET_RESOURCE);
+ if (value instanceof String) {
+ return Optional.of((String) value);
+ } else {
+ LOGGER.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
+ return Optional.empty();
+ }
+ }
- String portNetworkRole = getNetworkRole(resourceId, portResourceIdRegex);
- String portIntNetworkRole = getNetworkRole(resourceId, portIntResourceIdRegex);
+ private static Optional<String> evaluateHeatResourceId(Collection propertyValue) {
+ for (Object prop : propertyValue) {
+ Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
+ if (ret.isPresent()) {
+ return ret;
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Gets tosca service model.
+ *
+ * @param context translation context
+ * @return the tosca service model
+ */
+ public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
+ Map<String, String> metadata = new HashMap<>();
+ metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
+ return getToscaServiceModel(context, metadata);
+ }
+
+ /**
+ * Gets tosca service model.
+ *
+ * @param context translation context
+ * @param entryDefinitionMetadata template name of the entry definition servie template
+ * @return the tosca service model
+ */
+ private static ToscaServiceModel getToscaServiceModel(TranslationContext context,
+ Map<String, String> entryDefinitionMetadata) {
+ Map<String, ServiceTemplate> serviceTemplates = new HashMap<>(context.getGlobalServiceTemplates());
+ Collection<ServiceTemplate> tmpServiceTemplates = context.getTranslatedServiceTemplates().values();
+ for (ServiceTemplate serviceTemplate : tmpServiceTemplates) {
+ ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
+ }
+ return new ToscaServiceModel(null, serviceTemplates,
+ ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
+ }
+
+ /**
+ * Gets service template from context.
+ *
+ * @param serviceTemplateFileName the service template file name
+ * @param context the context
+ * @return the service template from context
+ */
+ public static Optional<ServiceTemplate> getServiceTemplateFromContext(String serviceTemplateFileName,
+ TranslationContext context) {
+ for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
+ if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
+ return Optional.of(serviceTemplate);
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Adding link requerment from port node template to network node template.
+ *
+ * @param portNodeTemplate port node template
+ * @param networkTranslatedId network node template id
+ */
+ public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
+ String networkTranslatedId) {
+ RequirementAssignment requirement = new RequirementAssignment();
+ requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE);
+ requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO);
+ requirement.setNode(networkTranslatedId);
+ DataModelUtil.addRequirementAssignment(portNodeTemplate, ToscaConstants.LINK_REQUIREMENT_ID, requirement);
+ return requirement;
+ }
+
+ /**
+ * Adding binding requerment from sub interface node template to interface (port) node template.
+ *
+ * @param subInterfaceNodeTemplate sub interface template
+ * @param interfaceTranslatedId interface node template id
+ */
+ public static void addBindingReqFromSubInterfaceToInterface(NodeTemplate subInterfaceNodeTemplate,
+ String interfaceTranslatedId) {
+ RequirementAssignment requirement = new RequirementAssignment();
+ requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
+ requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
+ requirement.setNode(interfaceTranslatedId);
+ DataModelUtil
+ .addRequirementAssignment(subInterfaceNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
+ }
+
+ /**
+ * Get property Parameter Name Value.
+ *
+ * @param property property
+ * @return Parameter name in case the property include "get_param" function
+ */
+ public static Optional<String> getPropertyParameterNameValue(Object property) {
+ if (Objects.isNull(property)) {
+ return Optional.empty();
+ }
+ Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
+ if (extractedProperty.isPresent()) {
+ return getParameterName(extractedProperty.get());
+ }
+ return Optional.empty();
+ }
- return Optional.ofNullable(Objects.nonNull(portNetworkRole)
- ? portNetworkRole : portIntNetworkRole);
+ private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
+ if (!extractedProperty.isGetParam()) {
+ return Optional.empty();
+ }
+ Object getParamFuncValue = extractedProperty.getPropertyValue();
+ if (getParamFuncValue instanceof String) {
+ return Optional.of((String) getParamFuncValue);
+ } else {
+ return Optional.of((String) ((List) getParamFuncValue).get(0));
+ }
}
- return Optional.empty();
- }
- private static Optional<PortType> getPortType(String resourceType) {
- if (resourceType.equals(
- HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource())) {
- return Optional.of(PortType.VMI);
- } else if (resourceType.equals(
- HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) {
- return Optional.of(PortType.PORT);
+ public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
+ String heatPropertyName) {
+ return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
+ }
+
+ /**
+ * Gets tosca property name.
+ *
+ * @param translateTo the translate to
+ * @param heatPropertyName the heat property name
+ * @return the tosca property name
+ */
+ public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
+ return translateTo.getContext()
+ .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
+ }
+
+ /**
+ * Gets tosca attribute name.
+ *
+ * @param context the context
+ * @param heatResourceType the heat resource type
+ * @param heatAttrName the heat attr name
+ * @return the tosca attribute name
+ */
+ public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
+ String heatAttrName) {
+ return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
+ }
+
+ /**
+ * Gets tosca attribute name.
+ *
+ * @param translateTo the translate to
+ * @param heatAttrName the heat attr name
+ * @return the tosca attribute name
+ */
+ public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
+ return translateTo.getContext()
+ .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
+ }
+
+ /**
+ * Create init substitution service template service template.
+ *
+ * @param templateName the template name
+ * @return the service template
+ */
+ public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) {
+ ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate();
+ Map<String, String> templateMetadata = new HashMap<>();
+ templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
+ nestedSubstitutionServiceTemplate.setMetadata(templateMetadata);
+ nestedSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
+ nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate());
+ List<Map<String, Import>> globalTypesImportList = GlobalTypesGenerator.getGlobalTypesImportList();
+ globalTypesImportList
+ .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
+ nestedSubstitutionServiceTemplate.setImports(globalTypesImportList);
+ return nestedSubstitutionServiceTemplate;
+ }
+
+ /**
+ * Create init global substitution service template service template.
+ *
+ * @return the service template
+ */
+ private static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() {
+ ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate();
+ Map<String, String> templateMetadata = new HashMap<>();
+ templateMetadata
+ .put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
+ globalSubstitutionServiceTemplate.setMetadata(templateMetadata);
+ globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList());
+ globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
+ return globalSubstitutionServiceTemplate;
+ }
+
+ /**
+ * Create substitution node type node type.
+ *
+ * @param substitutionServiceTemplate the substitution service template
+ * @return the node type
+ */
+ public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
+ NodeType substitutionNodeType = new NodeType();
+ substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
+ substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
+ substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
+ substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
+ return substitutionNodeType;
+ }
+
+ private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) {
+ Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
+ Map<String, ParameterDefinition> properties = substitutionServiceTemplate.getTopology_template().getInputs();
+ if (properties == null) {
+ return null;
+ }
+
+ PropertyDefinition propertyDefinition;
+ String toscaPropertyName;
+ for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
+ toscaPropertyName = entry.getKey();
+ propertyDefinition = new PropertyDefinition();
+ ParameterDefinition parameterDefinition =
+ substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
+ propertyDefinition.setType(parameterDefinition.getType());
+ propertyDefinition.setDescription(parameterDefinition.getDescription());
+ propertyDefinition.setRequired(parameterDefinition.getRequired());
+ propertyDefinition.set_default(parameterDefinition.get_default());
+ propertyDefinition.setConstraints(parameterDefinition.getConstraints());
+ propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
+ propertyDefinition.setStatus(parameterDefinition.getStatus());
+ substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
+ }
+ return substitutionNodeTypeProperties;
}
- return Optional.empty();
- }
- public static Optional<String> extractNetworkRoleFromSubInterfaceId(String resourceId,
- String resourceType) {
- Optional<PortType> portType = getPortType(resourceType);
- if (portType.isPresent()) {
- String subInterfaceResourceIdRegex =
- SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
- + PORT_RESOURCE_ID_REGEX_SUFFIX;
+ private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) {
+ Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
+ Map<String, ParameterDefinition> attributes = substitutionServiceTemplate.getTopology_template().getOutputs();
+ if (attributes == null) {
+ return null;
+ }
+ AttributeDefinition attributeDefinition;
+ String toscaAttributeName;
+
+ for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
+ attributeDefinition = new AttributeDefinition();
+ toscaAttributeName = entry.getKey();
+ ParameterDefinition parameterDefinition =
+ substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
+ if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
+ attributeDefinition.setType(parameterDefinition.getType());
+ } else {
+ attributeDefinition.setType(PropertyType.STRING.getDisplayName());
+ }
+ attributeDefinition.setDescription(parameterDefinition.getDescription());
+ attributeDefinition.set_default(parameterDefinition.get_default());
+ attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
+ attributeDefinition.setStatus(parameterDefinition.getStatus());
+ substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
+ }
+ return substitutionNodeTypeAttributes;
+ }
+
+ /**
+ * .
+ * Create and add substitution mapping to the nested substitution service template, and update
+ * the subtitution node type accordingly with the exposed requerments and capabilities
+ *
+ * @param context the translation context
+ * @param substitutionNodeTypeKey the substitution node type key
+ * @param nestedSubstitutionServiceTemplate the nested substitution service template
+ * @param substitutionNodeType the substitution node type
+ */
+ public static void handleSubstitutionMapping(TranslationContext context, String substitutionNodeTypeKey,
+ ServiceTemplate nestedSubstitutionServiceTemplate,
+ NodeType substitutionNodeType) {
+ Map<String, Map<String, List<String>>> substitutionMapping =
+ getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, nestedSubstitutionServiceTemplate,
+ context);
+ //add substitution mapping after capability and requirement expose calculation
+ nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(DataModelUtil
+ .createSubstitutionTemplateSubMapping(
+ substitutionNodeTypeKey,
+ substitutionNodeType,
+ substitutionMapping));
+ }
+
+ /**
+ * Gets node type with flat hierarchy.
+ *
+ * @param nodeTypeId the node type id
+ * @param serviceTemplate the service template
+ * @param context the context
+ * @return the node type with flat hierarchy
+ */
+ public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate,
+ TranslationContext context) {
+ ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
+ ToscaServiceModel toscaServiceModel =
+ HeatToToscaUtil.getToscaServiceModel(context, serviceTemplate.getMetadata());
+ return (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate,
+ toscaServiceModel).getFlatEntity();
+ }
+
+
+ /**
+ * Create abstract substitution node template.
+ *
+ * @param translateTo the translate to
+ * @param templateName the template name
+ * @param substitutionNodeTypeKey the substitution node type key
+ * @return the abstract substitute node template
+ */
+ public static NodeTemplate createAbstractSubstitutionNodeTemplate(TranslateTo translateTo, String templateName,
+ String substitutionNodeTypeKey) {
+ NodeTemplate substitutionNodeTemplate = new NodeTemplate();
+ List<String> directiveList = new ArrayList<>();
+ directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
+ substitutionNodeTemplate.setDirectives(directiveList);
+ substitutionNodeTemplate.setType(substitutionNodeTypeKey);
+ substitutionNodeTemplate.setProperties(
+ managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, templateName));
+ return substitutionNodeTemplate;
+ }
+
+
+ /**
+ * Checks if the source and target resource is a valid candidate for adding tosca dependency
+ * relationship.
+ *
+ * @param sourceResource the source resource
+ * @param targetResource the target resource
+ * @param dependencyEntity the dependency entity
+ * @return true if the candidate resources are a valid combination for the dependency relationship
+ * and false otherwise
+ */
+ public static boolean isValidDependsOnCandidate(Resource sourceResource, Resource targetResource,
+ ConsolidationEntityType dependencyEntity,
+ TranslationContext context) {
+ dependencyEntity.setEntityType(sourceResource, targetResource, context);
+ ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
+ ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
+
+ return ConsolidationTypesConnectivity.isDependsOnRelationshipValid(sourceEntityType, targetEntityType);
+ }
+
+ private static Map<String, Object> managerSubstitutionNodeTemplateProperties(TranslateTo translateTo,
+ Template template,
+ String templateName) {
+ Map<String, Object> substitutionProperties = new HashMap<>();
+ Map<String, Object> heatProperties = translateTo.getResource().getProperties();
+ if (Objects.nonNull(heatProperties)) {
+ for (Map.Entry<String, Object> entry : heatProperties.entrySet()) {
+ Object property = TranslatorHeatToToscaPropertyConverter
+ .getToscaPropertyValue(translateTo.getServiceTemplate(),
+ translateTo.getTranslatedId(), entry.getKey(), entry.getValue(), null,
+ translateTo.getHeatFileName(),
+ translateTo.getHeatOrchestrationTemplate(), template,
+ translateTo.getContext());
+ substitutionProperties.put(entry.getKey(), property);
+ }
+ }
+ return addAbstractSubstitutionProperty(templateName, substitutionProperties);
+ }
+
+ private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
+ Map<String, Object> substitutionProperties) {
+ Map<String, Object> innerProps = new HashMap<>();
+ innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME,
+ ToscaUtil.getServiceTemplateFileName(templateName));
+ substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
+ return substitutionProperties;
+ }
+
+ private static Map<String, Map<String, List<String>>> getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
+ ServiceTemplate substitutionServiceTemplate,
+ TranslationContext context) {
+ Map<String, NodeTemplate> nodeTemplates =
+ substitutionServiceTemplate.getTopology_template().getNode_templates();
+ String nodeTemplateId;
+ NodeTemplate nodeTemplate;
+ String nodeType;
+ Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
+ if (nodeTemplates == null) {
+ return substitutionMapping;
+ }
- return Optional.ofNullable(getNetworkRole(resourceId, subInterfaceResourceIdRegex));
+ Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
+ Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
+ substitutionMapping.put("capability", capabilitySubstitutionMapping);
+ substitutionMapping.put("requirement", requirementSubstitutionMapping);
+ List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
+ List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
+ Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
+ Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
+ ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
+
+ for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
+ nodeTemplateId = entry.getKey();
+ nodeTemplate = entry.getValue();
+ nodeType = nodeTemplate.getType();
+
+ // get requirements
+ nodeTypeRequirementsDefinition = getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate,
+ requirementSubstitutionMapping, context);
+ nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
+ fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
+ //set substitution node type requirements
+ exposedRequirementsDefinition = toscaAnalyzerService
+ .calculateExposedRequirements(nodeTypeRequirementsDefinition,
+ nodeTemplateRequirementsAssignment);
+ DataModelUtil.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
+ nodeTemplateId);
+
+ //get capabilities
+ addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType,
+ nodeTemplateId, substitutionServiceTemplate, context);
+ }
+
+ exposedCapabilitiesDefinition = toscaAnalyzerService
+ .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
+ fullFilledRequirementsDefinition);
+ DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
+ return substitutionMapping;
}
- return Optional.empty();
- }
- private enum PortType {
- PORT("port"),
- VMI("vmi");
+ private static void addNodeTypeCapabilitiesToSubMapping(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
+ Map<String, List<String>> capabilitySubstitutionMapping,
+ String type, String templateName,
+ ServiceTemplate serviceTemplate,
+ TranslationContext context) {
+ NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
- private String portTypeName;
+ if (flatNodeType.getCapabilities() != null) {
+ flatNodeType.getCapabilities().entrySet().stream().forEach(
+ capabilityNodeEntry -> addCapabilityToSubMapping(templateName, capabilityNodeEntry,
+ nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping));
+ }
+ }
- PortType(String portTypeName) {
- this.portTypeName = portTypeName;
+ public static boolean shouldAnnotationsToBeAdded() {
+ return ToggleableFeature.ANNOTATIONS.isActive();
}
- public String getPortTypeName() {
- return portTypeName;
+ private static void addCapabilityToSubMapping(String templateName,
+ Map.Entry<String, CapabilityDefinition> capabilityNodeEntry,
+ Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
+ Map<String, List<String>> capabilitySubstitutionMapping) {
+ String capabilityKey;
+ List<String> capabilityMapping;
+ capabilityKey = capabilityNodeEntry.getKey() + UNDERSCORE + templateName;
+ nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
+ capabilityMapping = new ArrayList<>();
+ capabilityMapping.add(templateName);
+ capabilityMapping.add(capabilityNodeEntry.getKey());
+ capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
}
- }
- private static String getNetworkRole(String portResourceId, String portIdRegex) {
- Pattern pattern = Pattern.compile(portIdRegex);
- Matcher matcher = pattern.matcher(portResourceId);
- if (matcher.matches()) {
- String networkRole = matcher.group(3);
- //Assuming network role will not contain ONLY digits
- if (!networkRole.matches("\\d+")) {
- return matcher.group(3);
- }
+ private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(String type, String templateName,
+ ServiceTemplate serviceTemplate,
+ Map<String, List<String>> requirementSubstitutionMapping,
+ TranslationContext context) {
+ List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
+ NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
+ List<String> requirementMapping;
+
+ if (flatNodeType.getRequirements() == null) {
+ return requirementList;
+ }
+
+ for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
+ for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap.entrySet()) {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil.yamlToObject(
+ toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
+ RequirementDefinition.class);
+ if (Objects.isNull(requirementNodeEntryValue.getOccurrences())) {
+ requirementNodeEntryValue.setOccurrences(new Object[] {1, 1});
+ }
+ Map<String, RequirementDefinition> requirementDef = new HashMap<>();
+ requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
+ DataModelUtil.addRequirementToList(requirementList, requirementDef);
+ requirementMapping = new ArrayList<>();
+ requirementMapping.add(templateName);
+ requirementMapping.add(requirementNodeEntry.getKey());
+ requirementSubstitutionMapping
+ .put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping);
+ if (Objects.isNull(requirementNodeEntryValue.getNode())) {
+ requirementNodeEntryValue.setOccurrences(new Object[] {1, 1});
+ }
+ }
+ }
+ return requirementList;
+ }
+
+ /**
+ * Fetch global substitution service template service template.
+ *
+ * @param serviceTemplate the service template
+ * @param context the context
+ * @return the service template
+ */
+ public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(ServiceTemplate serviceTemplate,
+ TranslationContext context) {
+ ServiceTemplate globalSubstitutionServiceTemplate =
+ context.getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
+ if (globalSubstitutionServiceTemplate == null) {
+ globalSubstitutionServiceTemplate = HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate();
+ context.getTranslatedServiceTemplates()
+ .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate);
+ }
+ boolean isImportAddedToServiceTemplate = DataModelUtil
+ .isImportAddedToServiceTemplate(serviceTemplate.getImports(),
+ Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
+ if (!isImportAddedToServiceTemplate) {
+ serviceTemplate.getImports()
+ .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
+ }
+ return globalSubstitutionServiceTemplate;
+ }
+
+ public static List<Map<String, Import>> createImportList(String templateName) {
+ List<Map<String, Import>> imports = new ArrayList<>();
+ Map<String, Import> importsMap = new HashMap<>();
+ importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName));
+ imports.add(importsMap);
+ return imports;
+ }
+
+ /**
+ * Create service template import import.
+ *
+ * @param serviceTemplate the service template
+ * @return the import
+ */
+ public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
+ Import serviceTemplateImport = new Import();
+ serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
+ return serviceTemplateImport;
+ }
+
+ /**
+ * Create service template import import.
+ *
+ * @param metadataTemplateName the service template name
+ * @return the import
+ */
+ private static Import createServiceTemplateImport(String metadataTemplateName) {
+ Import serviceTemplateImport = new Import();
+ serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
+ return serviceTemplateImport;
+ }
+
+ public static ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate,
+ TranslationContext translationContext) {
+ return new ToscaServiceModel(getCsarArtifactFiles(translationContext), getServiceTemplates(translationContext),
+ ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
+ }
+
+ private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
+ FileContentHandler artifactFiles = new FileContentHandler();
+ artifactFiles.setFiles(translationContext.getFiles());
+ artifactFiles.setFiles(translationContext.getExternalArtifacts());
+
+ HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles());
+ heatTreeManager.createTree();
+ ValidationStructureList validationStructureList = new ValidationStructureList(heatTreeManager.getTree());
+ byte[] validationStructureFile =
+ FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON);
+ artifactFiles.addFile("HEAT.meta", validationStructureFile);
+ return artifactFiles;
+ }
+
+
+ private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext translationContext) {
+ List<ServiceTemplate> serviceTemplates = new ArrayList<>();
+ serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP).values());
+ serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values());
+ Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>();
+
+ for (ServiceTemplate template : serviceTemplates) {
+ serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
+ }
+ return serviceTemplatesMap;
+ }
+
+ public static String getNestedResourceTypePrefix(TranslateTo translateTo) {
+ if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext()) && isSubInterfaceBoundToPort(
+ translateTo)) {
+ return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX;
+ }
+ return ToscaNodeType.NESTED_HEAT_RESOURCE_TYPE_PREFIX;
+ }
+
+ private static boolean isSubInterfaceBoundToPort(TranslateTo translateTo) {
+ return HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(translateTo).isPresent();
+ }
+
+ //Method evaluate the network role from sub interface node template id, designed considering
+ // only single sub interface present in nested file else it will return null
+ public static Optional<String> getNetworkRoleFromSubInterfaceId(Resource resource,
+ TranslationContext translationContext) {
+ Optional<String> networkRole = Optional.empty();
+ Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
+
+ if (!nestedHeatFileName.isPresent()) {
+ return networkRole;
+ }
+
+ HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
+ translationContext.getFileContent(nestedHeatFileName.get()), HeatOrchestrationTemplate.class);
+
+ if (MapUtils.isNotEmpty(nestedHeatOrchestrationTemplate.getResources())) {
+ ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper =
+ new ContrailV2VirtualMachineInterfaceHelper();
+ Optional<Map.Entry<String, Resource>> vlanSubInterfaceResource =
+ nestedHeatOrchestrationTemplate.getResources().entrySet().stream()
+ .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper
+ .isVlanSubInterfaceResource(
+ resourceEntry.getValue()))
+ .findFirst();
+ if (vlanSubInterfaceResource.isPresent()) {
+ Map.Entry<String, Resource> vlanSubInterfaceResourceEntry = vlanSubInterfaceResource.get();
+ networkRole = extractNetworkRoleFromSubInterfaceId(vlanSubInterfaceResourceEntry.getKey(),
+ vlanSubInterfaceResourceEntry.getValue().getType());
+ }
+ }
+ return networkRole;
+ }
+
+ public static Optional<String> evaluateNetworkRoleFromResourceId(String resourceId, String resourceType) {
+ Optional<PortType> portType = getPortType(resourceType);
+ if (portType.isPresent()) {
+ String portResourceIdRegex =
+ PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + WORDS_REGEX + UNDERSCORE + portType.get()
+ .getPortTypeName()
+ + PORT_RESOURCE_ID_REGEX_SUFFIX;
+ String portIntResourceIdRegex = PORT_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
+ + PORT_RESOURCE_ID_REGEX_SUFFIX;
+
+ String portNetworkRole = getNetworkRole(resourceId, portResourceIdRegex);
+ String portIntNetworkRole = getNetworkRole(resourceId, portIntResourceIdRegex);
+
+ return Optional.ofNullable(Objects.nonNull(portNetworkRole) ? portNetworkRole : portIntNetworkRole);
+ }
+ return Optional.empty();
+ }
+
+ private static Optional<PortType> getPortType(String resourceType) {
+ if (resourceType
+ .equals(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource())) {
+ return Optional.of(PortType.VMI);
+ } else if (resourceType.equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) {
+ return Optional.of(PortType.PORT);
+ }
+ return Optional.empty();
+ }
+
+ public static Optional<String> extractNetworkRoleFromSubInterfaceId(String resourceId, String resourceType) {
+ Optional<PortType> portType = getPortType(resourceType);
+ if (portType.isPresent()) {
+ String subInterfaceResourceIdRegex =
+ SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
+ + PORT_RESOURCE_ID_REGEX_SUFFIX;
+
+ return Optional.ofNullable(getNetworkRole(resourceId, subInterfaceResourceIdRegex));
+ }
+ return Optional.empty();
+ }
+
+ private enum PortType {
+ PORT("port"), VMI("vmi");
+
+ private String portTypeName;
+
+ PortType(String portTypeName) {
+ this.portTypeName = portTypeName;
+ }
+
+ public String getPortTypeName() {
+ return portTypeName;
+ }
+ }
+
+ private static String getNetworkRole(String portResourceId, String portIdRegex) {
+ Pattern pattern = Pattern.compile(portIdRegex);
+ Matcher matcher = pattern.matcher(portResourceId);
+ if (matcher.matches()) {
+ String networkRole = matcher.group(3);
+ //Assuming network role will not contain ONLY digits
+ if (!networkRole.matches("\\d+")) {
+ return matcher.group(3);
+ }
+ }
+ return null;
}
- return null;
- }
}
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java
new file mode 100644
index 0000000000..b898640df9
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * 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.
+ */
+
+package org.openecomp.sdc.tosca.datatypes;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.collections4.CollectionUtils;
+
+public class ToscaFlatData {
+
+ private Object flatEntity;
+ private ToscaElementTypes elementType;
+ private List<String> inheritanceHierarchyType;
+
+ public ToscaElementTypes getElementType() {
+ return elementType;
+ }
+
+ public void setElementType(ToscaElementTypes elementType) {
+ this.elementType = elementType;
+ }
+
+ public Object getFlatEntity() {
+ return flatEntity;
+ }
+
+ public void setFlatEntity(Object flatEntity) {
+ this.flatEntity = flatEntity;
+ }
+
+ public List<String> getInheritanceHierarchyType() {
+ return inheritanceHierarchyType;
+ }
+
+ public void addInheritanceHierarchyType(String inheritedType) {
+ if (CollectionUtils.isEmpty(inheritanceHierarchyType)) {
+ inheritanceHierarchyType = new ArrayList<>();
+ }
+ this.inheritanceHierarchyType.add(inheritedType);
+ }
+}
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java
index a8629aa287..fc411bf009 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java
@@ -45,7 +45,6 @@ import org.onap.sdc.tosca.datatypes.model.EntrySchema;
import org.onap.sdc.tosca.datatypes.model.GroupDefinition;
import org.onap.sdc.tosca.datatypes.model.Import;
import org.onap.sdc.tosca.datatypes.model.InterfaceDefinition;
-import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionTemplate;
import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
import org.onap.sdc.tosca.datatypes.model.InterfaceType;
import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
@@ -101,11 +100,10 @@ public class DataModelUtil {
* @param substitutionMapping the substitution mapping
*/
public static void addSubstitutionMapping(ServiceTemplate serviceTemplate,
- SubstitutionMapping substitutionMapping) {
+ SubstitutionMapping substitutionMapping) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", SERVICE_TEMPLATE)
- .build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", SERVICE_TEMPLATE)
+ .build());
}
if (serviceTemplate.getTopology_template() == null) {
@@ -135,12 +133,11 @@ public class DataModelUtil {
* @param substitutionMappingRequirementList the substitution mapping requirement list
*/
public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate,
- String substitutionMappingRequirementId,
- List<String> substitutionMappingRequirementList) {
+ String substitutionMappingRequirementId,
+ List<String> substitutionMappingRequirementList) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements",
- SERVICE_TEMPLATE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements",
+ SERVICE_TEMPLATE).build());
}
if (serviceTemplate.getTopology_template() == null) {
@@ -149,14 +146,12 @@ public class DataModelUtil {
if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
}
- if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
- == null) {
- serviceTemplate.getTopology_template().getSubstitution_mappings()
- .setRequirements(new HashMap<>());
+ if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() == null) {
+ serviceTemplate.getTopology_template().getSubstitution_mappings().setRequirements(new HashMap<>());
}
serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
- .put(substitutionMappingRequirementId, substitutionMappingRequirementList);
+ .put(substitutionMappingRequirementId, substitutionMappingRequirementList);
}
/**
@@ -167,12 +162,11 @@ public class DataModelUtil {
* @param substitutionMappingCapabilityList the substitution mapping capability list
*/
public static void addSubstitutionMappingCapability(ServiceTemplate serviceTemplate,
- String substitutionMappingCapabilityId,
- List<String> substitutionMappingCapabilityList) {
+ String substitutionMappingCapabilityId,
+ List<String> substitutionMappingCapabilityList) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Capabilities",
- SERVICE_TEMPLATE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Capabilities",
+ SERVICE_TEMPLATE).build());
}
if (serviceTemplate.getTopology_template() == null) {
@@ -181,14 +175,12 @@ public class DataModelUtil {
if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
}
- if (serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities()
- == null) {
- serviceTemplate.getTopology_template().getSubstitution_mappings()
- .setCapabilities(new HashMap<>());
+ if (serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() == null) {
+ serviceTemplate.getTopology_template().getSubstitution_mappings().setCapabilities(new HashMap<>());
}
serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities()
- .putIfAbsent(substitutionMappingCapabilityId, substitutionMappingCapabilityList);
+ .putIfAbsent(substitutionMappingCapabilityId, substitutionMappingCapabilityList);
}
/**
@@ -198,9 +190,8 @@ public class DataModelUtil {
* @return the service template node templates and empty map if not present
*/
public static Map<String, NodeTemplate> getNodeTemplates(ServiceTemplate serviceTemplate) {
- if (Objects.isNull(serviceTemplate)
- || Objects.isNull(serviceTemplate.getTopology_template())
- || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates())) {
+ if (Objects.isNull(serviceTemplate) || Objects.isNull(serviceTemplate.getTopology_template())
+ || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates())) {
return new HashMap<>();
}
@@ -214,9 +205,8 @@ public class DataModelUtil {
* @return the service template groups and empty map if not present
*/
public static Map<String, GroupDefinition> getGroups(ServiceTemplate serviceTemplate) {
- if (Objects.isNull(serviceTemplate)
- || Objects.isNull(serviceTemplate.getTopology_template())
- || MapUtils.isEmpty(serviceTemplate.getTopology_template().getGroups())) {
+ if (Objects.isNull(serviceTemplate) || Objects.isNull(serviceTemplate.getTopology_template())
+ || MapUtils.isEmpty(serviceTemplate.getTopology_template().getGroups())) {
return new HashMap<>();
}
@@ -231,10 +221,10 @@ public class DataModelUtil {
* @param nodeTemplate the node template
*/
public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId,
- NodeTemplate nodeTemplate) {
+ NodeTemplate nodeTemplate) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Node Template", SERVICE_TEMPLATE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Node Template", SERVICE_TEMPLATE)
+ .build());
}
TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
if (Objects.isNull(topologyTemplate)) {
@@ -253,15 +243,14 @@ public class DataModelUtil {
* @param nodeType the node type
* @param capabilities the capability definitions
*/
- public static void addNodeTypeCapabilitiesDef(NodeType nodeType,
- Map<String, CapabilityDefinition> capabilities) {
+ public static void addNodeTypeCapabilitiesDef(NodeType nodeType, Map<String, CapabilityDefinition> capabilities) {
if (MapUtils.isEmpty(capabilities) || capabilities.entrySet().isEmpty()) {
return;
}
if (nodeType == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE)
+ .build());
}
if (MapUtils.isEmpty(nodeType.getCapabilities())) {
@@ -283,11 +272,10 @@ public class DataModelUtil {
* @param policyDefinition the policy definition
*/
public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId,
- PolicyDefinition policyDefinition) {
+ PolicyDefinition policyDefinition) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Policy Definition", SERVICE_TEMPLATE)
- .build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Policy Definition", SERVICE_TEMPLATE)
+ .build());
}
TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
if (Objects.isNull(topologyTemplate)) {
@@ -307,11 +295,9 @@ public class DataModelUtil {
* @param nodeTypeId the node type id
* @param nodeType the node type
*/
- public static void addNodeType(ServiceTemplate serviceTemplate, String nodeTypeId,
- NodeType nodeType) {
+ public static void addNodeType(ServiceTemplate serviceTemplate, String nodeTypeId, NodeType nodeType) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder(NODE_TYPE, SERVICE_TEMPLATE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder(NODE_TYPE, SERVICE_TEMPLATE).build());
}
if (serviceTemplate.getNode_types() == null) {
serviceTemplate.setNode_types(new HashMap<>());
@@ -326,13 +312,11 @@ public class DataModelUtil {
* @param relationshipTemplateId the relationship template id
* @param relationshipTemplate the relationship template
*/
- public static void addRelationshipTemplate(ServiceTemplate serviceTemplate,
- String relationshipTemplateId,
- RelationshipTemplate relationshipTemplate) {
+ public static void addRelationshipTemplate(ServiceTemplate serviceTemplate, String relationshipTemplateId,
+ RelationshipTemplate relationshipTemplate) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Relationship Template", SERVICE_TEMPLATE)
- .build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Relationship Template",
+ SERVICE_TEMPLATE).build());
}
if (serviceTemplate.getTopology_template() == null) {
serviceTemplate.setTopology_template(new TopologyTemplate());
@@ -341,7 +325,7 @@ public class DataModelUtil {
serviceTemplate.getTopology_template().setRelationship_templates(new HashMap<>());
}
serviceTemplate.getTopology_template().getRelationship_templates()
- .put(relationshipTemplateId, relationshipTemplate);
+ .put(relationshipTemplateId, relationshipTemplate);
}
/**
@@ -352,11 +336,10 @@ public class DataModelUtil {
* @param requirementAssignment the requirement assignment
*/
public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId,
- RequirementAssignment requirementAssignment) {
+ RequirementAssignment requirementAssignment) {
if (nodeTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", "Node Template")
- .build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment",
+ "Node Template").build());
}
if (requirementAssignment.getNode() == null) {
throw new CoreException(new InvalidRequirementAssignmentErrorBuilder(requirementId).build());
@@ -391,11 +374,9 @@ public class DataModelUtil {
* @param nodeTemplateId the node template id
* @return the node template
*/
- public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate,
- String nodeTemplateId) {
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getNode_templates() == null) {
+ public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getNode_templates() == null) {
return null;
}
return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId);
@@ -422,18 +403,12 @@ public class DataModelUtil {
* @param requirementDefinitionId the requirement definition id
* @return the requirement definition
*/
- public static Optional<RequirementDefinition> getRequirementDefinition(
- NodeType nodeType,
- String requirementDefinitionId) {
+ public static Optional<RequirementDefinition> getRequirementDefinition(NodeType nodeType,
+ String requirementDefinitionId) {
if (nodeType == null || nodeType.getRequirements() == null || requirementDefinitionId == null) {
return Optional.empty();
}
- for (Map<String, RequirementDefinition> reqMap : nodeType.getRequirements()) {
- if (reqMap.containsKey(requirementDefinitionId)) {
- return Optional.of(reqMap.get(requirementDefinitionId));
- }
- }
- return Optional.empty();
+ return getRequirementDefinition(nodeType.getRequirements(), requirementDefinitionId);
}
/**
@@ -442,16 +417,19 @@ public class DataModelUtil {
* @param requirementsDefinitionList requirement definition list
* @param requirementKey requirement key
*/
- public static Optional<RequirementDefinition> getRequirementDefinition(
- List<Map<String, RequirementDefinition>> requirementsDefinitionList,
- String requirementKey) {
+ public static Optional<RequirementDefinition> getRequirementDefinition(List<Map<String, RequirementDefinition>> requirementsDefinitionList,
+ String requirementKey) {
if (CollectionUtils.isEmpty(requirementsDefinitionList)) {
return Optional.empty();
}
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
for (Map<String, RequirementDefinition> requirementMap : requirementsDefinitionList) {
if (requirementMap.containsKey(requirementKey)) {
- return Optional.of(requirementMap.get(requirementKey));
+ RequirementDefinition requirementDefinition = toscaExtensionYamlUtil.yamlToObject(
+ toscaExtensionYamlUtil.objectToYaml(requirementMap.get(requirementKey)),
+ RequirementDefinition.class);
+ return Optional.of(requirementDefinition);
}
}
return Optional.empty();
@@ -464,9 +442,8 @@ public class DataModelUtil {
* @param capabilityDefinitionId the capability definition id
* @return the capability definition
*/
- public static Optional<CapabilityDefinition> getCapabilityDefinition(
- NodeType nodeType,
- String capabilityDefinitionId) {
+ public static Optional<CapabilityDefinition> getCapabilityDefinition(NodeType nodeType,
+ String capabilityDefinitionId) {
if (nodeType == null || nodeType.getCapabilities() == null || capabilityDefinitionId == null) {
return Optional.empty();
}
@@ -480,12 +457,11 @@ public class DataModelUtil {
* @param groupName the group name
* @param group the group
*/
- public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate,
- String groupName, GroupDefinition group) {
+ public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate, String groupName,
+ GroupDefinition group) {
if (serviceTemplate == null) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Group Definition", SERVICE_TEMPLATE)
- .build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Group Definition", SERVICE_TEMPLATE)
+ .build());
}
TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
@@ -511,13 +487,10 @@ public class DataModelUtil {
* @param groupName the group name
* @param groupMemberId the group member id
*/
- public static void addGroupMember(ServiceTemplate serviceTemplate,
- String groupName,
- String groupMemberId) {
+ public static void addGroupMember(ServiceTemplate serviceTemplate, String groupName, String groupMemberId) {
TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
- if (Objects.isNull(topologyTemplate)
- || topologyTemplate.getGroups() == null
- || topologyTemplate.getGroups().get(groupName) == null) {
+ if (Objects.isNull(topologyTemplate) || topologyTemplate.getGroups() == null
+ || topologyTemplate.getGroups().get(groupName) == null) {
return;
}
@@ -542,11 +515,9 @@ public class DataModelUtil {
* @param defaultVal the default val
* @return the property definition
*/
- public static ParameterDefinition createParameterDefinition(String type, String description,
- boolean required,
- List<Constraint> constraints,
- EntrySchema entrySchema,
- Object defaultVal) {
+ public static ParameterDefinition createParameterDefinition(String type, String description, boolean required,
+ List<Constraint> constraints,
+ EntrySchema entrySchema, Object defaultVal) {
ParameterDefinition paramDef = new ParameterDefinition();
paramDef.setType(type);
paramDef.setDescription(description);
@@ -566,8 +537,8 @@ public class DataModelUtil {
* @param occurrences the occurrences
* @return the requirement definition
*/
- public static RequirementDefinition createRequirement(String capability, String node,
- String relationship, Object[] occurrences) {
+ public static RequirementDefinition createRequirement(String capability, String node, String relationship,
+ Object[] occurrences) {
RequirementDefinition requirementDefinition = new RequirementDefinition();
requirementDefinition.setCapability(capability);
requirementDefinition.setNode(node);
@@ -586,10 +557,8 @@ public class DataModelUtil {
* @param constraints the constraints
* @return the entry schema
*/
- public static EntrySchema createEntrySchema(String type, String description,
- List<Constraint> constraints) {
- if (Objects.isNull(type) && Objects.isNull(description)
- && CollectionUtils.isEmpty(constraints)) {
+ public static EntrySchema createEntrySchema(String type, String description, List<Constraint> constraints) {
+ if (Objects.isNull(type) && Objects.isNull(description) && CollectionUtils.isEmpty(constraints)) {
return null;
}
@@ -608,9 +577,8 @@ public class DataModelUtil {
* @param nestedPropertyName the nested property name
* @return the map
*/
- public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName,
- int indexInTheList,
- String... nestedPropertyName) {
+ public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName, int indexInTheList,
+ String... nestedPropertyName) {
List<Object> propertyList = new ArrayList<>();
propertyList.add(inputPropertyListName);
propertyList.add(indexInTheList);
@@ -628,8 +596,7 @@ public class DataModelUtil {
* @param propertyDefinition the property definition
* @return the parameter definition ext
*/
- public static ParameterDefinitionExt convertPropertyDefToParameterDef(
- PropertyDefinition propertyDefinition) {
+ public static ParameterDefinitionExt convertPropertyDefToParameterDef(PropertyDefinition propertyDefinition) {
if (propertyDefinition == null) {
return null;
}
@@ -641,8 +608,8 @@ public class DataModelUtil {
parameterDefinition.set_default(propertyDefinition.get_default());
parameterDefinition.setStatus(propertyDefinition.getStatus());
parameterDefinition.setConstraints(propertyDefinition.getConstraints());
- parameterDefinition.setEntry_schema(Objects.isNull(propertyDefinition.getEntry_schema()) ? null
- : propertyDefinition.getEntry_schema().clone());
+ parameterDefinition.setEntry_schema(Objects.isNull(propertyDefinition.getEntry_schema()) ? null :
+ propertyDefinition.getEntry_schema().clone());
parameterDefinition.setHidden(false);
parameterDefinition.setImmutable(false);
return parameterDefinition;
@@ -655,8 +622,8 @@ public class DataModelUtil {
* @param outputValue the output value
* @return the parameter definition ext
*/
- public static ParameterDefinitionExt convertAttributeDefToParameterDef(
- AttributeDefinition attributeDefinition, Map<String, List> outputValue) {
+ public static ParameterDefinitionExt convertAttributeDefToParameterDef(AttributeDefinition attributeDefinition,
+ Map<String, List> outputValue) {
if (attributeDefinition == null) {
return null;
}
@@ -668,7 +635,7 @@ public class DataModelUtil {
public static boolean isNodeTemplate(String entryId, ServiceTemplate serviceTemplate) {
return serviceTemplate.getTopology_template().getNode_templates() != null
- && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null;
+ && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null;
}
/**
@@ -679,12 +646,11 @@ public class DataModelUtil {
* @param parameterDefinition the parameter definition
*/
public static void addInputParameterToTopologyTemplate(ServiceTemplate serviceTemplate,
- String parameterDefinitionId,
- ParameterDefinition parameterDefinition) {
+ String parameterDefinitionId,
+ ParameterDefinition parameterDefinition) {
if (Objects.isNull(serviceTemplate)) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Topology Template Input Parameter",
- SERVICE_TEMPLATE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Topology Template Input Parameter",
+ SERVICE_TEMPLATE).build());
}
TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
if (Objects.isNull(topologyTemplate)) {
@@ -705,12 +671,11 @@ public class DataModelUtil {
* @param parameterDefinition the parameter definition
*/
public static void addOutputParameterToTopologyTemplate(ServiceTemplate serviceTemplate,
- String parameterDefinitionId,
- ParameterDefinition parameterDefinition) {
+ String parameterDefinitionId,
+ ParameterDefinition parameterDefinition) {
if (Objects.isNull(serviceTemplate)) {
- throw new CoreException(
- new InvalidAddActionNullEntityErrorBuilder("Topology Template Output Parameter",
- SERVICE_TEMPLATE).build());
+ throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Topology Template Output Parameter",
+ SERVICE_TEMPLATE).build());
}
TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
if (Objects.isNull(topologyTemplate)) {
@@ -730,7 +695,7 @@ public class DataModelUtil {
* @param requirementDef added requirement def
*/
public static void addRequirementToList(List<Map<String, RequirementDefinition>> requirementList,
- Map<String, RequirementDefinition> requirementDef) {
+ Map<String, RequirementDefinition> requirementDef) {
if (requirementDef == null) {
return;
}
@@ -748,8 +713,7 @@ public class DataModelUtil {
*
* @param nodeTemplate node template
*/
- public static Map<String, RequirementAssignment> getNodeTemplateRequirements(
- NodeTemplate nodeTemplate) {
+ public static Map<String, RequirementAssignment> getNodeTemplateRequirements(NodeTemplate nodeTemplate) {
if (Objects.isNull(nodeTemplate)) {
return null;
}
@@ -761,14 +725,11 @@ public class DataModelUtil {
}
YamlUtil yamlUtil = new YamlUtil();
for (Map<String, RequirementAssignment> requirementAssignmentMap : templateRequirements) {
- for (Map.Entry<String, RequirementAssignment> requirementEntry : requirementAssignmentMap
- .entrySet()) {
- RequirementAssignment requirementAssignment = (
- yamlUtil
- .yamlToObject(yamlUtil.objectToYaml(requirementEntry.getValue()),
- RequirementAssignment.class));
- nodeTemplateRequirementsAssignment
- .put(requirementEntry.getKey(), requirementAssignment);
+ for (Map.Entry<String, RequirementAssignment> requirementEntry : requirementAssignmentMap.entrySet()) {
+ RequirementAssignment requirementAssignment =
+ (yamlUtil.yamlToObject(yamlUtil.objectToYaml(requirementEntry.getValue()),
+ RequirementAssignment.class));
+ nodeTemplateRequirementsAssignment.put(requirementEntry.getKey(), requirementAssignment);
}
}
return nodeTemplateRequirementsAssignment;
@@ -780,24 +741,20 @@ public class DataModelUtil {
* @param nodeTemplate the node template
* @return the node template requirement list and null if the node has no requirements
*/
- public static List<Map<String, RequirementAssignment>> getNodeTemplateRequirementList(
- NodeTemplate nodeTemplate) {
+ public static List<Map<String, RequirementAssignment>> getNodeTemplateRequirementList(NodeTemplate nodeTemplate) {
ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
//Creating concrete objects
List<Map<String, RequirementAssignment>> requirements = nodeTemplate.getRequirements();
List<Map<String, RequirementAssignment>> concreteRequirementList = null;
if (requirements != null) {
concreteRequirementList = new ArrayList<>();
- ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements
- .listIterator();
+ ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements.listIterator();
while (reqListIterator.hasNext()) {
Map<String, RequirementAssignment> requirement = reqListIterator.next();
Map<String, RequirementAssignment> concreteRequirement = new HashMap<>();
for (Map.Entry<String, RequirementAssignment> reqEntry : requirement.entrySet()) {
- RequirementAssignment requirementAssignment = (
- toscaExtensionYamlUtil
- .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()),
- RequirementAssignment.class));
+ RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil.yamlToObject(
+ toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()), RequirementAssignment.class));
concreteRequirement.put(reqEntry.getKey(), requirementAssignment);
concreteRequirementList.add(concreteRequirement);
reqListIterator.remove();
@@ -816,9 +773,8 @@ public class DataModelUtil {
* @param requirementsAssignmentList requirement definition list
* @param requirementKey requirement key
*/
- public static Optional<List<RequirementAssignment>> getRequirementAssignment(
- List<Map<String, RequirementAssignment>> requirementsAssignmentList,
- String requirementKey) {
+ public static Optional<List<RequirementAssignment>> getRequirementAssignment(List<Map<String, RequirementAssignment>> requirementsAssignmentList,
+ String requirementKey) {
if (CollectionUtils.isEmpty(requirementsAssignmentList)) {
return Optional.empty();
}
@@ -827,10 +783,9 @@ public class DataModelUtil {
for (Map<String, RequirementAssignment> requirementMap : requirementsAssignmentList) {
if (requirementMap.containsKey(requirementKey)) {
YamlUtil yamlUtil = new YamlUtil();
- RequirementAssignment requirementAssignment = (
- yamlUtil
- .yamlToObject(yamlUtil.objectToYaml(requirementMap.get(requirementKey)),
- RequirementAssignment.class));
+ RequirementAssignment requirementAssignment =
+ (yamlUtil.yamlToObject(yamlUtil.objectToYaml(requirementMap.get(requirementKey)),
+ RequirementAssignment.class));
matchRequirementAssignmentList.add(requirementAssignment);
}
}
@@ -846,9 +801,8 @@ public class DataModelUtil {
* @param requirementsDefinitionList requirement definition list
* @param requirementKey requirement key
*/
- public static void removeRequirementsDefinition(
- List<Map<String, RequirementDefinition>> requirementsDefinitionList,
- String requirementKey) {
+ public static void removeRequirementsDefinition(List<Map<String, RequirementDefinition>> requirementsDefinitionList,
+ String requirementKey) {
if (requirementsDefinitionList == null) {
return;
}
@@ -871,9 +825,8 @@ public class DataModelUtil {
* @param requirementsAssignmentList requirement Assignment list
* @param requirementKey requirement key
*/
- public static void removeRequirementsAssignment(
- List<Map<String, RequirementAssignment>> requirementsAssignmentList,
- String requirementKey) {
+ public static void removeRequirementsAssignment(List<Map<String, RequirementAssignment>> requirementsAssignmentList,
+ String requirementKey) {
if (requirementsAssignmentList == null) {
return;
}
@@ -898,13 +851,10 @@ public class DataModelUtil {
* @param requirementKey the requirement key
* @param requirementAssignmentToBeDeleted the requirement assignment to be deleted
*/
- public static void removeRequirementAssignment(
- NodeTemplate nodeTemplate,
- String requirementKey,
- RequirementAssignment requirementAssignmentToBeDeleted) {
+ public static void removeRequirementAssignment(NodeTemplate nodeTemplate, String requirementKey,
+ RequirementAssignment requirementAssignmentToBeDeleted) {
ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- List<Map<String, RequirementAssignment>> nodeTemplateRequirements = nodeTemplate
- .getRequirements();
+ List<Map<String, RequirementAssignment>> nodeTemplateRequirements = nodeTemplate.getRequirements();
if (nodeTemplateRequirements == null) {
return;
}
@@ -915,10 +865,12 @@ public class DataModelUtil {
RequirementAssignment requirementAssignment = reqMap.get(requirementKey);
if (requirementAssignment != null) {
boolean isDesiredRequirementAssignment = toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment,
- requirementAssignmentToBeDeleted.getCapability(),
- requirementAssignmentToBeDeleted.getNode(),
- requirementAssignmentToBeDeleted.getRelationship());
+ .isDesiredRequirementAssignment(requirementAssignment,
+ requirementAssignmentToBeDeleted
+ .getCapability(),
+ requirementAssignmentToBeDeleted.getNode(),
+ requirementAssignmentToBeDeleted
+ .getRelationship());
if (isDesiredRequirementAssignment) {
iter.remove();
}
@@ -950,8 +902,7 @@ public class DataModelUtil {
* @param importId namespace
* @return true if exist, false if not exist
*/
- public static boolean isImportAddedToServiceTemplate(List<Map<String, Import>> imports,
- String importId) {
+ public static boolean isImportAddedToServiceTemplate(List<Map<String, Import>> imports, String importId) {
for (Map<String, Import> anImport : imports) {
if (anImport.containsKey(importId)) {
return true;
@@ -967,11 +918,9 @@ public class DataModelUtil {
* @param outputParameterId output parameter id
* @return ParameterDefinition - output parameter
*/
- public static ParameterDefinition getOuputParameter(ServiceTemplate serviceTemplate,
- String outputParameterId) {
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getOutputs() == null) {
+ public static ParameterDefinition getOuputParameter(ServiceTemplate serviceTemplate, String outputParameterId) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getOutputs() == null) {
return null;
}
return serviceTemplate.getTopology_template().getOutputs().get(outputParameterId);
@@ -983,11 +932,9 @@ public class DataModelUtil {
* @param serviceTemplate the service template
* @return the input parameters
*/
- public static Map<String, ParameterDefinition> getInputParameters(ServiceTemplate
- serviceTemplate) {
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getInputs() == null) {
+ public static Map<String, ParameterDefinition> getInputParameters(ServiceTemplate serviceTemplate) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getInputs() == null) {
return null;
}
return serviceTemplate.getTopology_template().getInputs();
@@ -999,11 +946,9 @@ public class DataModelUtil {
* @param serviceTemplate the service template
* @return the relationship template
*/
- public static Map<String, RelationshipTemplate> getRelationshipTemplates(ServiceTemplate
- serviceTemplate) {
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getRelationship_templates() == null) {
+ public static Map<String, RelationshipTemplate> getRelationshipTemplates(ServiceTemplate serviceTemplate) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getRelationship_templates() == null) {
return null;
}
return serviceTemplate.getTopology_template().getRelationship_templates();
@@ -1016,10 +961,8 @@ public class DataModelUtil {
* @param propertyId property id
* @return Object property Value
*/
- public static Object getPropertyValue(NodeTemplate nodeTemplate,
- String propertyId) {
- if (nodeTemplate == null
- || nodeTemplate.getProperties() == null) {
+ public static Object getPropertyValue(NodeTemplate nodeTemplate, String propertyId) {
+ if (nodeTemplate == null || nodeTemplate.getProperties() == null) {
return null;
}
return nodeTemplate.getProperties().get(propertyId);
@@ -1033,15 +976,13 @@ public class DataModelUtil {
* @return node template properties
*/
public static Map<String, Object> getNodeTemplateProperties(ServiceTemplate serviceTemplate,
- String nodeTemplateId) {
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getNode_templates() == null
- || serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) == null) {
+ String nodeTemplateId) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getNode_templates() == null
+ || serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) == null) {
return null;
}
- return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId)
- .getProperties();
+ return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId).getProperties();
}
/**
@@ -1051,9 +992,7 @@ public class DataModelUtil {
* @param propertyKey the property key
* @param propertyValue the property value
*/
- public static void addNodeTemplateProperty(NodeTemplate nodeTemplate,
- String propertyKey,
- Object propertyValue) {
+ public static void addNodeTemplateProperty(NodeTemplate nodeTemplate, String propertyKey, Object propertyValue) {
if (Objects.isNull(nodeTemplate)) {
return;
}
@@ -1072,9 +1011,8 @@ public class DataModelUtil {
* @return the substitution mappings
*/
public static SubstitutionMapping getSubstitutionMappings(ServiceTemplate serviceTemplate) {
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
return null;
}
return serviceTemplate.getTopology_template().getSubstitution_mappings();
@@ -1088,11 +1026,8 @@ public class DataModelUtil {
* @param second the second requirement assignment object
* @return true if objects are equal and false otherwise
*/
- public static boolean compareRequirementAssignment(RequirementAssignment first,
- RequirementAssignment second) {
- return (
- first.getCapability().equals(second.getCapability())
- && first.getNode().equals(second.getNode())
+ public static boolean compareRequirementAssignment(RequirementAssignment first, RequirementAssignment second) {
+ return (first.getCapability().equals(second.getCapability()) && first.getNode().equals(second.getNode())
&& first.getRelationship().equals(second.getRelationship()));
}
@@ -1126,8 +1061,7 @@ public class DataModelUtil {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
//Deserialize object
- ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream
- .toByteArray());
+ ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
clonedObjectValue = objectInputStream.readObject();
} catch (NotSerializableException ex) {
@@ -1147,15 +1081,12 @@ public class DataModelUtil {
* @param nodeTemplate the node template
* @param count the count
*/
- public static void addSubstitutionFilteringProperty(String templateName,
- NodeTemplate nodeTemplate, int count) {
+ public static void addSubstitutionFilteringProperty(String templateName, NodeTemplate nodeTemplate, int count) {
Map<String, Object> serviceTemplateFilterPropertyValue = new HashMap<>();
Map<String, Object> properties = nodeTemplate.getProperties();
- serviceTemplateFilterPropertyValue.put(ToscaConstants
- .SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, templateName);
+ serviceTemplateFilterPropertyValue.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, templateName);
serviceTemplateFilterPropertyValue.put(ToscaConstants.COUNT_PROPERTY_NAME, count);
- properties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME,
- serviceTemplateFilterPropertyValue);
+ properties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, serviceTemplateFilterPropertyValue);
nodeTemplate.setProperties(properties);
}
@@ -1165,14 +1096,12 @@ public class DataModelUtil {
* @param computeNodeTemplateId compute node template id
* @param portNodeTemplate port node template
*/
- public static void addBindingReqFromPortToCompute(String computeNodeTemplateId,
- NodeTemplate portNodeTemplate) {
+ public static void addBindingReqFromPortToCompute(String computeNodeTemplateId, NodeTemplate portNodeTemplate) {
RequirementAssignment requirementAssignment = new RequirementAssignment();
requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
requirementAssignment.setNode(computeNodeTemplateId);
- addRequirementAssignment(portNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID,
- requirementAssignment);
+ addRequirementAssignment(portNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirementAssignment);
}
/**
@@ -1183,18 +1112,15 @@ public class DataModelUtil {
* @param mapping the mapping
* @return the substitution mapping
*/
- public static SubstitutionMapping createSubstitutionTemplateSubMapping(
- String nodeTypeKey,
- NodeType substitutionNodeType,
- Map<String, Map<String, List<String>>> mapping) {
+ public static SubstitutionMapping createSubstitutionTemplateSubMapping(String nodeTypeKey,
+ NodeType substitutionNodeType,
+ Map<String, Map<String, List<String>>> mapping) {
SubstitutionMapping substitutionMapping = new SubstitutionMapping();
substitutionMapping.setNode_type(nodeTypeKey);
- substitutionMapping.setCapabilities(
- manageCapabilityMapping(substitutionNodeType.getCapabilities(), mapping.get(ToscaConstants
- .CAPABILITY)));
+ substitutionMapping.setCapabilities(manageCapabilityMapping(substitutionNodeType.getCapabilities(),
+ mapping.get(ToscaConstants.CAPABILITY)));
substitutionMapping.setRequirements(
- manageRequirementMapping(substitutionNodeType.getRequirements(),
- mapping.get("requirement")));
+ manageRequirementMapping(substitutionNodeType.getRequirements(), mapping.get("requirement")));
return substitutionMapping;
}
@@ -1207,8 +1133,8 @@ public class DataModelUtil {
* @param capabilityAttributes the capability attributes
*/
public static void addNodeTemplateCapability(NodeTemplate nodeTemplate, String capabilityId,
- Map<String, Object> capabilityProperties,
- Map<String, Object> capabilityAttributes) {
+ Map<String, Object> capabilityProperties,
+ Map<String, Object> capabilityAttributes) {
Map<String, CapabilityAssignment> capabilities = nodeTemplate.getCapabilities();
if (Objects.isNull(capabilities)) {
capabilities = new HashMap<>();
@@ -1220,9 +1146,8 @@ public class DataModelUtil {
nodeTemplate.setCapabilities(capabilities);
}
- private static Map<String, List<String>> manageRequirementMapping(
- List<Map<String, RequirementDefinition>> requirementList,
- Map<String, List<String>> requirementSubstitutionMapping) {
+ private static Map<String, List<String>> manageRequirementMapping(List<Map<String, RequirementDefinition>> requirementList,
+ Map<String, List<String>> requirementSubstitutionMapping) {
if (requirementList == null) {
return null;
}
@@ -1239,9 +1164,8 @@ public class DataModelUtil {
return requirementMapping;
}
- private static Map<String, List<String>> manageCapabilityMapping(
- Map<String, CapabilityDefinition> capabilities,
- Map<String, List<String>> capabilitySubstitutionMapping) {
+ private static Map<String, List<String>> manageCapabilityMapping(Map<String, CapabilityDefinition> capabilities,
+ Map<String, List<String>> capabilitySubstitutionMapping) {
if (capabilities == null) {
return null;
}
@@ -1257,14 +1181,18 @@ public class DataModelUtil {
return capabilityMapping;
}
-
- public static void addInterfaceOperation(ServiceTemplate serviceTemplate,
- String interfaceId,
- String operationId,
- OperationDefinition operationDefinition) {
+ /**
+ * Add interface operation.
+ *
+ * @param serviceTemplate the service template
+ * @param interfaceId the interface id
+ * @param operationId the operation id
+ * @param operationDefinition the operation definition
+ */
+ public static void addInterfaceOperation(ServiceTemplate serviceTemplate, String interfaceId, String operationId,
+ OperationDefinition operationDefinition) {
Map<String, Object> interfaceTypes = serviceTemplate.getInterface_types();
- if (MapUtils.isEmpty(interfaceTypes)
- || Objects.isNull(interfaceTypes.get(interfaceId))) {
+ if (MapUtils.isEmpty(interfaceTypes) || Objects.isNull(interfaceTypes.get(interfaceId))) {
return;
}
@@ -1289,8 +1217,7 @@ public class DataModelUtil {
interfaceValue -> convertedInterfaceTypes.put(interfaceEntry.getKey(), interfaceValue));
} catch (Exception e) {
LOGGER.error("Cannot create interface object", e);
- throw new CoreException(
- new ToscaInvalidInterfaceValueErrorBuilder(e.getMessage()).build());
+ throw new CoreException(new ToscaInvalidInterfaceValueErrorBuilder(e.getMessage()).build());
}
}
@@ -1298,35 +1225,23 @@ public class DataModelUtil {
}
public static <T extends InterfaceDefinition> Optional<T> convertObjToInterfaceDefinition(String interfaceId,
- Object interfaceObj,
- Class<T> interfaceClass) {
+ Object interfaceObj,
+ Class<T> interfaceClass) {
try {
- Optional<T> interfaceDefinition =
- CommonUtil.createObjectUsingSetters(interfaceObj, interfaceClass);
+ Optional<T> interfaceDefinition = CommonUtil.createObjectUsingSetters(interfaceObj, interfaceClass);
interfaceDefinition.ifPresent(interfaceDefinitionType1 -> updateInterfaceDefinitionOperations(
- CommonUtil.getObjectAsMap(interfaceObj),
- interfaceDefinitionType1, getOperationClass(interfaceClass)));
+ CommonUtil.getObjectAsMap(interfaceObj), interfaceDefinitionType1));
return interfaceDefinition;
} catch (Exception ex) {
- LOGGER.error("Could not create {} from {}", InterfaceDefinitionType.class.getName(),
- interfaceId, ex);
- throw new CoreException(
- new CreateInterfaceObjectErrorBuilder(InterfaceDefinitionType.class.getName(),
- interfaceId,
- ex.getMessage()).build());
+ LOGGER.error("Could not create {} from {}", InterfaceDefinitionType.class.getName(), interfaceId, ex);
+ throw new CoreException(new CreateInterfaceObjectErrorBuilder(InterfaceDefinitionType.class.getName(),
+ interfaceId, ex.getMessage()).build());
}
}
- private static <T extends OperationDefinition, V extends InterfaceDefinition> Class<T> getOperationClass(
- Class<V> interfaceClass) {
- return interfaceClass.equals(InterfaceDefinitionType.class)
- ? (Class<T>) OperationDefinitionType.class
- : (Class<T>) OperationDefinitionTemplate.class;
- }
- public static Optional<InterfaceType> convertObjToInterfaceType(String interfaceId,
- Object interfaceObj) {
+ public static Optional<InterfaceType> convertObjToInterfaceType(String interfaceId, Object interfaceObj) {
try {
Optional<InterfaceType> interfaceType =
CommonUtil.createObjectUsingSetters(interfaceObj, InterfaceType.class);
@@ -1336,9 +1251,8 @@ public class DataModelUtil {
return interfaceType;
} catch (Exception ex) {
LOGGER.error("Could not create {} from {}", InterfaceType.class.getName(), interfaceId, ex);
- throw new CoreException(
- new CreateInterfaceObjectErrorBuilder(InterfaceType.class.getName(), interfaceId,
- ex.getMessage()).build());
+ throw new CoreException(new CreateInterfaceObjectErrorBuilder(InterfaceType.class.getName(), interfaceId,
+ ex.getMessage()).build());
}
}
@@ -1346,6 +1260,10 @@ public class DataModelUtil {
return converInterfaceToToscaInterfaceObj(interfaceType);
}
+ public static Optional<Object> convertInterfaceDefinitionTypeToObj(InterfaceDefinitionType interfaceDefinitionType) {
+ return converInterfaceToToscaInterfaceObj(interfaceDefinitionType);
+ }
+
private static Optional<Object> converInterfaceToToscaInterfaceObj(Object interfaceEntity) {
if (Objects.isNull(interfaceEntity)) {
return Optional.empty();
@@ -1363,75 +1281,53 @@ public class DataModelUtil {
return Optional.of(objectMapper.convertValue(interfaceAsMap, Object.class));
}
- private static void updateInterfaceTypeOperations(Map<String, Object> interfaceAsMap,
- InterfaceType interfaceType) {
+ private static void updateInterfaceTypeOperations(Map<String, Object> interfaceAsMap, InterfaceType interfaceType) {
Set<String> fieldNames = CommonUtil.getClassFieldNames(InterfaceType.class);
for (Map.Entry<String, Object> entry : interfaceAsMap.entrySet()) {
Optional<? extends OperationDefinition> operationDefinition =
- createOperation(entry.getKey(), entry.getValue(), fieldNames,
- OperationDefinitionType.class);
- operationDefinition
- .ifPresent(operation -> interfaceType.addOperation(entry.getKey(), operation));
+ createOperation(entry.getKey(), entry.getValue(), fieldNames, OperationDefinitionType.class);
+ operationDefinition.ifPresent(operation -> interfaceType.addOperation(entry.getKey(), operation));
}
}
private static Optional<? extends OperationDefinition> createOperation(String propertyName,
- Object operationCandidate,
- Set<String> fieldNames,
- Class<? extends OperationDefinition>
- operationClass) {
+ Object operationCandidate,
+ Set<String> fieldNames,
+ Class<? extends OperationDefinition> operationClass) {
if (!fieldNames.contains(propertyName)) {
try {
return CommonUtil.createObjectUsingSetters(operationCandidate, operationClass);
} catch (Exception ex) {
LOGGER.error("Could not create Operation from {}", propertyName, ex);
- throw new CoreException(
- new CreateInterfaceOperationObjectErrorBuilder(propertyName, ex.getMessage()).build());
+ throw new CoreException(new CreateInterfaceOperationObjectErrorBuilder(propertyName, ex.getMessage())
+ .build());
}
}
return Optional.empty();
}
- private static <T extends OperationDefinition> void updateInterfaceDefinitionOperations(Map<String, Object>
- interfaceAsMap,
- InterfaceDefinition
- interfaceDefinition,
- Class<T> operationClass) {
- Set<String> fieldNames = CommonUtil.getClassFieldNames(interfaceDefinition.getClass());
- Optional<? extends OperationDefinition> operationDefinition;
+ private static <T extends OperationDefinition> void updateInterfaceDefinitionOperations(Map<String, Object> interfaceAsMap,
+ InterfaceDefinition interfaceDefinition) {
+ {
+ Set<String> fieldNames = CommonUtil.getClassFieldNames(InterfaceDefinitionType.class);
+ Optional<? extends OperationDefinition> operationDefinition;
- for (Map.Entry<String, Object> entry : interfaceAsMap.entrySet()) {
- operationDefinition =
- createOperation(entry.getKey(), entry.getValue(), fieldNames, operationClass);
- operationDefinition.ifPresent(operation -> addOperationToInterface(interfaceDefinition,
- entry.getKey(), operation));
+ for (Map.Entry<String, Object> entry : interfaceAsMap.entrySet()) {
+ operationDefinition = createOperation(entry.getKey(), entry.getValue(), fieldNames,
+ interfaceDefinition instanceof InterfaceDefinitionType ? OperationDefinitionType.class :
+ OperationDefinitionTemplate.class);
+ operationDefinition.ifPresent(operation -> interfaceDefinition.addOperation(entry.getKey(), operation));
+ }
}
}
- private static void addOperationToInterface(InterfaceDefinition interfaceDefinition,
- String operationName,
- OperationDefinition operationDefinition) {
- if (interfaceDefinition instanceof InterfaceDefinitionType) {
- InterfaceDefinitionType interfaceDefinitionType =
- (InterfaceDefinitionType) interfaceDefinition;
- interfaceDefinitionType.addOperation(operationName, (OperationDefinitionType)
- operationDefinition);
- }
- if (interfaceDefinition instanceof InterfaceDefinitionTemplate) {
- InterfaceDefinitionTemplate interfaceDefinitionTemplate =
- (InterfaceDefinitionTemplate) interfaceDefinition;
- interfaceDefinitionTemplate.addOperation(operationName, (OperationDefinitionTemplate)
- operationDefinition);
- }
- }
public static void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType,
- List<Map<String, RequirementDefinition>>
- requirementsList,
- String templateName) {
+ List<Map<String, RequirementDefinition>> requirementsList,
+ String templateName) {
if (CollectionUtils.isEmpty(requirementsList)) {
return;
}
@@ -1448,9 +1344,27 @@ public class DataModelUtil {
}
}
- public static boolean isNodeTemplateSectionMissingFromServiceTemplate(
- ServiceTemplate serviceTemplate) {
- return Objects.isNull(serviceTemplate.getTopology_template())
- || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates());
+ public static boolean isNodeTemplateSectionMissingFromServiceTemplate(ServiceTemplate serviceTemplate) {
+ return Objects.isNull(serviceTemplate.getTopology_template()) || MapUtils.isEmpty(
+ serviceTemplate.getTopology_template().getNode_templates());
+ }
+
+ /**
+ * Gets relationship template in a service template according to the relationship id.
+ *
+ * @param serviceTemplate the service template
+ * @param relationshipId the relationship id
+ * @return the relationship template
+ */
+ public static Optional<RelationshipTemplate> getRelationshipTemplate(ServiceTemplate serviceTemplate,
+ String relationshipId) {
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getRelationship_templates() == null
+ || serviceTemplate.getTopology_template().getRelationship_templates().get(relationshipId) == null) {
+ return Optional.empty();
+ }
+ return Optional.of(serviceTemplate.getTopology_template().getRelationship_templates().get(relationshipId));
}
+
+
}
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java
index e4d75c1296..34f5a905fd 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java
@@ -17,7 +17,7 @@
package org.openecomp.sdc.tosca.services;
import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
-import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
+import org.openecomp.sdc.tosca.datatypes.ToscaFlatData;
import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
import org.onap.sdc.tosca.datatypes.model.DefinitionOfDataType;
import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
@@ -33,67 +33,62 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-public interface ToscaAnalyzerService {
+import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
- /*
- node template with type equal to node type or derived from node type
- */
- Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType,
- ToscaServiceModel toscaServiceModel);
+public interface ToscaAnalyzerService {
- Optional<NodeType> fetchNodeType(String nodeTypeKey, Collection<ServiceTemplate> serviceTemplates);
+ /*
+ node template with type equal to node type or derived from node type
+ */
+ Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType,
+ ToscaServiceModel toscaServiceModel);
- boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaServiceModel);
+ Optional<NodeType> fetchNodeType(String nodeTypeKey, Collection<ServiceTemplate> serviceTemplates);
- List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate, String requirementId);
+ boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel);
- Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate,
- String nodeTemplateId);
+ boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel);
- Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId,
- NodeTemplate substitutableNodeTemplate);
+ boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel);
- Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate);
+ List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate, String requirementId);
- Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq(
- String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate,
- String requirementId);
+ Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate, String nodeTemplateId);
- /*
- match only for the input which is not null
- */
- boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment,
- String capability, String node, String relationship);
+ Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId,
+ NodeTemplate substitutableNodeTemplate);
- Object getFlatEntity(ToscaElementTypes elementType, String type, ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaModel);
+ Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate);
- boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate);
+ Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq(String substituteServiceTemplateFileName,
+ ServiceTemplate substituteServiceTemplate,
+ String requirementId);
- NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate,
- String nodeTypeDerivedFromValue);
+ /*
+ match only for the input which is not null
+ */
+ boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, String capability, String node,
+ String relationship);
- boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate,
- String requirementId,
- RequirementAssignment requirementAssignment);
+ ToscaFlatData getFlatEntity(ToscaElementTypes elementType, String type, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaModel);
- Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
- ServiceTemplate substitutionServiceTemplate);
+ boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate);
- Map<String, CapabilityDefinition> calculateExposedCapabilities(
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinitionMap);
+ NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate,
+ String nodeTypeDerivedFromValue);
- List<Map<String, RequirementDefinition>> calculateExposedRequirements(
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinitionList,
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment);
+ boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId,
+ RequirementAssignment requirementAssignment);
- boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType,
- ServiceTemplate
- serviceTemplate, ToscaServiceModel toscaServiceModel);
+ Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate);
- boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType, ServiceTemplate
- serviceTemplate, ToscaServiceModel toscaServiceModel);
+ Map<String, CapabilityDefinition> calculateExposedCapabilities(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinitionMap);
+ List<Map<String, RequirementDefinition>> calculateExposedRequirements(List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinitionList,
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment);
}
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java
index 4ce2535401..d81983057d 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java
@@ -36,6 +36,9 @@ public class ToscaConstants {
//General
public static final String TOSCA_DEFINITIONS_VERSION = "tosca_simple_yaml_1_0_0";
public static final String MODELABLE_ENTITY_NAME_SELF = "SELF";
+ public static final String MODELABLE_ENTITY_NAME_HOST = "HOST";
+ public static final String MODELABLE_ENTITY_NAME_SOURCE = "SOURCE";
+ public static final String MODELABLE_ENTITY_NAME_TARGET = "TARGET";
public static final String NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE = "substitutable";
public static final String UNBOUNDED = "UNBOUNDED";
public static final String ST_METADATA_TEMPLATE_NAME = "template_name";
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java
index 46d9b902ca..46e58bdc81 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java
@@ -22,7 +22,7 @@ import org.apache.commons.lang3.StringUtils;
import org.openecomp.core.utilities.CommonMethods;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
-import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
+import org.openecomp.sdc.tosca.datatypes.ToscaFlatData;
import org.onap.sdc.tosca.datatypes.model.AttributeDefinition;
import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
import org.onap.sdc.tosca.datatypes.model.CapabilityType;
@@ -38,18 +38,18 @@ import org.onap.sdc.tosca.datatypes.model.PropertyType;
import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
+import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
+import org.openecomp.sdc.tosca.errors.CreateInterfaceObjectErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaElementTypeNotFoundErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaFileNotFoundErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaInvalidEntryNotFoundErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder;
import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstitutionServiceTemplateErrorBuilder;
import org.openecomp.sdc.tosca.services.DataModelUtil;
+import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
import org.openecomp.sdc.tosca.services.ToscaConstants;
-import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
-import org.openecomp.sdc.tosca.services.ToscaUtil;
-import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -60,877 +60,911 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.lang.reflect.InvocationTargetException;
+
+import org.openecomp.sdc.tosca.services.ToscaUtil;
public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService {
- private final String GET_NODE_TYPE_METHOD_NAME = "getNode_types";
- private final String GET_DERIVED_FROM_METHOD_NAME = "getDerived_from";
- private final String GET_TYPE_METHOD_NAME = "getType";
- private final String GET_DATA_TYPE_METHOD_NAME = "getData_types";
- private final String GET_INTERFACE_TYPE_METHOD_NAME = "getInterface_types";
- private final String TOSCA_DOT = "tosca.";
- private final String DOT_ROOT = ".Root";
-
- @Override
- public List<Map<String, RequirementDefinition>> calculateExposedRequirements(
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinitionList,
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment) {
-
- if (nodeTypeRequirementsDefinitionList == null) {
- return Collections.emptyList();
- }
- for (Map.Entry<String, RequirementAssignment> entry : nodeTemplateRequirementsAssignment
- .entrySet()) {
- if (entry.getValue().getNode() != null) {
- Optional<RequirementDefinition> requirementDefinition =
- DataModelUtil.getRequirementDefinition(nodeTypeRequirementsDefinitionList, entry
- .getKey());
- RequirementDefinition cloneRequirementDefinition;
- if (requirementDefinition.isPresent()) {
- cloneRequirementDefinition = requirementDefinition.get().clone();
- updateRequirementDefinition(nodeTypeRequirementsDefinitionList, entry,
- cloneRequirementDefinition);
- }
- } else {
- for (Map<String, RequirementDefinition> nodeTypeRequirementsMap :
- nodeTypeRequirementsDefinitionList) {
- updateMinMaxOccurencesForNodeTypeRequirement(entry, nodeTypeRequirementsMap);
- }
- }
- }
- return nodeTypeRequirementsDefinitionList;
- }
-
- private void updateMinMaxOccurencesForNodeTypeRequirement(
- Map.Entry<String, RequirementAssignment> entry,
- Map<String, RequirementDefinition> nodeTypeRequirementsMap) {
- Object max = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null
- && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0
- ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[1] : 1;
- Object min = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null
- && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0
- ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[0] : 1;
- nodeTypeRequirementsMap.get(entry.getKey()).setOccurrences(new Object[]{min, max});
- }
-
- private void updateRequirementDefinition(
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinitionList,
- Map.Entry<String, RequirementAssignment> entry,
- RequirementDefinition cloneRequirementDefinition) {
- if (!evaluateRequirementFulfillment(cloneRequirementDefinition)) {
- CommonMethods.mergeEntryInList(entry.getKey(), cloneRequirementDefinition,
- nodeTypeRequirementsDefinitionList);
- } else {
- DataModelUtil.removeRequirementsDefinition(nodeTypeRequirementsDefinitionList, entry
- .getKey());
- }
- }
-
- private static boolean evaluateRequirementFulfillment(RequirementDefinition
- requirementDefinition) {
- Object[] occurrences = requirementDefinition.getOccurrences();
- if (occurrences == null) {
- requirementDefinition.setOccurrences(new Object[]{1, 1});
- return false;
- }
- if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) {
- return false;
- }
-
- if (occurrences[1].equals(1)) {
- return true;
- }
- occurrences[1] = (Integer) occurrences[1] - 1;
- return false;
- }
-
- @Override
- public Map<String, CapabilityDefinition> calculateExposedCapabilities(
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinitionMap) {
-
- String capabilityKey;
- String capability;
- String node;
- for (Map.Entry<String, Map<String, RequirementAssignment>> entry :
- fullFilledRequirementsDefinitionMap.entrySet()) {
- for (Map.Entry<String, RequirementAssignment> fullFilledEntry : entry.getValue().entrySet()) {
-
- capability = fullFilledEntry.getValue().getCapability();
- node = fullFilledEntry.getValue().getNode();
- capabilityKey = capability + "_" + node;
- CapabilityDefinition capabilityDefinition = nodeTypeCapabilitiesDefinition.get(
- capabilityKey);
- if (capabilityDefinition != null) {
- CapabilityDefinition clonedCapabilityDefinition = capabilityDefinition.clone();
- nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityDefinition.clone());
- updateNodeTypeCapabilitiesDefinition(nodeTypeCapabilitiesDefinition, capabilityKey,
- clonedCapabilityDefinition);
- }
- }
- }
-
- Map<String, CapabilityDefinition> exposedCapabilitiesDefinition = new HashMap<>();
- for (Map.Entry<String, CapabilityDefinition> entry : nodeTypeCapabilitiesDefinition
- .entrySet()) {
- exposedCapabilitiesDefinition.put(entry.getKey(), entry.getValue());
- }
- return exposedCapabilitiesDefinition;
- }
-
- private void updateNodeTypeCapabilitiesDefinition(
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition, String capabilityKey,
- CapabilityDefinition clonedCapabilityDefinition) {
- if (evaluateCapabilityFulfillment(clonedCapabilityDefinition)) {
- nodeTypeCapabilitiesDefinition.remove(capabilityKey);
- } else {
- nodeTypeCapabilitiesDefinition.put(capabilityKey, clonedCapabilityDefinition);
- }
- }
-
- private static boolean evaluateCapabilityFulfillment(CapabilityDefinition capabilityDefinition) {
-
- Object[] occurrences = capabilityDefinition.getOccurrences();
- if (occurrences == null) {
- capabilityDefinition.setOccurrences(new Object[]{1, ToscaConstants.UNBOUNDED});
- return false;
- }
- if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) {
- return false;
- }
-
- if (occurrences[1].equals(1)) {
- return true;
- }
- occurrences[1] = (Integer) occurrences[1] - 1;
- return false;
- }
-
- /*
- node template with type equal to node type or derived from node type
+
+ private final String GET_NODE_TYPE_METHOD_NAME = "getNode_types";
+ private final String GET_DERIVED_FROM_METHOD_NAME = "getDerived_from";
+ private final String GET_TYPE_METHOD_NAME = "getType";
+ private final String GET_DATA_TYPE_METHOD_NAME = "getData_types";
+ private final String GET_INTERFACE_TYPE_METHOD_NAME = "getInterface_types";
+ private final String TOSCA_DOT = "tosca.";
+ private final String DOT_ROOT = ".Root";
+
+ @Override
+ public List<Map<String, RequirementDefinition>> calculateExposedRequirements(List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinitionList,
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment) {
+
+ if (nodeTypeRequirementsDefinitionList == null) {
+ return Collections.emptyList();
+ }
+ for (Map.Entry<String, RequirementAssignment> entry : nodeTemplateRequirementsAssignment.entrySet()) {
+ if (entry.getValue().getNode() != null) {
+ Optional<RequirementDefinition> requirementDefinition =
+ DataModelUtil.getRequirementDefinition(nodeTypeRequirementsDefinitionList, entry.getKey());
+ RequirementDefinition cloneRequirementDefinition;
+ if (requirementDefinition.isPresent()) {
+ cloneRequirementDefinition = requirementDefinition.get().clone();
+ updateRequirementDefinition(nodeTypeRequirementsDefinitionList, entry, cloneRequirementDefinition);
+ }
+ } else {
+ for (Map<String, RequirementDefinition> nodeTypeRequirementsMap : nodeTypeRequirementsDefinitionList) {
+ updateMinMaxOccurencesForNodeTypeRequirement(entry, nodeTypeRequirementsMap);
+ }
+ }
+ }
+ return nodeTypeRequirementsDefinitionList;
+ }
+
+ private void updateMinMaxOccurencesForNodeTypeRequirement(Map.Entry<String, RequirementAssignment> entry,
+ Map<String, RequirementDefinition> nodeTypeRequirementsMap) {
+ Object max = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null
+ && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 ?
+ nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[1] : 1;
+ Object min = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null
+ && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 ?
+ nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[0] : 1;
+ nodeTypeRequirementsMap.get(entry.getKey()).setOccurrences(new Object[] {min, max});
+ }
+
+ private void updateRequirementDefinition(List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinitionList,
+ Map.Entry<String, RequirementAssignment> entry,
+ RequirementDefinition cloneRequirementDefinition) {
+ if (!evaluateRequirementFulfillment(cloneRequirementDefinition)) {
+ CommonMethods
+ .mergeEntryInList(entry.getKey(), cloneRequirementDefinition, nodeTypeRequirementsDefinitionList);
+ } else {
+ DataModelUtil.removeRequirementsDefinition(nodeTypeRequirementsDefinitionList, entry.getKey());
+ }
+ }
+
+ private static boolean evaluateRequirementFulfillment(RequirementDefinition requirementDefinition) {
+ Object[] occurrences = requirementDefinition.getOccurrences();
+ if (occurrences == null) {
+ requirementDefinition.setOccurrences(new Object[] {1, 1});
+ return false;
+ }
+ if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) {
+ return false;
+ }
+
+ if (occurrences[1].equals(1)) {
+ return true;
+ }
+ occurrences[1] = (Integer) occurrences[1] - 1;
+ return false;
+ }
+
+ @Override
+ public Map<String, CapabilityDefinition> calculateExposedCapabilities(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinitionMap) {
+
+ String capabilityKey;
+ String capability;
+ String node;
+ for (Map.Entry<String, Map<String, RequirementAssignment>> entry : fullFilledRequirementsDefinitionMap
+ .entrySet()) {
+ for (Map.Entry<String, RequirementAssignment> fullFilledEntry : entry.getValue().entrySet()) {
+
+ capability = fullFilledEntry.getValue().getCapability();
+ node = fullFilledEntry.getValue().getNode();
+ capabilityKey = capability + "_" + node;
+ CapabilityDefinition capabilityDefinition = nodeTypeCapabilitiesDefinition.get(capabilityKey);
+ if (capabilityDefinition != null) {
+ CapabilityDefinition clonedCapabilityDefinition = capabilityDefinition.clone();
+ nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityDefinition.clone());
+ updateNodeTypeCapabilitiesDefinition(nodeTypeCapabilitiesDefinition, capabilityKey,
+ clonedCapabilityDefinition);
+ }
+ }
+ }
+
+ Map<String, CapabilityDefinition> exposedCapabilitiesDefinition = new HashMap<>();
+ for (Map.Entry<String, CapabilityDefinition> entry : nodeTypeCapabilitiesDefinition.entrySet()) {
+ exposedCapabilitiesDefinition.put(entry.getKey(), entry.getValue());
+ }
+ return exposedCapabilitiesDefinition;
+ }
+
+ private void updateNodeTypeCapabilitiesDefinition(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
+ String capabilityKey,
+ CapabilityDefinition clonedCapabilityDefinition) {
+ if (evaluateCapabilityFulfillment(clonedCapabilityDefinition)) {
+ nodeTypeCapabilitiesDefinition.remove(capabilityKey);
+ } else {
+ nodeTypeCapabilitiesDefinition.put(capabilityKey, clonedCapabilityDefinition);
+ }
+ }
+
+ private static boolean evaluateCapabilityFulfillment(CapabilityDefinition capabilityDefinition) {
+
+ Object[] occurrences = capabilityDefinition.getOccurrences();
+ if (occurrences == null) {
+ capabilityDefinition.setOccurrences(new Object[] {1, ToscaConstants.UNBOUNDED});
+ return false;
+ }
+ if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) {
+ return false;
+ }
+
+ if (occurrences[1].equals(1)) {
+ return true;
+ }
+ occurrences[1] = (Integer) occurrences[1] - 1;
+ return false;
+ }
+
+ /*
+ node template with type equal to node type or derived from node type
+ */
+ @Override
+ public Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType,
+ ToscaServiceModel toscaServiceModel) {
+ Map<String, NodeTemplate> nodeTemplates = new HashMap<>();
+
+ if (Objects.nonNull(serviceTemplate.getTopology_template()) && MapUtils.isNotEmpty(
+ serviceTemplate.getTopology_template().getNode_templates())) {
+ for (Map.Entry<String, NodeTemplate> nodeTemplateEntry : serviceTemplate.getTopology_template()
+ .getNode_templates().entrySet()) {
+ if (isTypeOf(nodeTemplateEntry.getValue(), nodeType, serviceTemplate, toscaServiceModel)) {
+ nodeTemplates.put(nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue());
+ }
+
+ }
+ }
+ return nodeTemplates;
+ }
+
+ @Override
+ public Optional<NodeType> fetchNodeType(String nodeTypeKey, Collection<ServiceTemplate> serviceTemplates) {
+ Optional<Map<String, NodeType>> nodeTypeMap = serviceTemplates.stream().map(ServiceTemplate::getNode_types)
+ .filter(nodeTypes -> Objects.nonNull(nodeTypes)
+ && nodeTypes
+ .containsKey(
+ nodeTypeKey))
+ .findFirst();
+ return nodeTypeMap.map(stringNodeTypeMap -> stringNodeTypeMap.get(nodeTypeKey));
+ }
+
+ @Override
+ public boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel) {
+ return isTypeOf(nodeTemplate, nodeType, GET_NODE_TYPE_METHOD_NAME, serviceTemplate, toscaServiceModel);
+ }
+
+ @Override
+ public List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate, String requirementId) {
+ List<RequirementAssignment> requirements = new ArrayList<>();
+ List<Map<String, RequirementAssignment>> requirementList = nodeTemplate.getRequirements();
+ if (requirementList != null) {
+ requirementList.stream().filter(reqMap -> reqMap.get(requirementId) != null).forEach(reqMap -> {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ RequirementAssignment reqAssignment = toscaExtensionYamlUtil.yamlToObject(
+ toscaExtensionYamlUtil.objectToYaml(reqMap.get(requirementId)), RequirementAssignment.class);
+ requirements.add(reqAssignment);
+ });
+ }
+ return requirements;
+ }
+
+ @Override
+ public Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate, String nodeTemplateId) {
+ if ((serviceTemplate.getTopology_template() != null) && (serviceTemplate.getTopology_template()
+ .getNode_templates() != null)
+ && (serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) != null)) {
+ return Optional.of(serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId));
+ }
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId,
+ NodeTemplate substitutableNodeTemplate) {
+ if (!isSubstitutableNodeTemplate(substitutableNodeTemplate)) {
+ return Optional.empty();
+ }
+
+ if (substitutableNodeTemplate.getProperties() != null &&
+ substitutableNodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)
+ != null) {
+ Object serviceTemplateFilter =
+ substitutableNodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
+ if (serviceTemplateFilter != null && serviceTemplateFilter instanceof Map) {
+ Object substituteServiceTemplate =
+ ((Map) serviceTemplateFilter).get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
+ handleNoSubstituteServiceTemplate(substituteNodeTemplateId, substituteServiceTemplate);
+ return Optional.of(substituteServiceTemplate.toString());
+ }
+ }
+ throw new CoreException(new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId)
+ .build());
+ }
+
+ private void handleNoSubstituteServiceTemplate(String substituteNodeTemplateId, Object substituteServiceTemplate) {
+ if (substituteServiceTemplate == null) {
+ throw new CoreException(new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId)
+ .build());
+ }
+ }
+
+ @Override
+ public Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate) {
+ Map<String, NodeTemplate> substitutableNodeTemplates = new HashMap<>();
+
+ if (serviceTemplate == null || serviceTemplate.getTopology_template() == null
+ || serviceTemplate.getTopology_template().getNode_templates() == null) {
+ return substitutableNodeTemplates;
+ }
+
+ Map<String, NodeTemplate> nodeTemplates = serviceTemplate.getTopology_template().getNode_templates();
+ for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
+ String nodeTemplateId = entry.getKey();
+ NodeTemplate nodeTemplate = entry.getValue();
+ if (isSubstitutableNodeTemplate(nodeTemplate)) {
+ substitutableNodeTemplates.put(nodeTemplateId, nodeTemplate);
+ }
+ }
+
+ return substitutableNodeTemplates;
+ }
+
+ @Override
+ public Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq(String substituteServiceTemplateFileName,
+ ServiceTemplate substituteServiceTemplate,
+ String requirementId) {
+ if (isSubstitutionServiceTemplate(substituteServiceTemplateFileName, substituteServiceTemplate)) {
+ Map<String, List<String>> substitutionMappingRequirements =
+ substituteServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements();
+ if (substitutionMappingRequirements != null) {
+ List<String> requirementMapping = substitutionMappingRequirements.get(requirementId);
+ if (requirementMapping != null && !requirementMapping.isEmpty()) {
+ String mappedNodeTemplateId = requirementMapping.get(0);
+ Optional<NodeTemplate> mappedNodeTemplate =
+ getNodeTemplateById(substituteServiceTemplate, mappedNodeTemplateId);
+ mappedNodeTemplate.orElseThrow(
+ () -> new CoreException(new ToscaInvalidEntryNotFoundErrorBuilder("Node Template",
+ mappedNodeTemplateId)
+ .build()));
+ Map.Entry<String, NodeTemplate> mappedNodeTemplateEntry = new Map.Entry<String, NodeTemplate>() {
+ @Override
+ public String getKey() {
+ return mappedNodeTemplateId;
+ }
+
+ @Override
+ public NodeTemplate getValue() {
+ return mappedNodeTemplate.get();
+ }
+
+ @Override
+ public NodeTemplate setValue(NodeTemplate value) {
+ return null;
+ }
+ };
+ return Optional.of(mappedNodeTemplateEntry);
+ }
+ }
+ }
+ return Optional.empty();
+ }
+
+ /*
+ match only for the input which is not null
*/
- @Override
- public Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate,
- String nodeType,
- ToscaServiceModel toscaServiceModel) {
- Map<String, NodeTemplate> nodeTemplates = new HashMap<>();
-
- if (Objects.nonNull(serviceTemplate.getTopology_template())
- && MapUtils.isNotEmpty(serviceTemplate.getTopology_template().getNode_templates())) {
- for (Map.Entry<String, NodeTemplate> nodeTemplateEntry : serviceTemplate
- .getTopology_template().getNode_templates().entrySet()) {
- if (isTypeOf(nodeTemplateEntry.getValue(), nodeType, serviceTemplate, toscaServiceModel)) {
- nodeTemplates.put(nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue());
- }
-
- }
- }
- return nodeTemplates;
- }
-
- @Override
- public Optional<NodeType> fetchNodeType(String nodeTypeKey, Collection<ServiceTemplate>
- serviceTemplates) {
- Optional<Map<String, NodeType>> nodeTypeMap = serviceTemplates.stream()
- .map(ServiceTemplate::getNode_types)
- .filter(nodeTypes -> Objects.nonNull(nodeTypes) && nodeTypes.containsKey(nodeTypeKey))
- .findFirst();
- return nodeTypeMap.map(stringNodeTypeMap -> stringNodeTypeMap.get(nodeTypeKey));
- }
-
- @Override
- public boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
- return isTypeOf(nodeTemplate, nodeType, GET_NODE_TYPE_METHOD_NAME, serviceTemplate,
- toscaServiceModel);
- }
-
- @Override
- public List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate,
- String requirementId) {
- List<RequirementAssignment> requirements = new ArrayList<>();
- List<Map<String, RequirementAssignment>> requirementList = nodeTemplate.getRequirements();
- if (requirementList != null) {
- requirementList.stream().filter(reqMap -> reqMap.get(requirementId) != null)
- .forEach(reqMap -> {
+ @Override
+ public boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, String capability,
+ String node, String relationship) {
+ if (isSameCapability(requirementAssignment, capability)) {
+ return false;
+ }
+
+ if (isSameRequirement(requirementAssignment, node)) {
+ return false;
+ }
+
+ if (isSameRelationship(requirementAssignment, relationship)) {
+ return false;
+ }
+
+ return !(capability == null && node == null && relationship == null);
+
+ }
+
+ private boolean isSameRelationship(RequirementAssignment requirementAssignment, String relationship) {
+ return relationship != null && (requirementAssignment.getRelationship() == null || !requirementAssignment
+ .getRelationship()
+ .equals(relationship));
+ }
+
+ private boolean isSameRequirement(RequirementAssignment requirementAssignment, String node) {
+ return node != null && (requirementAssignment.getNode() == null || !requirementAssignment.getNode()
+ .equals(node));
+ }
+
+ private boolean isSameCapability(RequirementAssignment requirementAssignment, String capability) {
+ return capability != null && (requirementAssignment.getCapability() == null || !requirementAssignment
+ .getCapability()
+ .equals(capability));
+ }
+
+ @Override
+ public ToscaFlatData getFlatEntity(ToscaElementTypes elementType, String typeId, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaModel) {
+ ToscaFlatData flatData = new ToscaFlatData();
+ flatData.setElementType(elementType);
+
+ switch (elementType) {
+ case CAPABILITY_TYPE:
+ flatData.setFlatEntity(new CapabilityType());
+ break;
+ case NODE_TYPE:
+ flatData.setFlatEntity(new NodeType());
+ break;
+ case DATA_TYPE:
+ flatData.setFlatEntity(new DataType());
+ break;
+ default:
+ throw new RuntimeException("Entity[" + elementType + "] id[" + typeId + "] flat not supported");
+ }
+
+ boolean isEntityFound =
+ scanAnFlatEntity(elementType, typeId, flatData, serviceTemplate, toscaModel, new ArrayList<>(), 0);
+ if (!isEntityFound) {
+ throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build());
+ }
+
+ return flatData;
+ }
+
+ @Override
+ public boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate) {
+ return nodeTemplate.getDirectives() != null && nodeTemplate.getDirectives().contains(
+ ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
+ }
+
+ private <T> Optional<Boolean> isTypeExistInServiceTemplateHierarchy(String typeToMatch, String typeToSearch,
+ String getTypesMethodName,
+ ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel,
+ Set<String> analyzedImportFiles)
+ throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ Map<String, T> searchableTypes =
+ (Map<String, T>) serviceTemplate.getClass().getMethod(getTypesMethodName).invoke(serviceTemplate);
+
+ if (!MapUtils.isEmpty(searchableTypes)) {
+ T typeObject = searchableTypes.get(typeToSearch);
+ if (Objects.nonNull(typeObject)) {
+ String derivedFromTypeVal =
+ (String) typeObject.getClass().getMethod(GET_DERIVED_FROM_METHOD_NAME).invoke(typeObject);
+ if (Objects.equals(derivedFromTypeVal, typeToMatch)) {
+ return Optional.of(true);
+ } else if (Objects.isNull(derivedFromTypeVal) || isTypeIsToscaRoot(derivedFromTypeVal)) {
+ return Optional.of(false);
+ } else {
+ return isTypeExistInServiceTemplateHierarchy(typeToMatch, derivedFromTypeVal, getTypesMethodName,
+ serviceTemplate, toscaServiceModel, null);
+ }
+ } else {
+ return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate,
+ toscaServiceModel, analyzedImportFiles);
+ }
+ }
+ return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate, toscaServiceModel,
+ analyzedImportFiles);
+ }
+
+ private Optional<Boolean> isTypeExistInImports(String typeToMatch, String typeToSearch, String getTypesMethodName,
+ ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel, Set<String> filesScanned)
+ throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+ List<Map<String, Import>> imports = serviceTemplate.getImports();
+ if (CollectionUtils.isEmpty(imports)) {
+ return Optional.empty();
+ }
+
+ Set<String> createdFilesScanned = createFilesScannedSet(filesScanned);
+
+ for (Map<String, Import> map : imports) {
ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- RequirementAssignment reqAssignment = toscaExtensionYamlUtil
- .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqMap.get(requirementId)),
- RequirementAssignment.class);
- requirements.add(reqAssignment);
- });
- }
- return requirements;
- }
-
- @Override
- public Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate,
- String nodeTemplateId) {
- if ((serviceTemplate.getTopology_template() != null)
- && (serviceTemplate.getTopology_template().getNode_templates() != null)
- && (serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId)
- != null)) {
- return Optional
- .of(serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId));
- }
- return Optional.empty();
- }
-
- @Override
- public Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId,
- NodeTemplate substitutableNodeTemplate) {
- if (!isSubstitutableNodeTemplate(substitutableNodeTemplate)) {
- return Optional.empty();
- }
-
- if (substitutableNodeTemplate.getProperties() != null
- && substitutableNodeTemplate.getProperties()
- .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) != null) {
- Object serviceTemplateFilter = substitutableNodeTemplate.getProperties()
- .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
- if (serviceTemplateFilter != null && serviceTemplateFilter instanceof Map) {
- Object substituteServiceTemplate = ((Map) serviceTemplateFilter)
- .get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
- handleNoSubstituteServiceTemplate(substituteNodeTemplateId, substituteServiceTemplate);
- return Optional.of(substituteServiceTemplate.toString());
- }
- }
- throw new CoreException(
- new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId)
- .build());
- }
-
- private void handleNoSubstituteServiceTemplate(String substituteNodeTemplateId,
- Object substituteServiceTemplate) {
- if (substituteServiceTemplate == null) {
- throw new CoreException(
- new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId)
- .build());
- }
- }
-
- @Override
- public Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate) {
- Map<String, NodeTemplate> substitutableNodeTemplates = new HashMap<>();
-
- if (serviceTemplate == null
- || serviceTemplate.getTopology_template() == null
- || serviceTemplate.getTopology_template().getNode_templates() == null) {
- return substitutableNodeTemplates;
- }
-
- Map<String, NodeTemplate> nodeTemplates =
- serviceTemplate.getTopology_template().getNode_templates();
- for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
- String nodeTemplateId = entry.getKey();
- NodeTemplate nodeTemplate = entry.getValue();
- if (isSubstitutableNodeTemplate(nodeTemplate)) {
- substitutableNodeTemplates.put(nodeTemplateId, nodeTemplate);
- }
- }
-
- return substitutableNodeTemplates;
- }
-
- @Override
- public Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq(
- String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate,
- String requirementId) {
- if (isSubstitutionServiceTemplate(substituteServiceTemplateFileName,
- substituteServiceTemplate)) {
- Map<String, List<String>> substitutionMappingRequirements =
- substituteServiceTemplate.getTopology_template().getSubstitution_mappings()
- .getRequirements();
- if (substitutionMappingRequirements != null) {
- List<String> requirementMapping = substitutionMappingRequirements.get(requirementId);
- if (requirementMapping != null && !requirementMapping.isEmpty()) {
- String mappedNodeTemplateId = requirementMapping.get(0);
- Optional<NodeTemplate> mappedNodeTemplate =
- getNodeTemplateById(substituteServiceTemplate, mappedNodeTemplateId);
- mappedNodeTemplate.orElseThrow(() -> new CoreException(
- new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", mappedNodeTemplateId)
- .build()));
- Map.Entry<String, NodeTemplate> mappedNodeTemplateEntry =
- new Map.Entry<String, NodeTemplate>() {
- @Override
- public String getKey() {
- return mappedNodeTemplateId;
+ Import anImport = toscaExtensionYamlUtil
+ .yamlToObject(toscaExtensionYamlUtil.objectToYaml(map.values().iterator().next()),
+ Import.class);
+ handleImportWithNoFileEntry(anImport);
+ String importFile = anImport.getFile();
+ ServiceTemplate template = toscaServiceModel.getServiceTemplates().get(fetchFileNameForImport(importFile,
+ serviceTemplate.getMetadata() == null ? null : serviceTemplate.getMetadata().get("filename")));
+ if (Objects.isNull(template) || createdFilesScanned
+ .contains(ToscaUtil.getServiceTemplateFileName(template))) {
+ continue;
+ } else {
+ createdFilesScanned.add(ToscaUtil.getServiceTemplateFileName(template));
+ }
+ Optional<Boolean> typeExistInServiceTemplateHierarchy =
+ isTypeExistInServiceTemplateHierarchy(typeToMatch, typeToSearch, getTypesMethodName, template,
+ toscaServiceModel, createdFilesScanned);
+ if (typeExistInServiceTemplateHierarchy.isPresent() && (typeExistInServiceTemplateHierarchy.get())) {
+ createdFilesScanned.clear();
+ return Optional.of(true);
+ }
+
+ }
+ return Optional.of(false);
+ }
+
+ private void handleImportWithNoFileEntry(Import anImport) {
+ if (Objects.isNull(anImport) || Objects.isNull(anImport.getFile())) {
+ throw new RuntimeException("import without file entry");
+ }
+ }
+
+ private Set<String> createFilesScannedSet(Set<String> filesScanned) {
+ Set<String> retFileScanned = filesScanned;
+ if (Objects.isNull(retFileScanned)) {
+ retFileScanned = new HashSet<>();
+ }
+ return retFileScanned;
+ }
+
+ private boolean isTypeIsToscaRoot(String type) {
+ return (type.contains(TOSCA_DOT) && type.contains(DOT_ROOT));
+ }
+
+ private boolean isSubstitutionServiceTemplate(String substituteServiceTemplateFileName,
+ ServiceTemplate substituteServiceTemplate) {
+ if (substituteServiceTemplate != null && substituteServiceTemplate.getTopology_template() != null
+ && substituteServiceTemplate.getTopology_template().getSubstitution_mappings() != null) {
+ if (substituteServiceTemplate.getTopology_template().getSubstitution_mappings().getNode_type() == null) {
+ throw new CoreException(new ToscaInvalidSubstitutionServiceTemplateErrorBuilder(substituteServiceTemplateFileName)
+ .build());
+ }
+ return true;
+ }
+ return false;
+
+ }
+
+ private boolean scanAnFlatEntity(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData,
+ ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
+ List<String> filesScanned, int rootScanStartInx) {
+
+
+ boolean entityFound =
+ enrichEntityFromCurrentServiceTemplate(elementType, typeId, flatData, serviceTemplate, toscaModel,
+ filesScanned, rootScanStartInx);
+ if (!entityFound) {
+ List<Map<String, Import>> imports = serviceTemplate.getImports();
+ if (CollectionUtils.isEmpty(imports)) {
+ return false;
+ }
+ boolean found = false;
+ for (Map<String, Import> importMap : imports) {
+ if (found) {
+ return true;
}
+ found = isFlatEntity(importMap, flatData, serviceTemplate, filesScanned, toscaModel, elementType,
+ typeId);
+ }
+ return found;
+ }
+ return true;
+ }
- @Override
- public NodeTemplate getValue() {
- return mappedNodeTemplate.get();
+ private boolean isFlatEntity(Map<String, Import> importMap, ToscaFlatData flatData, ServiceTemplate serviceTemplate,
+ List<String> filesScanned, ToscaServiceModel toscaModel,
+ ToscaElementTypes elementType, String typeId) {
+ boolean found = false;
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ for (Object importObject : importMap.values()) {
+ Import importServiceTemplate = toscaExtensionYamlUtil
+ .yamlToObject(toscaExtensionYamlUtil.objectToYaml(importObject),
+ Import.class);
+ String fileName = fetchFileNameForImport(importServiceTemplate.getFile(),
+ serviceTemplate.getMetadata() == null ? null : serviceTemplate.getMetadata().get("filename"));
+ if (filesScanned.contains(fileName)) {
+ return false;
+ } else {
+ filesScanned.add(fileName);
+ }
+ ServiceTemplate template = toscaModel.getServiceTemplates().get(fileName);
+ if (Objects.isNull(template)) {
+ throw new CoreException(new ToscaFileNotFoundErrorBuilder(fileName).build());
+ }
+ found = scanAnFlatEntity(elementType, typeId, flatData, template, toscaModel, filesScanned,
+ filesScanned.size());
+ }
+ return found;
+ }
+
+ private String fetchFileNameForImport(String importServiceTemplateFile, String currentMetadatafileName) {
+ if (importServiceTemplateFile.contains("../")) {
+ return importServiceTemplateFile.replace("../", "");
+ } else if (currentMetadatafileName != null && currentMetadatafileName.indexOf('/') != -1) {
+ return currentMetadatafileName.substring(0, currentMetadatafileName.indexOf('/')) + "/"
+ + importServiceTemplateFile;
+ } else {
+ return importServiceTemplateFile;
+ }
+
+ }
+
+ private boolean enrichEntityFromCurrentServiceTemplate(ToscaElementTypes elementType, String typeId,
+ ToscaFlatData flatData,
+ ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaModel,
+ List<String> filesScanned, int rootScanStartInx) {
+ switch (elementType) {
+ case CAPABILITY_TYPE:
+ if (enrichCapabilityType(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned,
+ rootScanStartInx)) {
+ return false;
+ }
+ break;
+ case NODE_TYPE:
+ if (enrichNodeTypeInfo(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned,
+ rootScanStartInx)) {
+ return false;
+ }
+ break;
+ case DATA_TYPE:
+ if (enrichDataTypeInfo(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned,
+ rootScanStartInx)) {
+ return false;
}
+ break;
+ default:
+ throw new RuntimeException("Entity[" + elementType + "] id[" + typeId + "] flat not supported");
+ }
+
+ return true;
+
+
+ }
+
+ private boolean enrichNodeTypeInfo(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData,
+ ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
+ List<String> filesScanned, int rootScanStartInx) {
+ String derivedFrom;
+ if (serviceTemplate.getNode_types() != null && serviceTemplate.getNode_types().containsKey(typeId)) {
- @Override
- public NodeTemplate setValue(NodeTemplate value) {
- return null;
+ filesScanned.clear();
+ flatData.addInheritanceHierarchyType(typeId);
+ NodeType targetNodeType = (NodeType) flatData.getFlatEntity();
+ NodeType sourceNodeType = serviceTemplate.getNode_types().get(typeId);
+ derivedFrom = sourceNodeType.getDerived_from();
+ if (derivedFrom != null) {
+ boolean isEntityFound =
+ scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned,
+ rootScanStartInx);
+ if (!isEntityFound) {
+ throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build());
}
- };
- return Optional.of(mappedNodeTemplateEntry);
+ }
+ combineNodeTypeInfo(sourceNodeType, targetNodeType);
+ } else {
+ return true;
}
- }
+ return false;
}
- return Optional.empty();
- }
- /*
- match only for the input which is not null
- */
- @Override
- public boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment,
- String capability, String node,
- String relationship) {
- if (isSameCapability(requirementAssignment, capability)) {
- return false;
- }
-
- if (isSameRequirement(requirementAssignment, node)) {
- return false;
- }
-
- if (isSameRelationship(requirementAssignment, relationship)) {
- return false;
- }
-
- return !(capability == null && node == null && relationship == null);
-
- }
-
- private boolean isSameRelationship(RequirementAssignment requirementAssignment,
- String relationship) {
- return relationship != null && (requirementAssignment.getRelationship() == null
- || !requirementAssignment.getRelationship().equals(relationship));
- }
-
- private boolean isSameRequirement(RequirementAssignment requirementAssignment, String node) {
- return node != null && (requirementAssignment.getNode() == null
- || !requirementAssignment.getNode().equals(node));
- }
-
- private boolean isSameCapability(RequirementAssignment requirementAssignment, String capability) {
- return capability != null && (requirementAssignment.getCapability() == null
- || !requirementAssignment.getCapability().equals(capability));
- }
-
- @Override
- public Object getFlatEntity(ToscaElementTypes elementType, String typeId,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel) {
- Object returnEntity;
-
- switch (elementType) {
- case CAPABILITY_TYPE:
- returnEntity = new CapabilityType();
- break;
- case NODE_TYPE:
- returnEntity = new NodeType();
- break;
- case DATA_TYPE:
- returnEntity = new DataType();
- break;
- default:
- throw new RuntimeException(
- "Entity[" + elementType + "] id[" + typeId + "] flat not supported");
- }
-
- boolean isEntityFound =
- scanAnFlatEntity(elementType, typeId, returnEntity, serviceTemplate, toscaModel,
- new ArrayList<>(), 0);
- if (!isEntityFound) {
- throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build());
- }
-
- return returnEntity;
- }
-
- @Override
- public boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate) {
- return nodeTemplate.getDirectives() != null
- && nodeTemplate.getDirectives().contains(ToscaConstants
- .NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
- }
-
- private <T> Optional<Boolean> isTypeExistInServiceTemplateHierarchy(String typeToMatch,
- String typeToSearch,
- String getTypesMethodName,
- ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaServiceModel,
- Set<String> analyzedImportFiles)
- throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- Map<String, T> searchableTypes =
- (Map<String, T>) serviceTemplate.getClass().getMethod(getTypesMethodName)
- .invoke(serviceTemplate);
-
- if (!MapUtils.isEmpty(searchableTypes)) {
- T typeObject = searchableTypes.get(typeToSearch);
- if (Objects.nonNull(typeObject)) {
- String derivedFromTypeVal =
- (String) typeObject.getClass().getMethod(GET_DERIVED_FROM_METHOD_NAME).invoke(typeObject);
- if (Objects.equals(derivedFromTypeVal, typeToMatch)) {
- return Optional.of(true);
- } else if (Objects.isNull(derivedFromTypeVal) || isTypeIsToscaRoot(derivedFromTypeVal)) {
- return Optional.of(false);
+ private boolean enrichDataTypeInfo(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData,
+ ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
+ List<String> filesScanned, int rootScanStartInx) {
+ String derivedFrom;
+ if (serviceTemplate.getData_types() != null && serviceTemplate.getData_types().containsKey(typeId)) {
+
+ filesScanned.clear();
+ flatData.addInheritanceHierarchyType(typeId);
+ DataType targetDataType = (DataType) flatData.getFlatEntity();
+ DataType sourceDataType = serviceTemplate.getData_types().get(typeId);
+ derivedFrom = sourceDataType.getDerived_from();
+ if (derivedFrom != null) {
+ boolean isEntityFound =
+ scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned,
+ rootScanStartInx);
+ if (!isEntityFound) {
+ throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build());
+ }
+ }
+ combineDataTypeInfo(sourceDataType, targetDataType);
} else {
- return isTypeExistInServiceTemplateHierarchy(typeToMatch,
- derivedFromTypeVal, getTypesMethodName, serviceTemplate, toscaServiceModel, null);
- }
- } else {
- return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName,
- serviceTemplate, toscaServiceModel, analyzedImportFiles);
- }
- }
- return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate,
- toscaServiceModel, analyzedImportFiles);
- }
-
- private Optional<Boolean> isTypeExistInImports(String typeToMatch,
- String typeToSearch,
- String getTypesMethodName,
- ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaServiceModel,
- Set<String> filesScanned)
- throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
- List<Map<String, Import>> imports = serviceTemplate.getImports();
- if (CollectionUtils.isEmpty(imports)) {
- return Optional.empty();
- }
-
- Set<String> createdFilesScanned = createFilesScannedSet(filesScanned);
-
- for (Map<String, Import> map : imports) {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- Import anImport = toscaExtensionYamlUtil
- .yamlToObject(toscaExtensionYamlUtil.objectToYaml(map.values().iterator().next()),
- Import.class);
- handleImportWithNoFileEntry(anImport);
- String importFile = anImport.getFile();
- ServiceTemplate template =
- toscaServiceModel.getServiceTemplates().get(fetchFileNameForImport(importFile,
- serviceTemplate.getMetadata() == null ? null
- : serviceTemplate.getMetadata().get("filename")));
- if (Objects.isNull(template)
- || createdFilesScanned.contains(ToscaUtil.getServiceTemplateFileName(template))) {
- continue;
- } else {
- createdFilesScanned.add(ToscaUtil.getServiceTemplateFileName(template));
- }
- Optional<Boolean> typeExistInServiceTemplateHierarchy =
- isTypeExistInServiceTemplateHierarchy(typeToMatch, typeToSearch, getTypesMethodName,
- template, toscaServiceModel, createdFilesScanned);
- if (typeExistInServiceTemplateHierarchy.isPresent()
- && (typeExistInServiceTemplateHierarchy.get())) {
- createdFilesScanned.clear();
- return Optional.of(true);
- }
-
- }
- return Optional.of(false);
- }
-
- private void handleImportWithNoFileEntry(Import anImport) {
- if (Objects.isNull(anImport) || Objects.isNull(anImport.getFile())) {
- throw new RuntimeException("import without file entry");
- }
- }
-
- private Set<String> createFilesScannedSet(Set<String> filesScanned) {
- Set<String> retFileScanned = filesScanned;
- if (Objects.isNull(retFileScanned)) {
- retFileScanned = new HashSet<>();
- }
- return retFileScanned;
- }
-
- private boolean isTypeIsToscaRoot(String type) {
- return (type.contains(TOSCA_DOT) && type.contains(DOT_ROOT));
- }
-
- private boolean isSubstitutionServiceTemplate(String substituteServiceTemplateFileName,
- ServiceTemplate substituteServiceTemplate) {
- if (substituteServiceTemplate != null
- && substituteServiceTemplate.getTopology_template() != null
- && substituteServiceTemplate.getTopology_template().getSubstitution_mappings() != null) {
- if (substituteServiceTemplate.getTopology_template().getSubstitution_mappings()
- .getNode_type() == null) {
- throw new CoreException(new ToscaInvalidSubstitutionServiceTemplateErrorBuilder(
- substituteServiceTemplateFileName).build());
- }
- return true;
- }
- return false;
-
- }
-
- private boolean scanAnFlatEntity(ToscaElementTypes elementType, String typeId, Object entity,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
- List<String> filesScanned, int rootScanStartInx) {
-
-
- boolean entityFound = enrichEntityFromCurrentServiceTemplate(elementType, typeId, entity,
- serviceTemplate, toscaModel, filesScanned, rootScanStartInx);
- if (!entityFound) {
- List<Map<String, Import>> imports = serviceTemplate.getImports();
- if (CollectionUtils.isEmpty(imports)) {
+ return true;
+ }
return false;
- }
- boolean found = false;
- for (Map<String, Import> importMap : imports) {
- if (found) {
- return true;
- }
- found = isFlatEntity(importMap, entity, serviceTemplate, filesScanned,
- toscaModel, elementType, typeId);
- }
- return found;
- }
- return true;
- }
-
- private boolean isFlatEntity(Map<String, Import> importMap,
- Object entity,
- ServiceTemplate serviceTemplate,
- List<String> filesScanned,
- ToscaServiceModel toscaModel,
- ToscaElementTypes elementType, String typeId) {
- boolean found = false;
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- for (Object importObject : importMap.values()) {
- Import importServiceTemplate = toscaExtensionYamlUtil
- .yamlToObject(toscaExtensionYamlUtil.objectToYaml(importObject), Import.class);
- String fileName = fetchFileNameForImport(importServiceTemplate.getFile(),
- serviceTemplate.getMetadata() == null ? null : serviceTemplate.getMetadata().get(
- "filename"));
- if (filesScanned.contains(fileName)) {
+ }
+
+ private boolean enrichCapabilityType(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData,
+ ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
+ List<String> filesScanned, int rootScanStartInx) {
+ String derivedFrom;
+ if (serviceTemplate.getCapability_types() != null && serviceTemplate.getCapability_types()
+ .containsKey(typeId)) {
+
+ filesScanned.clear();
+ flatData.addInheritanceHierarchyType(typeId);
+ CapabilityType targetCapabilityType = (CapabilityType) flatData.getFlatEntity();
+ CapabilityType sourceCapabilityType = serviceTemplate.getCapability_types().get(typeId);
+ derivedFrom = sourceCapabilityType.getDerived_from();
+ if (derivedFrom != null) {
+ boolean isEntityFound =
+ scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned,
+ rootScanStartInx);
+ if (!isEntityFound) {
+ throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build());
+ }
+ }
+ combineCapabilityTypeInfo(sourceCapabilityType, targetCapabilityType);
+ } else {
+ return true;
+ }
return false;
- } else {
- filesScanned.add(fileName);
- }
- ServiceTemplate template = toscaModel.getServiceTemplates().get(fileName);
- if (Objects.isNull(template)) {
- throw new CoreException(
- new ToscaFileNotFoundErrorBuilder(fileName).build());
- }
- found = scanAnFlatEntity(elementType, typeId, entity, template, toscaModel,
- filesScanned, filesScanned.size());
- }
- return found;
- }
-
- private String fetchFileNameForImport(String importServiceTemplateFile,
- String currentMetadatafileName) {
- if (importServiceTemplateFile.contains("../")) {
- return importServiceTemplateFile.replace("../", "");
- } else if (currentMetadatafileName != null) {
- return currentMetadatafileName.substring(0, currentMetadatafileName.indexOf('/')) + "/"
- + importServiceTemplateFile;
- } else {
- return importServiceTemplateFile;
- }
-
- }
-
- private boolean enrichEntityFromCurrentServiceTemplate(ToscaElementTypes elementType,
- String typeId, Object entity,
- ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaModel,
- List<String> filesScanned,
- int rootScanStartInx) {
- switch (elementType) {
- case CAPABILITY_TYPE:
- if (enrichCapabilityType(elementType, typeId, entity, serviceTemplate, toscaModel,
- filesScanned, rootScanStartInx)) {
- return false;
- }
- break;
- case NODE_TYPE:
- if (enrichNodeTypeInfo(elementType, typeId, entity, serviceTemplate, toscaModel,
- filesScanned, rootScanStartInx)) {
- return false;
- }
- break;
- case DATA_TYPE:
- if (enrichDataTypeInfo(elementType, typeId, entity, serviceTemplate, toscaModel,
- filesScanned, rootScanStartInx)) {
- return false;
- }
- break;
- default:
- throw new RuntimeException(
- "Entity[" + elementType + "] id[" + typeId + "] flat not supported");
- }
-
- return true;
-
-
- }
-
- private boolean enrichNodeTypeInfo(ToscaElementTypes elementType, String typeId, Object entity,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
- List<String> filesScanned, int rootScanStartInx) {
- String derivedFrom;
- if (serviceTemplate.getNode_types() != null
- && serviceTemplate.getNode_types().containsKey(typeId)) {
-
- filesScanned.clear();
- NodeType targetNodeType = (NodeType) entity;
- NodeType sourceNodeType = serviceTemplate.getNode_types().get(typeId);
- derivedFrom = sourceNodeType.getDerived_from();
- if (derivedFrom != null) {
- scanAnFlatEntity(elementType, derivedFrom, entity, serviceTemplate, toscaModel,
- filesScanned, rootScanStartInx);
- }
- combineNodeTypeInfo(sourceNodeType, targetNodeType);
- } else {
- return true;
- }
- return false;
- }
-
- private boolean enrichDataTypeInfo(ToscaElementTypes elementType, String typeId, Object entity,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel,
- List<String> filesScanned, int rootScanStartInx) {
- String derivedFrom;
- if (serviceTemplate.getData_types() != null
- && serviceTemplate.getData_types().containsKey(typeId)) {
-
- filesScanned.clear();
- DataType targetDataType = (DataType) entity;
- DataType sourceDataType = serviceTemplate.getData_types().get(typeId);
- derivedFrom = sourceDataType.getDerived_from();
- if (derivedFrom != null) {
- scanAnFlatEntity(elementType, derivedFrom, entity, serviceTemplate, toscaModel,
- filesScanned, rootScanStartInx);
- }
- combineDataTypeInfo(sourceDataType, targetDataType);
- } else {
- return true;
- }
- return false;
- }
-
- private boolean enrichCapabilityType(ToscaElementTypes elementType, String typeId, Object entity,
- ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaModel, List<String> filesScanned,
- int rootScanStartInx) {
- String derivedFrom;
- if (serviceTemplate.getCapability_types() != null
- && serviceTemplate.getCapability_types().containsKey(typeId)) {
-
- filesScanned.clear();
- CapabilityType targetCapabilityType = (CapabilityType) entity;
- CapabilityType sourceCapabilityType = serviceTemplate.getCapability_types().get(typeId);
- derivedFrom = sourceCapabilityType.getDerived_from();
- if (derivedFrom != null) {
- scanAnFlatEntity(elementType, derivedFrom, entity, serviceTemplate, toscaModel,
- filesScanned, rootScanStartInx);
- }
- combineCapabilityTypeInfo(sourceCapabilityType, targetCapabilityType);
- } else {
- return true;
- }
- return false;
- }
-
- private void combineNodeTypeInfo(NodeType sourceNodeType, NodeType targetNodeType) {
- targetNodeType.setDerived_from(sourceNodeType.getDerived_from());
- targetNodeType.setDescription(sourceNodeType.getDescription());
- targetNodeType.setVersion(sourceNodeType.getVersion());
- targetNodeType.setProperties(
- CommonMethods.mergeMaps(targetNodeType.getProperties(), sourceNodeType.getProperties()));
- targetNodeType.setInterfaces(
- CommonMethods.mergeMaps(targetNodeType.getInterfaces(), sourceNodeType.getInterfaces()));
- targetNodeType.setArtifacts(
- CommonMethods.mergeMaps(targetNodeType.getArtifacts(), sourceNodeType.getArtifacts()));
- targetNodeType.setAttributes(
- CommonMethods.mergeMaps(targetNodeType.getAttributes(), sourceNodeType.getAttributes()));
- targetNodeType.setCapabilities(CommonMethods
- .mergeMaps(targetNodeType.getCapabilities(), sourceNodeType.getCapabilities()));
- targetNodeType.setRequirements(CommonMethods
- .mergeListsOfMap(targetNodeType.getRequirements(), sourceNodeType.getRequirements()));
-
- }
-
- private void combineDataTypeInfo(DataType sourceDataType, DataType targetDataType) {
- targetDataType.setDerived_from(sourceDataType.getDerived_from());
- targetDataType.setDescription(sourceDataType.getDescription());
- targetDataType.setVersion(sourceDataType.getVersion());
- targetDataType.setProperties(
- CommonMethods.mergeMaps(targetDataType.getProperties(), sourceDataType.getProperties()));
- targetDataType.setConstraints(
- CommonMethods.mergeLists(targetDataType.getConstraints(), sourceDataType.getConstraints()));
- }
-
-
- private void combineCapabilityTypeInfo(CapabilityType sourceCapabilityType,
- CapabilityType targetCapabilityType) {
-
- targetCapabilityType.setAttributes(CommonMethods
- .mergeMaps(targetCapabilityType.getAttributes(), sourceCapabilityType.getAttributes()));
- targetCapabilityType.setProperties(CommonMethods
- .mergeMaps(targetCapabilityType.getProperties(), sourceCapabilityType.getProperties()));
- targetCapabilityType.setValid_source_types(CommonMethods
- .mergeLists(targetCapabilityType.getValid_source_types(),
- sourceCapabilityType.getValid_source_types()));
-
- if (StringUtils.isNotEmpty(sourceCapabilityType.getDerived_from())) {
- targetCapabilityType.setDerived_from(sourceCapabilityType.getDerived_from());
- }
- if (StringUtils.isNotEmpty(sourceCapabilityType.getDescription())) {
- targetCapabilityType.setDescription(sourceCapabilityType.getDescription());
- }
- if (StringUtils.isNotEmpty(sourceCapabilityType.getVersion())) {
- targetCapabilityType.setVersion(sourceCapabilityType.getVersion());
- }
-
-
- }
-
-
- /*
- * Create node type according to the input substitution service template, while the substitution
- * service template can be mappted to this node type, for substitution mapping.
- *
- * @param substitutionServiceTemplate substitution serivce template
- * @param nodeTypeDerivedFromValue derived from value for the created node type
- * @return the node type
- */
- @Override
- public NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate,
- String nodeTypeDerivedFromValue) {
- NodeType substitutionNodeType = new NodeType();
- substitutionNodeType.setDerived_from(nodeTypeDerivedFromValue);
- substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
- substitutionNodeType
- .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
- substitutionNodeType
- .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
- return substitutionNodeType;
- }
-
- @Override
- public Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
- ServiceTemplate substitutionServiceTemplate) {
- Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
- Map<String, ParameterDefinition> properties =
- substitutionServiceTemplate.getTopology_template().getInputs();
- if (properties == null) {
- return null;
- }
-
- PropertyDefinition propertyDefinition;
- String toscaPropertyName;
- for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
- toscaPropertyName = entry.getKey();
- propertyDefinition = new PropertyDefinition();
- ParameterDefinition parameterDefinition =
- substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
- propertyDefinition.setType(parameterDefinition.getType());
- propertyDefinition.setDescription(parameterDefinition.getDescription());
- propertyDefinition.set_default(parameterDefinition.get_default());
- if (parameterDefinition.getRequired() != null) {
- propertyDefinition.setRequired(parameterDefinition.getRequired());
- }
- if (propertyDefinition.get_default() != null) {
- propertyDefinition.setRequired(false);
- }
- if (!CollectionUtils.isEmpty(parameterDefinition.getConstraints())) {
- propertyDefinition.setConstraints(parameterDefinition.getConstraints());
- }
- propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
- if (parameterDefinition.getStatus() != null) {
- propertyDefinition.setStatus(parameterDefinition.getStatus());
- }
- substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
- }
- return substitutionNodeTypeProperties;
- }
-
-
- private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
- ServiceTemplate substitutionServiceTemplate) {
- Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
- Map<String, ParameterDefinition> attributes =
- substitutionServiceTemplate.getTopology_template().getOutputs();
- if (attributes == null) {
- return null;
- }
- AttributeDefinition attributeDefinition;
- String toscaAttributeName;
-
- for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
- attributeDefinition = new AttributeDefinition();
- toscaAttributeName = entry.getKey();
- ParameterDefinition parameterDefinition =
- substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
- if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
- attributeDefinition.setType(parameterDefinition.getType());
- } else {
- attributeDefinition.setType(PropertyType.STRING.getDisplayName());
- }
- attributeDefinition.setDescription(parameterDefinition.getDescription());
- attributeDefinition.set_default(parameterDefinition.get_default());
- attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
- if (Objects.nonNull(parameterDefinition.getStatus())) {
- attributeDefinition.setStatus(parameterDefinition.getStatus());
- }
- substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
- }
- return substitutionNodeTypeAttributes;
- }
-
- /**
- * Checks if the requirement exists in the node template.
+ }
+
+ private void combineNodeTypeInfo(NodeType sourceNodeType, NodeType targetNodeType) {
+ targetNodeType.setDerived_from(sourceNodeType.getDerived_from());
+ targetNodeType.setDescription(sourceNodeType.getDescription());
+ targetNodeType.setVersion(sourceNodeType.getVersion());
+ targetNodeType
+ .setProperties(CommonMethods.mergeMaps(targetNodeType.getProperties(), sourceNodeType.getProperties()));
+ combineNodeTypeInterfaceInfo(sourceNodeType, targetNodeType);
+ targetNodeType
+ .setArtifacts(CommonMethods.mergeMaps(targetNodeType.getArtifacts(), sourceNodeType.getArtifacts()));
+ targetNodeType
+ .setAttributes(CommonMethods.mergeMaps(targetNodeType.getAttributes(), sourceNodeType.getAttributes()));
+ targetNodeType.setCapabilities(
+ CommonMethods.mergeMaps(targetNodeType.getCapabilities(), sourceNodeType.getCapabilities()));
+ targetNodeType.setRequirements(
+ CommonMethods.mergeListsOfMap(targetNodeType.getRequirements(), sourceNodeType.getRequirements()));
+
+ }
+
+ private InterfaceDefinitionType getInterfaceDefinitionType(String interfaceName, Object interfaceDefTypeObj) {
+ Optional<InterfaceDefinitionType> interfaceDefinitionType = DataModelUtil.convertObjToInterfaceDefinition(
+ interfaceName, interfaceDefTypeObj, InterfaceDefinitionType.class);
+ if (!interfaceDefinitionType.isPresent()) {
+ throw new CoreException(new CreateInterfaceObjectErrorBuilder("InterfaceDefinitionType", interfaceName,
+ "Invalid interface object").build());
+ }
+ return interfaceDefinitionType.get();
+ }
+
+ private void combineNodeTypeInterfaceInfo(NodeType sourceNodeType, NodeType targetNodeType) {
+ Optional<Map<String, Object>> interfaceNoMerge = combineInterfaceNoMerge(sourceNodeType, targetNodeType);
+ if (interfaceNoMerge.isPresent()) {
+ targetNodeType.setInterfaces(interfaceNoMerge.get());
+ return;
+ }
+ targetNodeType.setInterfaces(combineInterfaces(sourceNodeType, targetNodeType));
+ }
+
+ private Map<String, Object> combineInterfaces(NodeType sourceNodeType, NodeType targetNodeType) {
+ Map<String, Object> combineInterfaces = new HashMap<>();
+ for (Map.Entry<String, Object> sourceInterfaceDefEntry : sourceNodeType.getInterfaces().entrySet()) {
+ String interfaceName = sourceInterfaceDefEntry.getKey();
+ if (!MapUtils.isEmpty(targetNodeType.getInterfaces()) && targetNodeType.getInterfaces()
+ .containsKey(interfaceName)) {
+ combineInterfaces.put(interfaceName,
+ combineInterfaceDefinition(interfaceName, sourceInterfaceDefEntry.getValue(),
+ targetNodeType.getInterfaces().get(interfaceName)));
+ } else {
+ combineInterfaces.put(sourceInterfaceDefEntry.getKey(), sourceInterfaceDefEntry.getValue());
+ }
+ }
+
+ for (Map.Entry<String, Object> targetInterfaceDefEntry : targetNodeType.getInterfaces().entrySet()) {
+ String interfaceName = targetInterfaceDefEntry.getKey();
+ if (!sourceNodeType.getInterfaces().containsKey(interfaceName)) {
+ combineInterfaces.put(targetInterfaceDefEntry.getKey(), targetInterfaceDefEntry.getValue());
+ }
+ }
+
+ return combineInterfaces;
+ }
+
+ private Optional<Map<String, Object>> combineInterfaceNoMerge(NodeType sourceNodeType, NodeType targetNodeType) {
+ if ((MapUtils.isEmpty(sourceNodeType.getInterfaces()) && MapUtils.isEmpty(targetNodeType.getInterfaces()))) {
+ return Optional.empty();
+ }
+
+ if (MapUtils.isEmpty(sourceNodeType.getInterfaces()) && !MapUtils.isEmpty(targetNodeType.getInterfaces())) {
+ return Optional.of(targetNodeType.getInterfaces());
+ }
+
+ if (!MapUtils.isEmpty(sourceNodeType.getInterfaces()) && MapUtils.isEmpty(targetNodeType.getInterfaces())) {
+ return Optional.of(sourceNodeType.getInterfaces());
+ }
+ return Optional.empty();
+
+ }
+
+ private Object combineInterfaceDefinition(String interfaceName, Object sourceInterfaceDefType,
+ Object targetInterfaceDefType) {
+ InterfaceDefinitionType sourceInterface = getInterfaceDefinitionType(interfaceName, sourceInterfaceDefType);
+ InterfaceDefinitionType targetInterface = getInterfaceDefinitionType(interfaceName, targetInterfaceDefType);
+ InterfaceDefinitionType combineInterface = new InterfaceDefinitionType();
+ combineInterface.setType(sourceInterface.getType());
+ combineInterface.setInputs(CommonMethods.mergeMaps(targetInterface.getInputs(), sourceInterface.getInputs()));
+ combineInterface.setOperations(
+ CommonMethods.mergeMaps(targetInterface.getOperations(), sourceInterface.getOperations()));
+
+ return DataModelUtil.convertInterfaceDefinitionTypeToObj(combineInterface).get();
+ }
+
+ private void combineDataTypeInfo(DataType sourceDataType, DataType targetDataType) {
+ targetDataType.setDerived_from(sourceDataType.getDerived_from());
+ targetDataType.setDescription(sourceDataType.getDescription());
+ targetDataType.setVersion(sourceDataType.getVersion());
+ targetDataType
+ .setProperties(CommonMethods.mergeMaps(targetDataType.getProperties(), sourceDataType.getProperties()));
+ targetDataType.setConstraints(
+ CommonMethods.mergeLists(targetDataType.getConstraints(), sourceDataType.getConstraints()));
+ }
+
+
+ private void combineCapabilityTypeInfo(CapabilityType sourceCapabilityType, CapabilityType targetCapabilityType) {
+
+ targetCapabilityType.setAttributes(
+ CommonMethods.mergeMaps(targetCapabilityType.getAttributes(), sourceCapabilityType.getAttributes()));
+ targetCapabilityType.setProperties(
+ CommonMethods.mergeMaps(targetCapabilityType.getProperties(), sourceCapabilityType.getProperties()));
+ targetCapabilityType.setValid_source_types(CommonMethods
+ .mergeLists(targetCapabilityType.getValid_source_types(),
+ sourceCapabilityType.getValid_source_types()));
+
+ if (StringUtils.isNotEmpty(sourceCapabilityType.getDerived_from())) {
+ targetCapabilityType.setDerived_from(sourceCapabilityType.getDerived_from());
+ }
+ if (StringUtils.isNotEmpty(sourceCapabilityType.getDescription())) {
+ targetCapabilityType.setDescription(sourceCapabilityType.getDescription());
+ }
+ if (StringUtils.isNotEmpty(sourceCapabilityType.getVersion())) {
+ targetCapabilityType.setVersion(sourceCapabilityType.getVersion());
+ }
+
+
+ }
+
+
+ /*
+ * Create node type according to the input substitution service template, while the substitution
+ * service template can be mappted to this node type, for substitution mapping.
*
- * @param nodeTemplate the node template
- * @param requirementId the requirement id
- * @param requirementAssignment the requirement assignment
- * @return true if the requirement already exists and false otherwise
+ * @param substitutionServiceTemplate substitution serivce template
+ * @param nodeTypeDerivedFromValue derived from value for the created node type
+ * @return the node type
*/
- @Override
- public boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate,
- String requirementId,
- RequirementAssignment requirementAssignment) {
- List<Map<String, RequirementAssignment>> nodeTemplateRequirements = nodeTemplate
- .getRequirements();
- return nodeTemplateRequirements != null && nodeTemplateRequirements.stream().anyMatch(
- requirement -> requirement.containsKey(requirementId) && DataModelUtil
- .compareRequirementAssignment(requirementAssignment, requirement.get(requirementId)));
- }
-
- @Override
- public boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
- return isTypeOf(interfaceDefinition, interfaceType, GET_INTERFACE_TYPE_METHOD_NAME, serviceTemplate,
- toscaServiceModel);
- }
-
- @Override
- public boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType,
- ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
- return isTypeOf(parameterDefinition, dataType, GET_DATA_TYPE_METHOD_NAME, serviceTemplate,
- toscaServiceModel);
- }
-
- private <T> boolean isTypeOf(T object, String type, String getTypesMethodName,
- ServiceTemplate serviceTemplate,
- ToscaServiceModel toscaServiceModel) {
- if (object == null) {
- return false;
- }
-
- try {
- String objectType = (String) object.getClass().getMethod(GET_TYPE_METHOD_NAME).invoke(object);
- if (Objects.equals(objectType, type)) {
- return true;
- }
+ @Override
+ public NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate,
+ String nodeTypeDerivedFromValue) {
+ NodeType substitutionNodeType = new NodeType();
+ substitutionNodeType.setDerived_from(nodeTypeDerivedFromValue);
+ substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
+ substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
+ substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
+ return substitutionNodeType;
+ }
+
+ @Override
+ public Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) {
+ Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
+ Map<String, ParameterDefinition> properties = substitutionServiceTemplate.getTopology_template().getInputs();
+ if (properties == null) {
+ return null;
+ }
+
+ PropertyDefinition propertyDefinition;
+ String toscaPropertyName;
+ for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
+ toscaPropertyName = entry.getKey();
+ propertyDefinition = new PropertyDefinition();
+ ParameterDefinition parameterDefinition =
+ substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
+ propertyDefinition.setType(parameterDefinition.getType());
+ propertyDefinition.setDescription(parameterDefinition.getDescription());
+ propertyDefinition.set_default(parameterDefinition.get_default());
+ if (parameterDefinition.getRequired() != null) {
+ propertyDefinition.setRequired(parameterDefinition.getRequired());
+ }
+ if (propertyDefinition.get_default() != null) {
+ propertyDefinition.setRequired(false);
+ }
+ if (!CollectionUtils.isEmpty(parameterDefinition.getConstraints())) {
+ propertyDefinition.setConstraints(parameterDefinition.getConstraints());
+ }
+ propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
+ if (parameterDefinition.getStatus() != null) {
+ propertyDefinition.setStatus(parameterDefinition.getStatus());
+ }
+ substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
+ }
+ return substitutionNodeTypeProperties;
+ }
+
+
+ private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) {
+ Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
+ Map<String, ParameterDefinition> attributes = substitutionServiceTemplate.getTopology_template().getOutputs();
+ if (attributes == null) {
+ return null;
+ }
+ AttributeDefinition attributeDefinition;
+ String toscaAttributeName;
+
+ for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
+ attributeDefinition = new AttributeDefinition();
+ toscaAttributeName = entry.getKey();
+ ParameterDefinition parameterDefinition =
+ substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
+ if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
+ attributeDefinition.setType(parameterDefinition.getType());
+ } else {
+ attributeDefinition.setType(PropertyType.STRING.getDisplayName());
+ }
+ attributeDefinition.setDescription(parameterDefinition.getDescription());
+ attributeDefinition.set_default(parameterDefinition.get_default());
+ attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
+ if (Objects.nonNull(parameterDefinition.getStatus())) {
+ attributeDefinition.setStatus(parameterDefinition.getStatus());
+ }
+ substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
+ }
+ return substitutionNodeTypeAttributes;
+ }
- Optional<Boolean> typeExistInServiceTemplateHierarchy =
- isTypeExistInServiceTemplateHierarchy(type, objectType, getTypesMethodName,
- serviceTemplate, toscaServiceModel, null);
- return typeExistInServiceTemplateHierarchy.orElseThrow(() -> new CoreException(
- new ToscaElementTypeNotFoundErrorBuilder(objectType).build()));
+ /**
+ * Checks if the requirement exists in the node template.
+ *
+ * @param nodeTemplate the node template
+ * @param requirementId the requirement id
+ * @param requirementAssignment the requirement assignment
+ * @return true if the requirement already exists and false otherwise
+ */
+ @Override
+ public boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId,
+ RequirementAssignment requirementAssignment) {
+ List<Map<String, RequirementAssignment>> nodeTemplateRequirements = nodeTemplate.getRequirements();
+ return nodeTemplateRequirements != null && nodeTemplateRequirements.stream().anyMatch(
+ requirement -> requirement.containsKey(requirementId) && DataModelUtil.compareRequirementAssignment(
+ requirementAssignment, requirement.get(requirementId)));
+ }
+
+ @Override
+ public boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType,
+ ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
+ return isTypeOf(interfaceDefinition, interfaceType, GET_INTERFACE_TYPE_METHOD_NAME, serviceTemplate,
+ toscaServiceModel);
+ }
- } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
- throw new RuntimeException(e);
+ @Override
+ public boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel) {
+ return isTypeOf(parameterDefinition, dataType, GET_DATA_TYPE_METHOD_NAME, serviceTemplate, toscaServiceModel);
+ }
+
+ private <T> boolean isTypeOf(T object, String type, String getTypesMethodName, ServiceTemplate serviceTemplate,
+ ToscaServiceModel toscaServiceModel) {
+ if (object == null) {
+ return false;
+ }
+
+ try {
+ String objectType = (String) object.getClass().getMethod(GET_TYPE_METHOD_NAME).invoke(object);
+ if (Objects.equals(objectType, type)) {
+ return true;
+ }
+
+ Optional<Boolean> typeExistInServiceTemplateHierarchy =
+ isTypeExistInServiceTemplateHierarchy(type, objectType, getTypesMethodName, serviceTemplate,
+ toscaServiceModel, null);
+ return typeExistInServiceTemplateHierarchy.orElseThrow(
+ () -> new CoreException(new ToscaElementTypeNotFoundErrorBuilder(objectType).build()));
+
+ } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
}
- }
}
+
+
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/DataModelUtilTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/DataModelUtilTest.java
index 419951d684..a009899003 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/DataModelUtilTest.java
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/DataModelUtilTest.java
@@ -20,21 +20,18 @@
package org.openecomp.sdc.tosca.services;
+import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.sdc.tosca.datatypes.model.*;
import org.openecomp.sdc.common.errors.CoreException;
-import org.onap.sdc.tosca.datatypes.model.GroupDefinition;
-import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
-import org.onap.sdc.tosca.datatypes.model.NodeType;
-import org.onap.sdc.tosca.datatypes.model.PolicyDefinition;
-import org.onap.sdc.tosca.datatypes.model.RelationshipTemplate;
-import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
-import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping;
import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Optional;
/**
* @author shiria
@@ -125,4 +122,34 @@ public class DataModelUtilTest {
"Invalid action, can't add 'Group Definition' to 'Service Template', 'Service Template' entity is NULL.");
DataModelUtil.addGroupDefinitionToTopologyTemplate(null, "123", new GroupDefinition());
}
+
+
+ @Test
+ public void testGetRelationshipTemplate(){
+ RelationshipTemplate relationshipTemplate = new RelationshipTemplate();
+ String testingRelationshipType = "testingRelationshipType";
+ relationshipTemplate.setType(testingRelationshipType);
+ TopologyTemplate topologyTemplate = new TopologyTemplate();
+ topologyTemplate.setRelationship_templates(new HashMap<>());
+ String relationId = "rtest";
+ topologyTemplate.getRelationship_templates().put(relationId, relationshipTemplate);
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setTopology_template(topologyTemplate);
+
+ Optional<RelationshipTemplate> relationshipTemplateOut =
+ DataModelUtil.getRelationshipTemplate(serviceTemplate, relationId);
+ Assert.assertNotNull(relationshipTemplateOut);
+ Assert.assertEquals(true,relationshipTemplateOut.isPresent());
+ Assert.assertEquals(testingRelationshipType, relationshipTemplateOut.get().getType());
+ }
+
+ @Test
+ public void testGetEmptyRelationshipTemplate(){
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ String relationId = "rtest";
+ Optional<RelationshipTemplate> relationshipTemplateOut =
+ DataModelUtil.getRelationshipTemplate(serviceTemplate, relationId);
+ Assert.assertNotNull(relationshipTemplateOut);
+ Assert.assertEquals(false,relationshipTemplateOut.isPresent());
+ }
}
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java
index e034fb8565..71647a68a2 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java
@@ -26,18 +26,13 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.sdc.tosca.datatypes.model.OperationDefinitionType;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.tosca.TestUtil;
import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
+import org.openecomp.sdc.tosca.datatypes.ToscaFlatData;
import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
-import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
-import org.onap.sdc.tosca.datatypes.model.DataType;
-import org.onap.sdc.tosca.datatypes.model.DefinitionOfDataType;
-import org.onap.sdc.tosca.datatypes.model.DataType;
-import org.onap.sdc.tosca.datatypes.model.Import;
-import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
-import org.onap.sdc.tosca.datatypes.model.InterfaceType;
import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
import org.onap.sdc.tosca.datatypes.model.NodeType;
import org.onap.sdc.tosca.datatypes.model.ParameterDefinition;
@@ -47,29 +42,33 @@ import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping;
import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
+import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
+import org.onap.sdc.tosca.datatypes.model.Import;
+import org.openecomp.sdc.tosca.services.DataModelUtil;
+import org.onap.sdc.tosca.datatypes.model.InterfaceType;
+import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
+import org.onap.sdc.tosca.datatypes.model.DataType;
import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
import org.openecomp.sdc.tosca.services.ToscaConstants;
-import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
+import org.onap.sdc.tosca.datatypes.model.DefinitionOfDataType;
-import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.io.IOException;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
+import static org.junit.Assert.assertEquals;
+
+import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
-/**
- * @author Avrahamg
- * @since July 14, 2016
- */
@RunWith(MockitoJUnitRunner.class)
public class ToscaAnalyzerServiceImplTest {
/*
@@ -79,774 +78,803 @@ public class ToscaAnalyzerServiceImplTest {
NdTy: NodeType
*/
- private static ToscaAnalyzerService toscaAnalyzerService;
- private static ToscaServiceModel toscaServiceModel;
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Mock
- private NodeTemplate nodeTemplateMock;
- @Mock
- private ParameterDefinition parameterDefinitionMock;
- @Mock
- private PropertyDefinition propertyDefinitionMock;
- @Mock
- private InterfaceDefinitionType interfaceDefinitionMock;
- @Mock
- private ToscaServiceModel toscaServiceModelMock;
-
- @BeforeClass
- public static void onlyOnceSetUp() throws IOException {
- toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
- toscaServiceModel = TestUtil.loadToscaServiceModel("/mock/analyzerService/toscasubstitution/",
- "/mock/globalServiceTemplates/", null);
- }
-
- @Before
- public void init() throws IOException {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void testGetFlatEntityNotFound() throws Exception {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Entity Type 'org.openecomp.resource.vfc.notFound' or one of its derivedFrom type hierarchy, is not defined in tosca service model");
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
-
- ServiceTemplate
- serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.notFound",
- serviceTemplateFromYaml, toscaServiceModel);
- }
- }
-
- @Test
- public void testGetFlatEntityFileNotFound() throws Exception {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Tosca file 'missingFile.yaml' was not found in tosca service model");
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/ServiceTemplateFileNotFoundTest.yaml")) {
-
- ServiceTemplate
- serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE,
- "org.openecomp.resource.vfc.nodes.heat.cmaui_image",
- serviceTemplateFromYaml, toscaServiceModel);
- }
- }
-
- @Test
- public void testGetFlatEntityNodeType() throws Exception {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
-
- ServiceTemplate
- serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- final NodeType flatEntity = (NodeType) toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.nodes.heat" +
- ".cmaui_image", serviceTemplateFromYaml, toscaServiceModel);
-
- Assert.assertNotNull(flatEntity);
- Assert.assertEquals("org.openecomp.resource.vfc.nodes.heat.nova.Server", flatEntity
- .getDerived_from());
- Assert.assertEquals(20, flatEntity.getProperties().size());
- Assert.assertEquals("overridden default value",
- flatEntity.getProperties().get("admin_pass").get_default());
- Assert.assertEquals("REBUILD",
- flatEntity.getProperties().get("image_update_policy").get_default());
- Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
- }
- }
-
- @Test
- public void testGetFlatEntityDataType() throws Exception {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
-
- ServiceTemplate
- serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- final DataType flatEntity = (DataType) toscaAnalyzerService
- .getFlatEntity(ToscaElementTypes.DATA_TYPE,
- "org.openecomp.datatypes.heat.network.MyNewAddressPair", serviceTemplateFromYaml,
- toscaServiceModel);
-
- Assert.assertNotNull(flatEntity);
- Assert.assertEquals("org.openecomp.datatypes.heat.network.MyAddressPair", flatEntity
- .getDerived_from());
- Assert.assertEquals(3, flatEntity.getProperties().size());
- Assert.assertEquals("overridden default value",
- flatEntity.getProperties().get("mac_address").get_default());
- Assert.assertEquals(true,
- flatEntity.getProperties().get("mac_address").getRequired());
- Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
- }
- }
-
- @Test
- public void testCalculateExposedRequirements() throws Exception {
- Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
- RequirementDefinition rd = new RequirementDefinition();
- rd.setCapability("tosca.capabilities.Node");
- rd.setNode("tosca.nodes.Root");
- rd.setRelationship("tosca.relationships.DependsOn");
- Object[] occurences = new Object[]{0, "UNBOUNDED"};
- rd.setOccurrences(occurences);
-
- RequirementDefinition rd1 = new RequirementDefinition();
- rd.setCapability("tosca.capabilities.network.Bindable");
- rd.setNode(null);
- rd.setRelationship("tosca.relationships.network.BindsTo");
- Object[] occurences1 = new Object[]{1, 1};
- rd1.setOccurrences(occurences1);
-
- nodeTypeRequirementDefinition.put("binding", rd1);
- nodeTypeRequirementDefinition.put("dependency", rd);
-
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
- new HashMap<>();
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
- RequirementAssignment ra = new RequirementAssignment();
- ra.setCapability("tosca.capabilities.network.Bindable");
- ra.setNode("pd_server");
- ra.setRelationship("tosca.relationships.network.BindsTo");
- nodeTemplateRequirementsAssignment.put("binding", ra);
-
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
- nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
-
- List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
- .calculateExposedRequirements(nodeTypeRequirementsDefinition,
- nodeTemplateRequirementsAssignment);
- Assert.assertEquals(1, exposedRequirements.size());
- }
-
- @Test
- public void testCalExpReqWithNullNodeInReqAssignment() throws Exception {
- Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
- RequirementDefinition rd = new RequirementDefinition();
- rd.setCapability("tosca.capabilities.Node");
- rd.setNode("tosca.nodes.Root");
- rd.setRelationship("tosca.relationships.DependsOn");
- Object[] occurences = new Object[]{0, "UNBOUNDED"};
- rd.setOccurrences(occurences);
-
- RequirementDefinition rd1 = new RequirementDefinition();
- rd.setCapability("tosca.capabilities.network.Bindable");
- rd.setNode(null);
- rd.setRelationship("tosca.relationships.network.BindsTo");
- Object[] occurences1 = new Object[]{1, 1};
- rd1.setOccurrences(occurences1);
-
- nodeTypeRequirementDefinition.put("binding", rd1);
- nodeTypeRequirementDefinition.put("dependency", rd);
-
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
- new HashMap<>();
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
- RequirementAssignment ra = new RequirementAssignment();
- ra.setCapability("tosca.capabilities.network.Bindable");
- ra.setNode(null);
- ra.setRelationship("tosca.relationships.network.BindsTo");
- nodeTemplateRequirementsAssignment.put("binding", ra);
-
- List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
- nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
-
- List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
- .calculateExposedRequirements(nodeTypeRequirementsDefinition,
- nodeTemplateRequirementsAssignment);
- Assert.assertEquals(1, exposedRequirements.size());
- }
-
- @Test
- public void testCalculateExposedCapabilities() throws Exception {
- Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
- CapabilityDefinition cd = new CapabilityDefinition();
- cd.setType("tosca.capabilities.Scalable");
- nodeTypeCapabilitiesDefinition.put("tosca.capabilities.network.Bindable_pd_server", cd);
- Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
- new HashMap<>();
- Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
- RequirementAssignment ra = new RequirementAssignment();
- ra.setCapability("tosca.capabilities.network.Bindable");
- ra.setNode("pd_server");
- ra.setRelationship("tosca.relationships.network.BindsTo");
- nodeTemplateRequirementsAssignment.put("binding", ra);
- fullFilledRequirementsDefinition.put("pd_server", nodeTemplateRequirementsAssignment);
- Map<String, CapabilityDefinition> exposedCapabilities =
- toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
- fullFilledRequirementsDefinition);
- Assert.assertEquals(1, exposedCapabilities.size());
- }
-
- @Test
- public void testIsRequirementExistsWithInvalidReqId() throws Exception {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
-
- ServiceTemplate
- serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- TestUtil.createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml,
- toscaExtensionYamlUtil);
-
- NodeTemplate port_0 =
- serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
-
- RequirementAssignment ra = new RequirementAssignment();
- ra.setCapability("tosca.capabilities.network.Bindable");
- ra.setNode("server_cmaui");
- ra.setRelationship("tosca.relationships.network.BindsTo");
-
- //Test With Empty requirementId
- Assert.assertEquals(false,
- toscaAnalyzerService.isRequirementExistInNodeTemplate(port_0, "", ra));
-
- //Test With valid requirementId
- Assert.assertEquals(true,
- toscaAnalyzerService.isRequirementExistInNodeTemplate(port_0, "binding", ra));
-
- //Test With invalid requirement assignment
- RequirementAssignment ra1 = new RequirementAssignment();
- ra1.setCapability("tosca.capabilities.network.Bindable1");
- ra1.setNode("server_cmaui1");
- ra1.setRelationship("tosca.relationships.network.BindsTo1");
- Assert.assertEquals(false,
- toscaAnalyzerService.isRequirementExistInNodeTemplate(port_0, "binding", ra1));
- }
- }
-
- @Test
- public void testGetRequirements() throws Exception {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
-
- ServiceTemplate
- serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- NodeTemplate port_0 =
- serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
- List<RequirementAssignment> reqList =
- toscaAnalyzerService.getRequirements(port_0, ToscaConstants.BINDING_REQUIREMENT_ID);
- assertEquals(1, reqList.size());
-
- reqList.clear();
- NodeTemplate port_1 =
- serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui1_port_1");
- reqList = toscaAnalyzerService.getRequirements(port_1, ToscaConstants.LINK_REQUIREMENT_ID);
- assertEquals(2, reqList.size());
-
- reqList.clear();
- reqList = toscaAnalyzerService.getRequirements(port_0, ToscaConstants.LINK_REQUIREMENT_ID);
- assertEquals(0, reqList.size());
- }
- }
-
- @Test
- public void testGetNodeTemplateById() throws Exception {
- ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
- Optional<NodeTemplate> nodeTemplate =
- toscaAnalyzerService.getNodeTemplateById(emptyServiceTemplate, "test_net222");
- assertEquals(false, nodeTemplate.isPresent());
-
- ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
- .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
- nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
- assertEquals(true, nodeTemplate.isPresent());
-
- nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net222");
- assertEquals(false, nodeTemplate.isPresent());
- }
-
- @Test
- public void testGetSubstituteServiceTemplateName() throws Exception {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Invalid Substitute Node Template invalid2, mandatory map property service_template_filter with mandatory key substitute_service_template must be defined.");
-
- Optional<String> substituteServiceTemplateName;
-
- ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
- .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
- Optional<NodeTemplate> notSubstitutableNodeTemplate =
- toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
- assertEquals(true, notSubstitutableNodeTemplate.isPresent());
-
- if (notSubstitutableNodeTemplate.isPresent()) {
- substituteServiceTemplateName = toscaAnalyzerService
- .getSubstituteServiceTemplateName("test_net", notSubstitutableNodeTemplate.get());
- assertEquals(false, substituteServiceTemplateName.isPresent());
- }
-
- Optional<NodeTemplate> substitutableNodeTemplate =
- toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_nested");
- assertEquals(true, substitutableNodeTemplate.isPresent());
- if (substitutableNodeTemplate.isPresent()) {
- substituteServiceTemplateName = toscaAnalyzerService
- .getSubstituteServiceTemplateName("test_nested", substitutableNodeTemplate.get());
- assertEquals(true, substituteServiceTemplateName.isPresent());
- assertEquals("nestedServiceTemplate.yaml", substituteServiceTemplateName.get());
- }
-
- NodeTemplate invalidSubstitutableNodeTemplate1 = new NodeTemplate();
- substituteServiceTemplateName = toscaAnalyzerService
- .getSubstituteServiceTemplateName("invalid1", invalidSubstitutableNodeTemplate1);
- assertEquals(false, substituteServiceTemplateName.isPresent());
-
- substitutableNodeTemplate.ifPresent(nodeTemplate -> {
- Object serviceTemplateFilter = nodeTemplate.getProperties()
- .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
- ((Map) serviceTemplateFilter).clear();
- toscaAnalyzerService
- .getSubstituteServiceTemplateName("invalid2", nodeTemplate);
-
- });
- }
-
-
- @Test
- public void testGetSubstitutableNodeTemplates() throws Exception {
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/ServiceTemplateSubstituteTest.yaml")) {
- ServiceTemplate serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- Map<String, NodeTemplate> substitutableNodeTemplates =
- toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
- assertEquals(2, substitutableNodeTemplates.size());
- assertNotNull(substitutableNodeTemplates.get("test_nested1"));
- assertNotNull(substitutableNodeTemplates.get("test_nested2"));
-
- ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
- emptyServiceTemplate.setTopology_template(new TopologyTemplate());
- substitutableNodeTemplates =
- toscaAnalyzerService.getSubstitutableNodeTemplates(emptyServiceTemplate);
- assertEquals(0, substitutableNodeTemplates.size());
- }
-
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
- ServiceTemplate serviceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
- Map<String, NodeTemplate> substitutableNodeTemplates =
- toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
- assertEquals(0, substitutableNodeTemplates.size());
- }
- }
-
- @Test
- public void testGetSubstitutionMappedNodeTemplateByExposedReq() throws Exception {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
- ServiceTemplate nestedServiceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService
- .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
- nestedServiceTemplateFromYaml, "local_storage_server_cmaui");
- assertEquals(true, mappedNodeTemplate.isPresent());
- mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
- assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
- assertNotNull(stringNodeTemplateEntry.getValue());
- });
-
- mappedNodeTemplate = toscaAnalyzerService
- .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
- nestedServiceTemplateFromYaml, "link_cmaui_port_invalid");
- assertEquals(true, mappedNodeTemplate.isPresent());
- mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
- assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
- assertNotNull(stringNodeTemplateEntry.getValue());
- });
-
- ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
- .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
- mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
- toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
- "local_storage_server_cmaui");
- assertEquals(false, mappedNodeTemplate.isPresent());
- }
- }
-
- @Test
- public void invalidSubstitutableMapping() throws Exception {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Invalid Substitution Service Template invalidMappingServiceTemplate.yaml, missing mandatory file 'Node type' in substitution mapping.");
- ServiceTemplate invalidMappingServiceTemplate = new ServiceTemplate();
- invalidMappingServiceTemplate.setTopology_template(new TopologyTemplate());
- invalidMappingServiceTemplate.getTopology_template()
- .setSubstitution_mappings(new SubstitutionMapping());
- toscaAnalyzerService
- .getSubstitutionMappedNodeTemplateByExposedReq("invalidMappingServiceTemplate.yaml",
- invalidMappingServiceTemplate, "local_storage_server_cmaui");
- }
-
- @Test
- public void substitutableMappingWithNoReqMap() throws Exception {
- ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
- .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
- ServiceTemplate emptyReqMapping = new ServiceTemplate();
- emptyReqMapping.setTopology_template(new TopologyTemplate());
- emptyReqMapping.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
- emptyReqMapping.getTopology_template().getSubstitution_mappings().setNode_type("temp");
- Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService
- .getSubstitutionMappedNodeTemplateByExposedReq(
- toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
- "local_storage_server_cmaui");
- assertEquals(false, mappedNodeTemplate.isPresent());
- }
-
- @Test
- public void testGetSubstitutionMappedNodeTemplateByExposedReqInvalid() throws Exception {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
- ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
- try (InputStream yamlFile = toscaExtensionYamlUtil
- .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
- ServiceTemplate nestedServiceTemplateFromYaml =
- toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
-
- toscaAnalyzerService
- .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
- nestedServiceTemplateFromYaml, "link_cmaui_port_invalid");
- }
- }
-
- @Test
- public void testIsDesiredRequirementAssignmentMatch() throws Exception {
-
- RequirementAssignment requirementAssignment = new RequirementAssignment();
- String capability = "Test.Capability";
- String node = "Test.node";
- String relationship = "Test.relationship";
- requirementAssignment.setCapability(capability);
- requirementAssignment.setNode(node);
- requirementAssignment.setRelationship(relationship);
-
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, node, relationship));
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, null, node, relationship));
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, null, relationship));
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, node, null));
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, null, null, relationship));
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, null, null));
- assertEquals(true, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, null, node, null));
-
- }
-
- @Test
- public void testIsDesiredRequirementAssignmentNoMatch() throws Exception {
-
- RequirementAssignment requirementAssignment = new RequirementAssignment();
- String capability = "Test.Capability";
- String node = "Test.node";
- String relationship = "Test.relationship";
- requirementAssignment.setCapability(capability);
- requirementAssignment.setNode(node);
- requirementAssignment.setRelationship(relationship);
-
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, "no", node, relationship));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, "no", "no", relationship));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, "no", "no", "no"));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, "no", relationship));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, node, "no"));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, capability, "no", "no"));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, "no", null, null));
- assertEquals(false, toscaAnalyzerService
- .isDesiredRequirementAssignment(requirementAssignment, null, null, null));
-
-
- }
-
- @Test
- public void shouldReturnFalseIfNdTmpIsNull() {
- NodeTemplate nodeTemplate = null;
- assertFalse(toscaAnalyzerService
- .isTypeOf(nodeTemplate, ToscaNodeType.NATIVE_NETWORK, new ServiceTemplate(),
- toscaServiceModelMock));
- }
-
- @Test
- public void shouldReturnTrueIfNdTmpTypeIsOfRequestedType() {
- NodeTemplate nodeTemplate = new NodeTemplate();
- String nodeTypeToSearch = ToscaNodeType.NATIVE_BLOCK_STORAGE;
- nodeTemplate.setType(nodeTypeToSearch);
- assertTrue(toscaAnalyzerService
- .isTypeOf(nodeTemplate, nodeTypeToSearch, new ServiceTemplate(),
- toscaServiceModelMock));
- }
-
- @Test
- public void shouldReturnTrueIfDataTypeIsOfRequestedType() {
- PropertyDefinition propertyDefinition = new PropertyDefinition();
- String propertyTypeToSearch = "tosca.datatypes.TimeInterval";
- propertyDefinition.setType(propertyTypeToSearch);
- assertTrue(toscaAnalyzerService
- .isTypeOf(propertyDefinition, propertyTypeToSearch, new ServiceTemplate(),
- toscaServiceModelMock));
- }
-
- @Test
- public void shouldReturnTrueIfInterfaceTypeIsOfRequestedType() {
- InterfaceDefinitionType interfaceDefinition = new InterfaceDefinitionType();
- String interfaceTypeToSearch = "test.interface.A";
- interfaceDefinition.setType(interfaceTypeToSearch);
- assertTrue(toscaAnalyzerService
- .isTypeOf(interfaceDefinition, interfaceTypeToSearch, new ServiceTemplate(),
- toscaServiceModelMock));
- }
-
- @Test
- public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNdTyDerivedFromRequestedType() {
- String typeToMatch = ToscaNodeType.CINDER_VOLUME;
- when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
- Map<String, NodeType> stNodeTypes = new HashMap<>();
- addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
- NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
- addNodeType(stNodeTypes, typeToMatch, nodeType);
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setNode_types(stNodeTypes);
- assertTrue(toscaAnalyzerService
- .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE,
- serviceTemplate, toscaServiceModelMock));
-
- }
-
- @Test
- public void dataTypeParameterExistInHierarchy() {
- String testedDataTypeKey = "test.dataType.B";
- when(parameterDefinitionMock.getType()).thenReturn(testedDataTypeKey);
- dataTypeExistInHierarchy(testedDataTypeKey, parameterDefinitionMock);
-
- }
-
- @Test
- public void dataTypePropertyExistInHierarchy() {
- String testedDataTypeKey = "test.dataType.B";
- when(propertyDefinitionMock.getType()).thenReturn(testedDataTypeKey);
- dataTypeExistInHierarchy(testedDataTypeKey, propertyDefinitionMock);
- }
-
- private void dataTypeExistInHierarchy(String testedDataTypeKey,
- DefinitionOfDataType testedDefinitionDataType) {
- String typeToMatch = "test.dataType.A";
- Map<String, DataType> stDataTypes = new HashMap<>();
- addDataType(stDataTypes, "tosca.datatypes.network.NetworkInfo", new DataType());
- DataType testedDataType = createDataType(typeToMatch);
- addDataType(stDataTypes, testedDataTypeKey, testedDataType);
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setData_types(stDataTypes);
- assertTrue(toscaAnalyzerService
- .isTypeOf(testedDefinitionDataType, typeToMatch, serviceTemplate, toscaServiceModelMock));
- }
-
- @Test
- public void interfaceTypeExistInHierarchy() {
- String typeToMatch = "test.interfaceType.A";
- String testedInterfaceTypeKey = "test.interfaceType.B";
- when(interfaceDefinitionMock.getType()).thenReturn(testedInterfaceTypeKey);
- Map<String, Object> stInterfaceTypes = new HashMap<>();
- stInterfaceTypes.put("tosca.interfaces.network.NetworkInfo", new InterfaceType());
- InterfaceType testedInterfaceType = createInterfaceType(typeToMatch);
- stInterfaceTypes.put(testedInterfaceTypeKey, testedInterfaceType);
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setInterface_types(stInterfaceTypes);
- assertTrue(toscaAnalyzerService
- .isTypeOf(interfaceDefinitionMock, "test.interfaceType.A",
- serviceTemplate, toscaServiceModelMock));
- }
-
- @Test
- public void shouldThrowCoreExceptionForInvalidNodeType() {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Entity Type 'AAA' or one of its derivedFrom type hierarchy, is not defined in " +
- "tosca service model");
- when(nodeTemplateMock.getType()).thenReturn("AAA");
- Map<String, NodeType> stNodeTypes = new HashMap<>();
- addNodeType(stNodeTypes, "notImportant", new NodeType());
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setNode_types(stNodeTypes);
- toscaAnalyzerService
- .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_COMPUTE, serviceTemplate,
- toscaServiceModelMock);
- }
-
- @Test
- public void shouldThrowCoreExceptionForInvalidNodeType2Level() {
- thrown.expect(CoreException.class);
- thrown.expectMessage(
- "Entity Type 'A' or one of its derivedFrom type hierarchy, is not defined in tosca " +
- "service model");
- String typeToMatch = "A";
- when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
- Map<String, NodeType> stNodeTypes = new HashMap<>();
- addNodeType(stNodeTypes, "notImportant", new NodeType());
- addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
- addNodeType(stNodeTypes, "ADerivedFromB'", createNodeType("BDerivedFromC"));
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setNode_types(stNodeTypes);
- assertTrue(toscaAnalyzerService
- .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
- }
-
- @Test
- public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNotDerivedFromRequestedTypeBut2ndLevelDerivedFromMatch() {
- String typeToMatch = "A";
- when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
- Map<String, NodeType> stNodeTypes = new HashMap<>();
- addNodeType(stNodeTypes, "notImportant", new NodeType());
- addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
- addNodeType(stNodeTypes, "ADerivedFromB", createNodeType("BDerivedFromC"));
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setNode_types(stNodeTypes);
- assertTrue(toscaAnalyzerService
- .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
- }
-
- private NodeType createNodeType(String derivedFrom) {
- NodeType nodeType = new NodeType();
- nodeType.setDerived_from(derivedFrom);
- return nodeType;
- }
-
- private DataType createDataType(String derivedFrom) {
- DataType dataType = new DataType();
- dataType.setDerived_from(derivedFrom);
- return dataType;
- }
-
- private InterfaceType createInterfaceType(String derivedFrom) {
- InterfaceType interfaceType = new InterfaceType();
- interfaceType.setDerived_from(derivedFrom);
- return interfaceType;
- }
-
- private void addNodeType(Map<String, NodeType> stNodeTypes, String key, NodeType nodeType) {
- stNodeTypes.put(key, nodeType);
- }
-
- private void addDataType(Map<String, DataType> stDataTypes, String key, DataType dataType) {
- stDataTypes.put(key, dataType);
- }
-
- @Test
- public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn1stLevelImports() {
- String typeToMatch = ToscaNodeType.CINDER_VOLUME;
- when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
- ServiceTemplate mainST = new ServiceTemplate();
- List<Map<String, Import>> imports = new ArrayList<>();
- Map<String, Import> importMap = new HashMap<>();
- Import anImport = new Import();
- anImport.setFile("mainImport");
- importMap.put("bla bla", anImport);
- imports.add(importMap);
- mainST.setImports(imports);
-
- //create searchable service template
- Map<String, NodeType> stNodeTypes = new HashMap<>();
- addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
- NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
- addNodeType(stNodeTypes, typeToMatch, nodeType);
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setNode_types(stNodeTypes);
-
- // add service templates to tosca service model
- Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
- serviceTemplates.put("testMainServiceTemplate", mainST);
- serviceTemplates.put("mainImport", serviceTemplate);
- when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
-
- assertTrue(toscaAnalyzerService
- .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainST,
- toscaServiceModelMock));
- }
-
- @Test
- public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn2ndLevelImports() {
- String typeToMatch = ToscaNodeType.CINDER_VOLUME;
- when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
- ServiceTemplate mainST = new ServiceTemplate();
- List<Map<String, Import>> imports = new ArrayList<>();
- Map<String, Import> importMap = new HashMap<>();
- Import anImport = new Import();
- anImport.setFile("refToMainImport");
- importMap.put("bla bla", anImport);
- imports.add(importMap);
- mainST.setImports(imports);
-
- //create searchable service template
- Map<String, NodeType> stNodeTypes = new HashMap<>();
- addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
- NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
- addNodeType(stNodeTypes, typeToMatch, nodeType);
- ServiceTemplate serviceTemplate = new ServiceTemplate();
- serviceTemplate.setNode_types(stNodeTypes);
-
- // create 1st level service template with import only
- ServiceTemplate firstLevelST = new ServiceTemplate();
- List<Map<String, Import>> firstLevelImports = new ArrayList<>();
- Map<String, Import> firstLevelImportsMap = new HashMap<>();
- Import firstLevelImport = new Import();
- firstLevelImport.setFile("mainImport");
- firstLevelImportsMap.put("bla bla 2", firstLevelImport);
- firstLevelImports.add(firstLevelImportsMap);
- firstLevelST.setImports(firstLevelImports);
-
- // add service templates to tosca service model
- Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
- serviceTemplates.put("testMainServiceTemplate", mainST);
- serviceTemplates.put("refToMainImport", firstLevelST);
- serviceTemplates.put("mainImport", serviceTemplate);
- when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
-
- assertTrue(toscaAnalyzerService
- .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainST,
- toscaServiceModelMock));
- }
-
- // not found at all should throw core exception
+ private static ToscaAnalyzerService toscaAnalyzerService;
+ private static ToscaServiceModel toscaServiceModel;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Mock
+ private NodeTemplate nodeTemplateMock;
+ @Mock
+ private ParameterDefinition parameterDefinitionMock;
+ @Mock
+ private PropertyDefinition propertyDefinitionMock;
+ @Mock
+ private InterfaceDefinitionType interfaceDefinitionMock;
+ @Mock
+ private ToscaServiceModel toscaServiceModelMock;
+
+ @BeforeClass
+ public static void onlyOnceSetUp() throws IOException {
+ toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
+ toscaServiceModel = TestUtil.loadToscaServiceModel("/mock/analyzerService/toscasubstitution/",
+ "/mock/globalServiceTemplates/", null);
+ }
+
+ @Before
+ public void init() throws IOException {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testGetFlatEntityNotFound() throws Exception {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage(
+ "Entity Type 'org.openecomp.resource.vfc.notFound' or one of its derivedFrom type hierarchy, is not defined in tosca service model");
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.notFound",
+ serviceTemplateFromYaml, toscaServiceModel);
+ }
+ }
+
+ @Test
+ public void testGetFlatEntityFileNotFound() throws Exception {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage("Tosca file 'missingFile.yaml' was not found in tosca service model");
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/ServiceTemplateFileNotFoundTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ toscaAnalyzerService
+ .getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.nodes.heat.cmaui_image",
+ serviceTemplateFromYaml, toscaServiceModel);
+ }
+ }
+
+ @Test
+ public void testGetFlatEntityNodeType() throws Exception {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE,
+ "org.openecomp.resource.vfc.nodes.heat" + ".cmaui_image", serviceTemplateFromYaml,
+ toscaServiceModel);
+
+ Assert.assertNotNull(flatData);
+ checkNodeTypeFlatEntity(flatData);
+ checkNodeTypeInheritanceHierarchy(flatData);
+ }
+ }
+
+ private void checkNodeTypeInheritanceHierarchy(ToscaFlatData flatData) {
+ List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
+ Assert.assertNotNull(inheritanceHierarchyType);
+ Assert.assertEquals(4, inheritanceHierarchyType.size());
+ Assert.assertEquals(true,
+ inheritanceHierarchyType.contains("org.openecomp.resource.vfc.nodes.heat.cmaui_image"));
+ Assert.assertEquals(true,
+ inheritanceHierarchyType.contains("org.openecomp.resource.vfc.nodes.heat.nova.Server"));
+ Assert.assertEquals(true, inheritanceHierarchyType.contains("tosca.nodes.Compute"));
+ Assert.assertEquals(true, inheritanceHierarchyType.contains("tosca.nodes.Root"));
+ }
+
+ private void checkNodeTypeFlatEntity(ToscaFlatData flatData) {
+ Assert.assertNotNull(flatData.getFlatEntity());
+ NodeType flatEntity = (NodeType) flatData.getFlatEntity();
+ Assert.assertEquals("org.openecomp.resource.vfc.nodes.heat.nova.Server", flatEntity.getDerived_from());
+ Assert.assertEquals(20, flatEntity.getProperties().size());
+ Assert.assertEquals("overridden default value", flatEntity.getProperties().get("admin_pass").get_default());
+ Assert.assertEquals("REBUILD", flatEntity.getProperties().get("image_update_policy").get_default());
+ Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
+ }
+
+ @Test
+ public void testGetFlatEntityNodeTypeInterface() throws Exception {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE,
+ "org.openecomp.resource.vfc.nodes.heat.cmaui_image_extend", serviceTemplateFromYaml,
+ toscaServiceModel);
+
+ Assert.assertNotNull(flatData);
+ Assert.assertNotNull(flatData.getFlatEntity());
+ NodeType flatEntity = (NodeType) flatData.getFlatEntity();
+ Assert.assertNotNull(flatEntity.getInterfaces());
+ Object standardInterfaceObj = flatEntity.getInterfaces().get("Standard");
+ Assert.assertNotNull(standardInterfaceObj);
+ Optional<InterfaceDefinitionType> standardInterface = DataModelUtil
+ .convertObjToInterfaceDefinition("Standard",
+ standardInterfaceObj,
+ InterfaceDefinitionType.class);
+ Assert.assertEquals(true, standardInterface.isPresent());
+ Assert.assertEquals(2, standardInterface.get().getInputs().size());
+ Assert.assertEquals(3, standardInterface.get().getOperations().size());
+ OperationDefinitionType createOperation = toscaExtensionYamlUtil.yamlToObject(
+ toscaExtensionYamlUtil.objectToYaml(standardInterface.get().getOperations().get("create")),
+ OperationDefinitionType.class);
+ Assert.assertEquals(2, createOperation.getInputs().size());
+
+ List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
+ Assert.assertNotNull(inheritanceHierarchyType);
+ Assert.assertEquals(5, inheritanceHierarchyType.size());
+ }
+ }
+
+
+ @Test
+ public void testGetFlatEntityDataType() throws Exception {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.DATA_TYPE,
+ "org.openecomp.datatypes.heat.network.MyNewAddressPair", serviceTemplateFromYaml,
+ toscaServiceModel);
+
+ Assert.assertNotNull(flatData);
+ Assert.assertNotNull(flatData.getFlatEntity());
+ DataType flatEntity = (DataType) flatData.getFlatEntity();
+ Assert.assertEquals("org.openecomp.datatypes.heat.network.MyAddressPair", flatEntity.getDerived_from());
+ Assert.assertEquals(3, flatEntity.getProperties().size());
+ Assert.assertEquals("overridden default value",
+ flatEntity.getProperties().get("mac_address").get_default());
+ Assert.assertEquals(true, flatEntity.getProperties().get("mac_address").getRequired());
+ Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
+
+ List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
+ Assert.assertNotNull(inheritanceHierarchyType);
+ Assert.assertEquals(4, inheritanceHierarchyType.size());
+ }
+ }
+
+ @Test
+ public void testCalculateExposedRequirements() throws Exception {
+ RequirementDefinition rd = new RequirementDefinition();
+ rd.setCapability("tosca.capabilities.Node");
+ rd.setNode("tosca.nodes.Root");
+ rd.setRelationship("tosca.relationships.DependsOn");
+ Object[] occurences = new Object[] {0, "UNBOUNDED"};
+ rd.setOccurrences(occurences);
+
+ RequirementDefinition rd1 = new RequirementDefinition();
+ rd.setCapability("tosca.capabilities.network.Bindable");
+ rd.setNode(null);
+ rd.setRelationship("tosca.relationships.network.BindsTo");
+ Object[] occurences1 = new Object[] {1, 1};
+ rd1.setOccurrences(occurences1);
+
+ Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
+ nodeTypeRequirementDefinition.put("binding", rd1);
+ nodeTypeRequirementDefinition.put("dependency", rd);
+
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
+ RequirementAssignment ra = new RequirementAssignment();
+ ra.setCapability("tosca.capabilities.network.Bindable");
+ ra.setNode("pd_server");
+ ra.setRelationship("tosca.relationships.network.BindsTo");
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
+ nodeTemplateRequirementsAssignment.put("binding", ra);
+
+ List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
+ nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
+
+ List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
+ .calculateExposedRequirements(
+ nodeTypeRequirementsDefinition,
+ nodeTemplateRequirementsAssignment);
+ Assert.assertEquals(1, exposedRequirements.size());
+ }
+
+ @Test
+ public void testCalExpReqWithNullNodeInReqAssignment() throws Exception {
+ RequirementDefinition rd = new RequirementDefinition();
+ rd.setCapability("tosca.capabilities.Node");
+ rd.setNode("tosca.nodes.Root");
+ rd.setRelationship("tosca.relationships.DependsOn");
+ Object[] occurences = new Object[] {0, "UNBOUNDED"};
+ rd.setOccurrences(occurences);
+
+ RequirementDefinition rd1 = new RequirementDefinition();
+ rd.setCapability("tosca.capabilities.network.Bindable");
+ rd.setNode(null);
+ rd.setRelationship("tosca.relationships.network.BindsTo");
+ Object[] occurences1 = new Object[] {1, 1};
+ rd1.setOccurrences(occurences1);
+
+ Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
+ nodeTypeRequirementDefinition.put("binding", rd1);
+ nodeTypeRequirementDefinition.put("dependency", rd);
+
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
+ RequirementAssignment ra = new RequirementAssignment();
+ ra.setCapability("tosca.capabilities.network.Bindable");
+ ra.setNode(null);
+ ra.setRelationship("tosca.relationships.network.BindsTo");
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
+ nodeTemplateRequirementsAssignment.put("binding", ra);
+
+ List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
+ nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
+
+ List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
+ .calculateExposedRequirements(
+ nodeTypeRequirementsDefinition,
+ nodeTemplateRequirementsAssignment);
+ Assert.assertEquals(1, exposedRequirements.size());
+ }
+
+ @Test
+ public void testCalculateExposedCapabilities() throws Exception {
+ Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
+ CapabilityDefinition cd = new CapabilityDefinition();
+ cd.setType("tosca.capabilities.Scalable");
+ nodeTypeCapabilitiesDefinition.put("tosca.capabilities.network.Bindable_pd_server", cd);
+ Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
+ RequirementAssignment ra = new RequirementAssignment();
+ ra.setCapability("tosca.capabilities.network.Bindable");
+ ra.setNode("pd_server");
+ ra.setRelationship("tosca.relationships.network.BindsTo");
+ nodeTemplateRequirementsAssignment.put("binding", ra);
+ Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
+ fullFilledRequirementsDefinition.put("pd_server", nodeTemplateRequirementsAssignment);
+ Map<String, CapabilityDefinition> exposedCapabilities = toscaAnalyzerService.calculateExposedCapabilities(
+ nodeTypeCapabilitiesDefinition, fullFilledRequirementsDefinition);
+ Assert.assertEquals(1, exposedCapabilities.size());
+ }
+
+ @Test
+ public void testIsRequirementExistsWithInvalidReqId() throws Exception {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ TestUtil.createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml, toscaExtensionYamlUtil);
+
+
+ RequirementAssignment ra = new RequirementAssignment();
+ ra.setCapability("tosca.capabilities.network.Bindable");
+ ra.setNode("server_cmaui");
+ ra.setRelationship("tosca.relationships.network.BindsTo");
+
+ NodeTemplate port0 =
+ serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
+ //Test With Empty requirementId
+ Assert.assertEquals(false, toscaAnalyzerService.isRequirementExistInNodeTemplate(port0, "", ra));
+
+ //Test With valid requirementId
+ Assert.assertEquals(true, toscaAnalyzerService.isRequirementExistInNodeTemplate(port0, "binding", ra));
+
+ //Test With invalid requirement assignment
+ RequirementAssignment ra1 = new RequirementAssignment();
+ ra1.setCapability("tosca.capabilities.network.Bindable1");
+ ra1.setNode("server_cmaui1");
+ ra1.setRelationship("tosca.relationships.network.BindsTo1");
+ Assert.assertEquals(false, toscaAnalyzerService.isRequirementExistInNodeTemplate(port0, "binding", ra1));
+ }
+ }
+
+ @Test
+ public void testGetRequirements() throws Exception {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ NodeTemplate port0 =
+ serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
+ List<RequirementAssignment> reqList =
+ toscaAnalyzerService.getRequirements(port0, ToscaConstants.BINDING_REQUIREMENT_ID);
+ assertEquals(1, reqList.size());
+
+ reqList.clear();
+ NodeTemplate port1 =
+ serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui1_port_1");
+ reqList = toscaAnalyzerService.getRequirements(port1, ToscaConstants.LINK_REQUIREMENT_ID);
+ assertEquals(2, reqList.size());
+
+ reqList.clear();
+ reqList = toscaAnalyzerService.getRequirements(port0, ToscaConstants.LINK_REQUIREMENT_ID);
+ assertEquals(0, reqList.size());
+ }
+ }
+
+ @Test
+ public void testGetNodeTemplateById() throws Exception {
+ ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
+ Optional<NodeTemplate> nodeTemplate =
+ toscaAnalyzerService.getNodeTemplateById(emptyServiceTemplate, "test_net222");
+ assertEquals(false, nodeTemplate.isPresent());
+
+ ServiceTemplate mainServiceTemplate =
+ toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
+ nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
+ assertEquals(true, nodeTemplate.isPresent());
+
+ nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net222");
+ assertEquals(false, nodeTemplate.isPresent());
+ }
+
+ @Test
+ public void testGetSubstituteServiceTemplateName() throws Exception {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage(
+ "Invalid Substitute Node Template invalid2, mandatory map property service_template_filter with mandatory key substitute_service_template must be defined.");
+
+ Optional<String> substituteServiceTemplateName;
+
+ ServiceTemplate mainServiceTemplate =
+ toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
+ Optional<NodeTemplate> notSubstitutableNodeTemplate =
+ toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
+ assertEquals(true, notSubstitutableNodeTemplate.isPresent());
+
+ if (notSubstitutableNodeTemplate.isPresent()) {
+ substituteServiceTemplateName = toscaAnalyzerService.getSubstituteServiceTemplateName("test_net",
+ notSubstitutableNodeTemplate.get());
+ assertEquals(false, substituteServiceTemplateName.isPresent());
+ }
+
+ Optional<NodeTemplate> substitutableNodeTemplate =
+ toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_nested");
+ assertEquals(true, substitutableNodeTemplate.isPresent());
+ if (substitutableNodeTemplate.isPresent()) {
+ substituteServiceTemplateName = toscaAnalyzerService.getSubstituteServiceTemplateName("test_nested",
+ substitutableNodeTemplate.get());
+ assertEquals(true, substituteServiceTemplateName.isPresent());
+ assertEquals("nestedServiceTemplate.yaml", substituteServiceTemplateName.get());
+ }
+
+ NodeTemplate invalidSubstitutableNodeTemplate1 = new NodeTemplate();
+ substituteServiceTemplateName =
+ toscaAnalyzerService.getSubstituteServiceTemplateName("invalid1", invalidSubstitutableNodeTemplate1);
+ assertEquals(false, substituteServiceTemplateName.isPresent());
+
+ substitutableNodeTemplate.ifPresent(nodeTemplate -> {
+ Object serviceTemplateFilter =
+ nodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
+ ((Map) serviceTemplateFilter).clear();
+ toscaAnalyzerService.getSubstituteServiceTemplateName("invalid2", nodeTemplate);
+
+ });
+ }
+
+
+ @Test
+ public void testGetSubstitutableNodeTemplates() throws Exception {
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/ServiceTemplateSubstituteTest.yaml")) {
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ Map<String, NodeTemplate> substitutableNodeTemplates =
+ toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
+ assertEquals(2, substitutableNodeTemplates.size());
+ assertNotNull(substitutableNodeTemplates.get("test_nested1"));
+ assertNotNull(substitutableNodeTemplates.get("test_nested2"));
+
+ ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
+ emptyServiceTemplate.setTopology_template(new TopologyTemplate());
+ substitutableNodeTemplates = toscaAnalyzerService.getSubstitutableNodeTemplates(emptyServiceTemplate);
+ assertEquals(0, substitutableNodeTemplates.size());
+ }
+
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+ ServiceTemplate serviceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+ Map<String, NodeTemplate> substitutableNodeTemplates =
+ toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
+ assertEquals(0, substitutableNodeTemplates.size());
+ }
+ }
+
+ @Test
+ public void testGetSubstitutionMappedNodeTemplateByExposedReq() throws Exception {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage(
+ "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+ ServiceTemplate nestedServiceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService
+ .getSubstitutionMappedNodeTemplateByExposedReq(
+ "NestedServiceTemplateSubstituteTest.yaml",
+ nestedServiceTemplateFromYaml,
+ "local_storage_server_cmaui");
+ assertEquals(true, mappedNodeTemplate.isPresent());
+ mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
+ assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
+ assertNotNull(stringNodeTemplateEntry.getValue());
+ });
+
+ mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
+ "NestedServiceTemplateSubstituteTest.yaml", nestedServiceTemplateFromYaml,
+ "link_cmaui_port_invalid");
+ assertEquals(true, mappedNodeTemplate.isPresent());
+ mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
+ assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
+ assertNotNull(stringNodeTemplateEntry.getValue());
+ });
+
+ ServiceTemplate mainServiceTemplate =
+ toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
+ mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
+ toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
+ "local_storage_server_cmaui");
+ assertEquals(false, mappedNodeTemplate.isPresent());
+ }
+ }
+
+ @Test
+ public void invalidSubstitutableMapping() throws Exception {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage(
+ "Invalid Substitution Service Template invalidMappingServiceTemplate.yaml, missing mandatory file 'Node type' in substitution mapping.");
+ ServiceTemplate invalidMappingServiceTemplate = new ServiceTemplate();
+ invalidMappingServiceTemplate.setTopology_template(new TopologyTemplate());
+ invalidMappingServiceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
+ toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq("invalidMappingServiceTemplate.yaml",
+ invalidMappingServiceTemplate, "local_storage_server_cmaui");
+ }
+
+ @Test
+ public void substitutableMappingWithNoReqMap() throws Exception {
+ ServiceTemplate emptyReqMapping = new ServiceTemplate();
+ emptyReqMapping.setTopology_template(new TopologyTemplate());
+ emptyReqMapping.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
+ emptyReqMapping.getTopology_template().getSubstitution_mappings().setNode_type("temp");
+ ServiceTemplate mainServiceTemplate =
+ toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
+ Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService
+ .getSubstitutionMappedNodeTemplateByExposedReq(
+ toscaServiceModel
+ .getEntryDefinitionServiceTemplate(),
+ mainServiceTemplate,
+ "local_storage_server_cmaui");
+ assertEquals(false, mappedNodeTemplate.isPresent());
+ }
+
+ @Test
+ public void testGetSubstitutionMappedNodeTemplateByExposedReqInvalid() throws Exception {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage(
+ "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
+ ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
+ try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
+ "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
+ ServiceTemplate nestedServiceTemplateFromYaml =
+ toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
+
+ toscaAnalyzerService
+ .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
+ nestedServiceTemplateFromYaml, "link_cmaui_port_invalid");
+ }
+ }
+
+ @Test
+ public void testIsDesiredRequirementAssignmentMatch() throws Exception {
+
+ RequirementAssignment requirementAssignment = new RequirementAssignment();
+ String capability = "Test.Capability";
+ String node = "Test.node";
+ String relationship = "Test.relationship";
+ requirementAssignment.setCapability(capability);
+ requirementAssignment.setNode(node);
+ requirementAssignment.setRelationship(relationship);
+
+ assertEquals(true, toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, node,
+ relationship));
+ assertEquals(true,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, node, relationship));
+ assertEquals(true, toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, null,
+ relationship));
+ assertEquals(true,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, node, null));
+ assertEquals(true,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, null, relationship));
+ assertEquals(true,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, null, null));
+ assertEquals(true,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, node, null));
+
+ }
+
+ @Test
+ public void testIsDesiredRequirementAssignmentNoMatch() throws Exception {
+
+ RequirementAssignment requirementAssignment = new RequirementAssignment();
+ String capability = "Test.Capability";
+ String node = "Test.node";
+ String relationship = "Test.relationship";
+ requirementAssignment.setCapability(capability);
+ requirementAssignment.setNode(node);
+ requirementAssignment.setRelationship(relationship);
+
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", node, relationship));
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", "no", relationship));
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", "no", "no"));
+ assertEquals(false, toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, "no",
+ relationship));
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, node, "no"));
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, "no", "no"));
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", null, null));
+ assertEquals(false,
+ toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, null, null));
+
+
+ }
+
+ @Test
+ public void shouldReturnFalseIfNdTmpIsNull() {
+ NodeTemplate nodeTemplate = null;
+ assertFalse(toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.NATIVE_NETWORK, new ServiceTemplate(),
+ toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldReturnTrueIfNdTmpTypeIsOfRequestedType() {
+ NodeTemplate nodeTemplate = new NodeTemplate();
+ String nodeTypeToSearch = ToscaNodeType.NATIVE_BLOCK_STORAGE;
+ nodeTemplate.setType(nodeTypeToSearch);
+ assertTrue(toscaAnalyzerService
+ .isTypeOf(nodeTemplate, nodeTypeToSearch, new ServiceTemplate(), toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldReturnTrueIfDataTypeIsOfRequestedType() {
+ PropertyDefinition propertyDefinition = new PropertyDefinition();
+ String propertyTypeToSearch = "tosca.datatypes.TimeInterval";
+ propertyDefinition.setType(propertyTypeToSearch);
+ assertTrue(toscaAnalyzerService.isTypeOf(propertyDefinition, propertyTypeToSearch, new ServiceTemplate(),
+ toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldReturnTrueIfInterfaceTypeIsOfRequestedType() {
+ InterfaceDefinitionType interfaceDefinition = new InterfaceDefinitionType();
+ String interfaceTypeToSearch = "test.interface.A";
+ interfaceDefinition.setType(interfaceTypeToSearch);
+ assertTrue(toscaAnalyzerService.isTypeOf(interfaceDefinition, interfaceTypeToSearch, new ServiceTemplate(),
+ toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNdTyDerivedFromRequestedType() {
+ String typeToMatch = ToscaNodeType.CINDER_VOLUME;
+ when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
+ Map<String, NodeType> stNodeTypes = new HashMap<>();
+ addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
+ NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
+ addNodeType(stNodeTypes, typeToMatch, nodeType);
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setNode_types(stNodeTypes);
+ assertTrue(toscaAnalyzerService.isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, serviceTemplate,
+ toscaServiceModelMock));
+
+ }
+
+ @Test
+ public void dataTypeParameterExistInHierarchy() {
+ String testedDataTypeKey = "test.dataType.B";
+ when(parameterDefinitionMock.getType()).thenReturn(testedDataTypeKey);
+ dataTypeExistInHierarchy(testedDataTypeKey, parameterDefinitionMock);
+
+ }
+
+ @Test
+ public void dataTypePropertyExistInHierarchy() {
+ String testedDataTypeKey = "test.dataType.B";
+ when(propertyDefinitionMock.getType()).thenReturn(testedDataTypeKey);
+ dataTypeExistInHierarchy(testedDataTypeKey, propertyDefinitionMock);
+ }
+
+ private void dataTypeExistInHierarchy(String testedDataTypeKey, DefinitionOfDataType testedDefinitionDataType) {
+ String typeToMatch = "test.dataType.A";
+ Map<String, DataType> stDataTypes = new HashMap<>();
+ addDataType(stDataTypes, "tosca.datatypes.network.NetworkInfo", new DataType());
+ DataType testedDataType = createDataType(typeToMatch);
+ addDataType(stDataTypes, testedDataTypeKey, testedDataType);
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setData_types(stDataTypes);
+ assertTrue(toscaAnalyzerService
+ .isTypeOf(testedDefinitionDataType, typeToMatch, serviceTemplate, toscaServiceModelMock));
+ }
+
+ @Test
+ public void interfaceTypeExistInHierarchy() {
+ String typeToMatch = "test.interfaceType.A";
+ String testedInterfaceTypeKey = "test.interfaceType.B";
+ when(interfaceDefinitionMock.getType()).thenReturn(testedInterfaceTypeKey);
+ Map<String, Object> stInterfaceTypes = new HashMap<>();
+ stInterfaceTypes.put("tosca.interfaces.network.NetworkInfo", new InterfaceType());
+ InterfaceType testedInterfaceType = createInterfaceType(typeToMatch);
+ stInterfaceTypes.put(testedInterfaceTypeKey, testedInterfaceType);
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setInterface_types(stInterfaceTypes);
+ assertTrue(toscaAnalyzerService.isTypeOf(interfaceDefinitionMock, "test.interfaceType.A", serviceTemplate,
+ toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldThrowCoreExceptionForInvalidNodeType() {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage("Entity Type 'AAA' or one of its derivedFrom type hierarchy, is not defined in "
+ + "tosca service model");
+ when(nodeTemplateMock.getType()).thenReturn("AAA");
+ Map<String, NodeType> stNodeTypes = new HashMap<>();
+ addNodeType(stNodeTypes, "notImportant", new NodeType());
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setNode_types(stNodeTypes);
+ toscaAnalyzerService
+ .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_COMPUTE, serviceTemplate, toscaServiceModelMock);
+ }
+
+ @Test
+ public void shouldThrowCoreExceptionForInvalidNodeType2Level() {
+ thrown.expect(CoreException.class);
+ thrown.expectMessage(
+ "Entity Type 'A' or one of its derivedFrom type hierarchy, is not defined in tosca " + "service model");
+ String typeToMatch = "A";
+ when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
+ Map<String, NodeType> stNodeTypes = new HashMap<>();
+ addNodeType(stNodeTypes, "notImportant", new NodeType());
+ addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
+ addNodeType(stNodeTypes, "ADerivedFromB'", createNodeType("BDerivedFromC"));
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setNode_types(stNodeTypes);
+ assertTrue(toscaAnalyzerService
+ .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNotDerivedFromRequestedTypeBut2ndLevelDerivedFromMatch() {
+ String typeToMatch = "A";
+ when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
+ Map<String, NodeType> stNodeTypes = new HashMap<>();
+ addNodeType(stNodeTypes, "notImportant", new NodeType());
+ addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
+ addNodeType(stNodeTypes, "ADerivedFromB", createNodeType("BDerivedFromC"));
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setNode_types(stNodeTypes);
+ assertTrue(toscaAnalyzerService
+ .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
+ }
+
+ private NodeType createNodeType(String derivedFrom) {
+ NodeType nodeType = new NodeType();
+ nodeType.setDerived_from(derivedFrom);
+ return nodeType;
+ }
+
+ private DataType createDataType(String derivedFrom) {
+ DataType dataType = new DataType();
+ dataType.setDerived_from(derivedFrom);
+ return dataType;
+ }
+
+ private InterfaceType createInterfaceType(String derivedFrom) {
+ InterfaceType interfaceType = new InterfaceType();
+ interfaceType.setDerived_from(derivedFrom);
+ return interfaceType;
+ }
+
+ private void addNodeType(Map<String, NodeType> stNodeTypes, String key, NodeType nodeType) {
+ stNodeTypes.put(key, nodeType);
+ }
+
+ private void addDataType(Map<String, DataType> stDataTypes, String key, DataType dataType) {
+ stDataTypes.put(key, dataType);
+ }
+
+ @Test
+ public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn1stLevelImports() {
+ String typeToMatch = ToscaNodeType.CINDER_VOLUME;
+ when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
+ List<Map<String, Import>> imports = new ArrayList<>();
+ Map<String, Import> importMap = new HashMap<>();
+ Import anImport = new Import();
+ anImport.setFile("mainImport");
+ importMap.put("bla bla", anImport);
+ imports.add(importMap);
+ ServiceTemplate mainST = new ServiceTemplate();
+ mainST.setImports(imports);
+
+ //create searchable service template
+ Map<String, NodeType> stNodeTypes = new HashMap<>();
+ addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
+ NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
+ addNodeType(stNodeTypes, typeToMatch, nodeType);
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setNode_types(stNodeTypes);
+
+ // add service templates to tosca service model
+ Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
+ serviceTemplates.put("testMainServiceTemplate", mainST);
+ serviceTemplates.put("mainImport", serviceTemplate);
+ when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
+
+ assertTrue(toscaAnalyzerService.isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainST,
+ toscaServiceModelMock));
+ }
+
+ @Test
+ public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn2ndLevelImports() {
+ String typeToMatch = ToscaNodeType.CINDER_VOLUME;
+ when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
+ List<Map<String, Import>> imports = new ArrayList<>();
+ Map<String, Import> importMap = new HashMap<>();
+ Import anImport = new Import();
+ anImport.setFile("refToMainImport");
+ importMap.put("bla bla", anImport);
+ imports.add(importMap);
+ ServiceTemplate mainST = new ServiceTemplate();
+ mainST.setImports(imports);
+
+ //create searchable service template
+ Map<String, NodeType> stNodeTypes = new HashMap<>();
+ addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
+ NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
+ addNodeType(stNodeTypes, typeToMatch, nodeType);
+ ServiceTemplate serviceTemplate = new ServiceTemplate();
+ serviceTemplate.setNode_types(stNodeTypes);
+
+ // create 1st level service template with import only
+ List<Map<String, Import>> firstLevelImports = new ArrayList<>();
+ Map<String, Import> firstLevelImportsMap = new HashMap<>();
+ Import firstLevelImport = new Import();
+ firstLevelImport.setFile("mainImport");
+ firstLevelImportsMap.put("bla bla 2", firstLevelImport);
+ firstLevelImports.add(firstLevelImportsMap);
+ ServiceTemplate firstLevelST = new ServiceTemplate();
+ firstLevelST.setImports(firstLevelImports);
+
+ // add service templates to tosca service model
+ Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
+ serviceTemplates.put("testMainServiceTemplate", mainST);
+ serviceTemplates.put("refToMainImport", firstLevelST);
+ serviceTemplates.put("mainImport", serviceTemplate);
+ when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
+
+ assertTrue(toscaAnalyzerService.isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainST,
+ toscaServiceModelMock));
+ }
+ // not found at all should throw core exception
}
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml
new file mode 100644
index 0000000000..4abc7ca681
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml
@@ -0,0 +1,232 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+metadata:
+ template_name: nested
+imports:
+- NovaServerGlobalTypes:
+ file: NovaServerGlobalTypesServiceTemplate.yaml
+node_types:
+ org.openecomp.resource.vfc.nodes.heat.cmaui_image:
+ derived_from: org.openecomp.resource.vfc.nodes.heat.nova.Server
+ properties:
+ admin_pass:
+ description: The administrator password for the server
+ type: string
+ status: SUPPORTED
+ default: overridden default value
+ required: false
+ new_property:
+ description: new property
+ type: string
+ status: SUPPORTED
+ required: false
+ interfaces:
+ Standard:
+ type: tosca.interfaces.node.lifecycle.Standard
+ inputs:
+ url_path:
+ type: string
+ interfaceID:
+ type: string
+ create:
+ inputs:
+ peering:
+ type: string
+ config:
+ inputs:
+ name:
+ type: string
+ org.openecomp.resource.vfc.nodes.heat.cmaui_image_extend:
+ derived_from: org.openecomp.resource.vfc.nodes.heat.cmaui_image
+ interfaces:
+ Standard:
+ inputs:
+ url_path:
+ type: string
+ required: false
+ type: tosca.interfaces.node.lifecycle.Standard
+ create:
+ inputs:
+ peeringSessions:
+ type: string
+ name:
+ type: string
+ start:
+ inputs:
+ time:
+ type: string
+
+data_types:
+ org.openecomp.datatypes.heat.network.MyAddressPair:
+ derived_from: org.openecomp.datatypes.heat.network.AddressPair
+ description: My MAC/IP address pairs
+ properties:
+ mac_address:
+ description: MAC address
+ type: string
+ status: SUPPORTED
+ required: false
+ default: overridden default value
+ new_property:
+ description: new property
+ type: string
+ status: SUPPORTED
+ required: false
+ org.openecomp.datatypes.heat.network.MyNewAddressPair:
+ derived_from: org.openecomp.datatypes.heat.network.MyAddressPair
+ description: My new MAC/IP address pairs
+ properties:
+ mac_address:
+ description: MAC address
+ type: string
+ status: SUPPORTED
+ required: true
+ default: overridden default value
+topology_template:
+ inputs:
+ cmaui_names:
+ hidden: false
+ immutable: false
+ type: list
+ description: CMAUI1, CMAUI2 server names
+ entry_schema:
+ type: String
+ p1:
+ hidden: false
+ immutable: false
+ type: string
+ description: UID of OAM network
+ cmaui_image:
+ hidden: false
+ immutable: false
+ type: string
+ description: Image for CMAUI server
+ cmaui_flavor:
+ hidden: false
+ immutable: false
+ type: string
+ description: Flavor for CMAUI server
+ security_group_name:
+ hidden: false
+ immutable: false
+ description: not impotrtant
+ availability_zone_0:
+ label: availabilityzone name
+ hidden: false
+ immutable: false
+ type: string
+ description: availabilityzone name
+ node_templates:
+ server_cmaui:
+ type: org.openecomp.resource.vfc.nodes.heat.cmaui_image
+ properties:
+ flavor:
+ get_input: cmaui_flavor
+ availability_zone:
+ get_input: availability_zone_0
+ image:
+ get_input: cmaui_image
+ name:
+ get_input:
+ - cmaui_names
+ - 0
+ cmaui_port_0:
+ type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port
+ properties:
+ replacement_policy: AUTO
+ security_groups:
+ - get_input: security_group_name
+ fixed_ips:
+ - ip_address:
+ get_input:
+ - cmaui_oam_ips
+ - 0
+ network:
+ get_input: p1
+ requirements:
+ - binding:
+ capability: tosca.capabilities.network.Bindable
+ node: server_cmaui
+ relationship: tosca.relationships.network.BindsTo
+ cmaui1_port_1:
+ type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port
+ properties:
+ replacement_policy: AUTO
+ security_groups:
+ - get_input: security_group_name
+ fixed_ips:
+ - subnet: subnetNameVal
+ ip_address:
+ get_input:
+ - cmaui_oam_ips
+ - 1
+ - subnet: subnetNameVal2
+ ip_address:
+ get_input:
+ - cmaui_oam_ips
+ - 1
+ network: jsa_net
+ requirements:
+ - link:
+ capability: tosca.capabilities.network.Linkable
+ node: jsa_net1
+ relationship: tosca.relationships.network.LinksTo
+ - link:
+ capability: tosca.capabilities.network.Linkable
+ node: jsa_net2
+ relationship: tosca.relationships.network.LinksTo
+ - binding:
+ capability: tosca.capabilities.network.Bindable
+ node: server_cmaui
+ relationship: tosca.relationships.network.BindsTo
+ jsa_net1:
+ type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net
+ properties:
+ shared: true
+ network_name:
+ get_input: jsa_net_name
+ jsa_net2:
+ type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net
+ properties:
+ shared: true
+ network_name:
+ get_input: jsa_net_name
+ groups:
+ nested:
+ type: org.openecomp.groups.heat.HeatStack
+ properties:
+ heat_file: ../Artifacts/nested.yml
+ description: cmaui server template for vMMSC
+ members:
+ - server_cmaui
+ - cmaui_port_0
+ substitution_mappings:
+ node_type: org.openecomp.resource.abstract.nodes.heat.nested
+ capabilities:
+ host_server_cmaui:
+ - server_cmaui
+ - host
+ os_server_cmaui:
+ - server_cmaui
+ - os
+ endpoint_server_cmaui:
+ - server_cmaui
+ - endpoint
+ binding_server_cmaui:
+ - server_cmaui
+ - binding
+ scalable_server_cmaui:
+ - server_cmaui
+ - scalable
+ attachment_cmaui_port_0:
+ - cmaui_port_0
+ - attachment
+ requirements:
+ local_storage_server_cmaui:
+ - server_cmaui
+ - local_storage
+ link_cmaui_port_0:
+ - cmaui_port_0
+ - link
+ link_cmaui_port_invalid:
+ - cmaui_port_9
+ - link
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/CommonGlobalTypesServiceTemplate.yaml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/CommonGlobalTypesServiceTemplate.yaml
index 1a183e9c50..5b85d5047b 100644
--- a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/CommonGlobalTypesServiceTemplate.yaml
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/CommonGlobalTypesServiceTemplate.yaml
@@ -3,6 +3,9 @@ metadata:
template_name: CommonGlobalTypes
template_version: 1.0.0
description: TOSCA Global Types
+imports:
+- toscaIndex:
+ file: _index.yml
data_types:
org.openecomp.datatypes.heat.network.AddressPair:
derived_from: tosca.datatypes.Root
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/_index.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/_index.yml
new file mode 100644
index 0000000000..1ad0aa3a2d
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/_index.yml
@@ -0,0 +1,37 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: _index.yml
+ version: '1.0'
+
+imports:
+- capabilities:
+ file: capabilities.yml
+- nodes:
+ file: nodes.yml
+- relationships:
+ file: relationships.yml
+- groups:
+ file: groups.yml
+- data:
+ file: data.yml
+- interfaces:
+ file: interfaces.yml
+- artifacts:
+ file: artifacts.yml
+- policies:
+ file: policies.yml \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/artifacts.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/artifacts.yml
new file mode 100644
index 0000000000..8f69e5ebb7
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/artifacts.yml
@@ -0,0 +1,55 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: artifacts.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+artifact_types:
+ tosca.artifacts.Root:
+ description: This is the default (root) TOSCA Artifact Type definition that all other TOSCA base Artifact Types derive from.
+
+ tosca.artifacts.Deployment.Image:
+ derived_from: tosca.artifacts.Deployment
+ description: This artifact type represents a parent type for any "image" which is an opaque packaging of a TOSCA Node's deployment (whether real or virtual) whose contents are typically already installed and pre-configured (i.e., "stateful") and prepared to be run on a known target container.
+
+ tosca.artifacts.Implementation.Bash:
+ derived_from: tosca.artifacts.Implementation
+ description: This artifact type represents a Bash script type that contains Bash commands that can be executed on the Unix Bash shell.
+
+ tosca.artifacts.Deployment.Image.VM:
+ derived_from: tosca.artifacts.Deployment
+ description: This artifact represents the parent type for all Virtual Machine (VM) image and container formatted deployment artifacts. These images contain a stateful capture of a machine (e.g., server) including operating system and installed software along with any configurations and can be run on another machine using a hypervisor which virtualizes typical server (i.e., hardware) resources.
+
+ tosca.artifacts.Implementation.Python:
+ derived_from: tosca.artifacts.Implementation
+ description: This artifact type represents a Python file that contains Python language constructs that can be executed within a Python interpreter.
+
+ tosca.artifacts.Deployment:
+ derived_from: tosca.artifacts.Root
+ description: This artifact type represents the parent type for all deployment artifacts in TOSCA. This class of artifacts typically represents a binary packaging of an application or service that is used to install/create or deploy it as part of a node's lifecycle.
+
+ tosca.artifacts.File:
+ derived_from: tosca.artifacts.Root
+ description: This artifact type is used when an artifact definition needs to have its associated file simply treated as a file and no special handling/handlers are invoked (i.e., it is not treated as either an implementation or deployment artifact type).
+
+ tosca.artifacts.Implementation:
+ derived_from: tosca.artifacts.Root
+ description: This artifact type represents the parent type for all implementation artifacts in TOSCA. These artifacts are used to implement operations of TOSCA interfaces either directly (e.g., scripts) or indirectly (e.g., config. files).
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/capabilities.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/capabilities.yml
new file mode 100644
index 0000000000..31653d927a
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/capabilities.yml
@@ -0,0 +1,230 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: capabilities.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+capability_types:
+ tosca.capabilities.Root:
+ description: This is the default (root) TOSCA Capability Type definition that all other TOSCA Capability Types derive from.
+
+ tosca.capabilities.Node:
+ derived_from: tosca.capabilities.Root
+ description: The Node capability indicates the base capabilities of a TOSCA Node Type.
+
+ tosca.capabilities.Container:
+ derived_from: tosca.capabilities.Root
+ description: The Container capability, when included on a Node Type or Template definition, indicates that the node can act as a container for (or a host for) one or more other declared Node Types.
+ properties:
+ num_cpus:
+ description: Number of (actual or virtual) CPUs associated with the Compute node.
+ type: integer
+ required: false
+ constraints:
+ - greater_or_equal: 1
+ cpu_frequency:
+ description: Specifies the operating frequency of CPU's core. This property expresses the expected frequency of one (1) CPU as provided by the property "num_cpus".
+ type: scalar-unit.frequency
+ required: false
+ constraints:
+ - greater_or_equal: 0.1 GHz
+ disk_size:
+ description: Size of the local disk available to applications running on the Compute node (default unit is MB).
+ type: scalar-unit.size
+ required: false
+ constraints:
+ - greater_or_equal: 0 MB
+ mem_size:
+ description: Size of memory available to applications running on the Compute node (default unit is MB).
+ type: scalar-unit.size
+ required: false
+ constraints:
+ - greater_or_equal: 0 MB
+
+ tosca.capabilities.Endpoint:
+ derived_from: tosca.capabilities.Root
+ description: This is the default TOSCA type that should be used or extended to define a network endpoint capability. This includes the information to express a basic endpoint with a single port or a complex endpoint with multiple ports. By default the Endpoint is assumed to represent an address on a private network unless otherwise specified.
+ properties:
+ protocol:
+ description: 'The name of the protocol (i.e., the protocol prefix) that the
+ endpoint accepts (any OSI Layer 4-7 protocols). Examples: http, https, ftp,
+ tcp, udp, etc.'
+ type: string
+ default: tcp
+ required: true
+ port:
+ description: The optional port of the endpoint.
+ type: tosca.datatypes.network.PortDef
+ required: false
+ secure:
+ description: Requests for the endpoint to be secure and use credentials supplied on the ConnectsTo relationship.
+ type: boolean
+ default: false
+ required: false
+ url_path:
+ description: The optional URL path of the endpoint's address if applicable for the protocol.
+ type: string
+ required: false
+ port_name:
+ description: The optional name (or ID) of the network port this endpoint should be bound to.
+ type: string
+ required: false
+ network_name:
+ description: 'The optional name (or ID) of the network this endpoint should
+ be bound to. network_name: PRIVATE | PUBLIC | <network_name> | <network_id>.'
+ type: string
+ default: PRIVATE
+ required: false
+ initiator:
+ description: The optional indicator of the direction of the connection.
+ type: string
+ default: source
+ required: false
+ constraints:
+ - valid_values:
+ - source
+ - target
+ - peer
+ ports:
+ description: The optional map of ports the Endpoint supports (if more than one).
+ type: map
+ entry_schema:
+ type: tosca.datatypes.network.PortSpec
+ required: false
+ constraints:
+ - min_length: 1
+ attributes:
+ ip_address:
+ description: 'Note: This is the IP address as propagated up by the associated
+ node''s host (Compute) container.'
+ type: string
+
+ tosca.capabilities.Endpoint.Public:
+ derived_from: tosca.capabilities.Endpoint
+ description: |-
+ This capability represents a public endpoint which is accessible to the general internet (and its public IP address ranges).
+ This public endpoint capability also can be used to create a floating (IP) address that the underlying network assigns from a pool allocated from the application's underlying public network. This floating address is managed by the underlying network such that can be routed an application's private address and remains reliable to internet clients.
+ properties:
+ network_name:
+ type: string
+ default: PUBLIC
+ constraints:
+ - equal: PUBLIC
+
+ tosca.capabilities.Endpoint.Admin:
+ derived_from: tosca.capabilities.Endpoint
+ description: This is the default TOSCA type that should be used or extended to define a specialized administrator endpoint capability.
+ properties:
+ secure:
+ description: Requests for the endpoint to be secure and use credentials supplied on the ConnectsTo relationship.
+ type: boolean
+ default: true
+ constraints:
+ - equal: true
+
+ tosca.capabilities.Endpoint.Database:
+ derived_from: tosca.capabilities.Endpoint
+ description: This is the default TOSCA type that should be used or extended to define a specialized database endpoint capability.
+
+ tosca.capabilities.Attachment:
+ derived_from: tosca.capabilities.Root
+ description: This is the default TOSCA type that should be used or extended to define an attachment capability of a (logical) infrastructure device node (e.g., BlockStorage node).
+
+ tosca.capabilities.OperatingSystem:
+ derived_from: tosca.capabilities.Root
+ description: This is the default TOSCA type that should be used to express an Operating System capability for a node.
+ properties:
+ architecture:
+ description: 'The Operating System (OS) architecture. Examples of valid values
+ include: x86_32, x86_64, etc.'
+ type: string
+ required: false
+ type:
+ description: 'The Operating System (OS) type. Examples of valid values include:
+ linux, aix, mac, windows, etc.'
+ type: string
+ required: false
+ distribution:
+ description: 'The Operating System (OS) distribution. Examples of valid values
+ for a "type" of "Linux" would include: debian, fedora, rhel and ubuntu.'
+ type: string
+ required: false
+ version:
+ description: The Operating System version.
+ type: version
+ required: false
+
+ tosca.capabilities.Scalable:
+ derived_from: tosca.capabilities.Root
+ description: This is the default TOSCA type that should be used to express a scalability capability for a node.
+ properties:
+ min_instances:
+ description: This property is used to indicate the minimum number of instances that should be created for the associated TOSCA Node Template by a TOSCA orchestrator.
+ type: integer
+ default: 1
+ max_instances:
+ description: This property is used to indicate the maximum number of instances that should be created for the associated TOSCA Node Template by a TOSCA orchestrator.
+ type: integer
+ default: 1
+ default_instances:
+ description: 'An optional property that indicates the requested default number
+ of instances that should be the starting number of instances a TOSCA orchestrator
+ should attempt to allocate. Note: The value for this property MUST be in
+ the range between the values set for "min_instances" and "max_instances"
+ properties.'
+ type: integer
+ required: false
+
+ tosca.capabilities.network.Bindable:
+ derived_from: tosca.capabilities.Node
+ description: A node type that includes the Bindable capability indicates that it can be bound to a logical network association via a network port.
+
+ tosca.capabilities.network.Linkable:
+ derived_from: tosca.capabilities.Node
+ description: A node type that includes the Linkable capability indicates that it can be pointed by tosca.relationships.network.LinksTo relationship type.
+
+ tosca.capabilities.Container.Docker:
+ derived_from: tosca.capabilities.Container
+ properties:
+ version:
+ type: list
+ entry_schema:
+ type: version
+ required: false
+ publish_all:
+ type: boolean
+ default: false
+ required: false
+ publish_ports:
+ type: list
+ entry_schema:
+ type: PortSpec
+ required: false
+ expose_ports:
+ type: list
+ entry_schema:
+ type: PortSpec
+ required: false
+ volumes:
+ type: list
+ entry_schema:
+ type: string
+ required: false
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/data.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/data.yml
new file mode 100644
index 0000000000..3197845dfd
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/data.yml
@@ -0,0 +1,191 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: data.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+data_types:
+ tosca.datatypes.Root:
+ description: The TOSCA root Data Type all other TOSCA base Data Types derive from
+
+ string:
+ derived_from: tosca.datatypes.Root
+
+ integer:
+ derived_from: tosca.datatypes.Root
+
+ boolean:
+ derived_from: tosca.datatypes.Root
+
+ float:
+ derived_from: tosca.datatypes.Root
+
+ range:
+ derived_from: tosca.datatypes.Root
+
+ list:
+ derived_from: tosca.datatypes.Root
+
+ map:
+ derived_from: tosca.datatypes.Root
+
+ timestamp:
+ derived_from: tosca.datatypes.Root
+
+ version:
+ derived_from: tosca.datatypes.Root
+
+ scalar-unit.size:
+ derived_from: tosca.datatypes.Root
+
+ scalar-unit.frequency:
+ derived_from: tosca.datatypes.Root
+
+ scalar-unit.time:
+ derived_from: tosca.datatypes.Root
+
+ tosca.datatypes.network.NetworkInfo:
+ derived_from: tosca.datatypes.Root
+ description: The Network type is a complex TOSCA data type used to describe logical network information.
+ properties:
+ network_name:
+ description: The name of the logical network. e.g., "public", "private", "admin". etc.
+ type: string
+ required: false
+ network_id:
+ description: The unique ID of for the network generated by the network provider.
+ type: string
+ required: false
+ addresses:
+ description: The list of IP addresses assigned from the underlying network.
+ type: list
+ entry_schema:
+ type: string
+ required: false
+
+ tosca.datatypes.TimeInterval:
+ derived_from: tosca.datatypes.Root
+ properties:
+ start_time:
+ type: timestamp
+ required: true
+ end_time:
+ type: timestamp
+ required: true
+
+ tosca.datatypes.network.PortSpec:
+ derived_from: tosca.datatypes.Root
+ description: The PortSpec type is a complex TOSCA data Type used when describing port specifications for a network connection.
+ properties:
+ protocol:
+ description: The required protocol used on the port.
+ type: string
+ default: tcp
+ constraints:
+ - valid_values:
+ - udp
+ - tcp
+ - igmp
+ source:
+ description: The optional source port.
+ type: tosca.datatypes.network.PortDef
+ required: false
+ source_range:
+ description: The optional range for source port.
+ type: range
+ required: false
+ constraints:
+ - in_range:
+ - 1
+ - 65535
+ target:
+ description: The optional target port.
+ type: tosca.datatypes.network.PortDef
+ required: false
+ target_range:
+ description: The optional range for target port.
+ type: range
+ required: false
+ constraints:
+ - in_range:
+ - 1
+ - 65535
+
+ tosca.datatypes.network.PortDef:
+ derived_from: integer
+ description: The PortDef type is a TOSCA data Type used to define a network port.
+ constraints:
+ - in_range:
+ - 1
+ - 65535
+
+ tosca.datatypes.network.PortInfo:
+ derived_from: tosca.datatypes.Root
+ description: The PortInfo type is a complex TOSCA data type used to describe network port information.
+ properties:
+ port_name:
+ description: The logical network port name.
+ type: string
+ required: false
+ port_id:
+ description: The unique ID for the network port generated by the network provider.
+ type: string
+ required: false
+ network_id:
+ description: The unique ID for the network.
+ type: string
+ required: false
+ mac_address:
+ description: The unique media access control address (MAC address) assigned to the port.
+ type: string
+ required: false
+ addresses:
+ description: The list of IP address(es) assigned to the port.
+ type: list
+ entry_schema:
+ type: string
+ required: false
+
+ tosca.datatypes.Credential:
+ derived_from: tosca.datatypes.Root
+ description: The Credential type is a complex TOSCA data Type used when describing authorization credentials used to access network accessible resources.
+ properties:
+ protocol:
+ description: The optional protocol name.
+ type: string
+ required: false
+ token_type:
+ description: The required token type.
+ type: string
+ default: password
+ token:
+ description: The required token used as a credential for authorization or access to a networked resource.
+ type: string
+ keys:
+ description: The optional list of protocol-specific keys or assertions.
+ type: map
+ entry_schema:
+ type: string
+ required: false
+ user:
+ description: The optional user (name or ID) used for non-token based credentials.
+ type: string
+ required: false
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/groups.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/groups.yml
new file mode 100644
index 0000000000..e7e7417baa
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/groups.yml
@@ -0,0 +1,30 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: groups.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+group_types:
+ tosca.groups.Root:
+ description: This is the default (root) TOSCA Group Type definition that all other TOSCA base Group Types derive from.
+ interfaces:
+ Standard:
+ type: tosca.interfaces.node.lifecycle.Standard
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/interfaces.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/interfaces.yml
new file mode 100644
index 0000000000..75a8760791
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/interfaces.yml
@@ -0,0 +1,61 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: interfaces.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+interface_types:
+ tosca.interfaces.Root:
+ description: This is the default (root) TOSCA Interface Type definition that all other TOSCA Interface Types derive from.
+
+ tosca.interfaces.node.lifecycle.Standard:
+ derived_from: tosca.interfaces.Root
+ description: This lifecycle interface defines the essential, normative operations that TOSCA nodes may support.
+ stop:
+ description: Standard lifecycle stop operation.
+ start:
+ description: Standard lifecycle start operation.
+ create:
+ description: Standard lifecycle create operation.
+ configure:
+ description: Standard lifecycle configure operation.
+ delete:
+ description: Standard lifecycle delete operation.
+
+ tosca.interfaces.relationship.Configure:
+ derived_from: tosca.interfaces.Root
+ description: The lifecycle interfaces define the essential, normative operations that each TOSCA Relationship Types may support.
+ pre_configure_source:
+ description: Operation to pre-configure the source endpoint.
+ pre_configure_target:
+ description: Operation to pre-configure the target endpoint.
+ post_configure_source:
+ description: Operation to post-configure the source endpoint.
+ post_configure_target:
+ description: Operation to post-configure the target endpoint.
+ add_target:
+ description: Operation to notify the source node of a target node being added via a relationship.
+ add_source:
+ description: Operation to notify the target node of a source node which is now available via a relationship.
+ target_changed:
+ description: Operation to notify source some property or attribute of the target changed
+ remove_target:
+ description: Operation to remove a target node. \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/nodes.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/nodes.yml
new file mode 100644
index 0000000000..ec06d6dd52
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/nodes.yml
@@ -0,0 +1,371 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: nodes.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+node_types:
+ tosca.nodes.Root:
+ description: The TOSCA Root Node Type is the default type that all other TOSCA base Node Types derive from. This allows for all TOSCA nodes to have a consistent set of features for modeling and management (e.g., consistent definitions for requirements, capabilities and lifecycle interfaces).
+ attributes:
+ tosca_id:
+ description: A unique identifier of the realized instance of a Node Template that derives from any TOSCA normative type.
+ type: string
+ tosca_name:
+ description: This attribute reflects the name of the Node Template as defined in the TOSCA service template. This name is not unique to the realized instance model of corresponding deployed application as each template in the model can result in one or more instances (e.g., scaled) when orchestrated to a provider environment.
+ type: string
+ state:
+ description: The state of the node instance.
+ type: string
+ default: initial
+ capabilities:
+ feature:
+ type: tosca.capabilities.Node
+ requirements:
+ - dependency:
+ capability: tosca.capabilities.Node
+ node: tosca.nodes.Root
+ relationship: tosca.relationships.DependsOn
+ occurrences:
+ - 0
+ - UNBOUNDED
+ interfaces:
+ Standard:
+ type: tosca.interfaces.node.lifecycle.Standard
+
+ tosca.nodes.ObjectStorage:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA ObjectStorage node represents storage that provides the ability to store data as objects (or BLOBs of data) without consideration for the underlying filesystem or devices.
+ properties:
+ name:
+ description: The logical name of the object store (or container).
+ type: string
+ size:
+ description: The requested initial storage size (default unit is in Gigabytes).
+ type: scalar-unit.size
+ required: false
+ constraints:
+ - greater_or_equal: 0 GB
+ maxsize:
+ description: The requested maximum storage size (default unit is in Gigabytes).
+ type: scalar-unit.size
+ required: false
+ constraints:
+ - greater_or_equal: 0 GB
+ capabilities:
+ storage_endpoint:
+ type: tosca.capabilities.Endpoint
+
+ tosca.nodes.DBMS:
+ derived_from: tosca.nodes.SoftwareComponent
+ description: The TOSCA DBMS node represents a typical relational, SQL Database Management System software component or service.
+ properties:
+ root_password:
+ description: The optional root password for the DBMS server.
+ type: string
+ required: false
+ port:
+ description: The DBMS server's port.
+ type: integer
+ required: false
+ capabilities:
+ host:
+ type: tosca.capabilities.Container
+ valid_source_types:
+ - tosca.nodes.Database
+
+ tosca.nodes.WebApplication:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA WebApplication node represents a software application that can be managed and run by a TOSCA WebServer node. Specific types of web applications such as Java, etc. could be derived from this type.
+ properties:
+ context_root:
+ description: The web application's context root which designates the application's URL path within the web server it is hosted on.
+ type: string
+ required: false
+ capabilities:
+ app_endpoint:
+ type: tosca.capabilities.Endpoint
+ requirements:
+ - host:
+ capability: tosca.capabilities.Container
+ node: tosca.nodes.WebServer
+ relationship: tosca.relationships.HostedOn
+
+ tosca.nodes.Compute:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA Compute node represents one or more real or virtual processors of software applications or services along with other essential local resources. Collectively, the resources the compute node represents can logically be viewed as a (real or virtual) "server".
+ attributes:
+ private_address:
+ description: The primary private IP address assigned by the cloud provider that applications may use to access the Compute node.
+ type: string
+ public_address:
+ description: The primary public IP address assigned by the cloud provider that applications may use to access the Compute node.
+ type: string
+ networks:
+ description: The list of logical networks assigned to the compute host instance and information about them.
+ type: map
+ entry_schema:
+ type: tosca.datatypes.network.NetworkInfo
+ ports:
+ description: The list of logical ports assigned to the compute host instance and information about them.
+ type: map
+ entry_schema:
+ type: tosca.datatypes.network.PortInfo
+ capabilities:
+ host:
+ type: tosca.capabilities.Container
+ valid_source_types:
+ - tosca.nodes.SoftwareComponent
+ binding:
+ type: tosca.capabilities.network.Bindable
+ os:
+ type: tosca.capabilities.OperatingSystem
+ scalable:
+ type: tosca.capabilities.Scalable
+ endpoint:
+ type: tosca.capabilities.Endpoint.Admin
+ requirements:
+ - local_storage:
+ capability: tosca.capabilities.Attachment
+ node: tosca.nodes.BlockStorage
+ relationship: tosca.relationships.AttachesTo
+ occurrences:
+ - 0
+ - UNBOUNDED
+
+ tosca.nodes.network.Network:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA Network node represents a simple, logical network service.
+ properties:
+ ip_version:
+ description: The IP version of the requested network.
+ type: integer
+ default: 4
+ required: false
+ constraints:
+ - valid_values:
+ - 4
+ - 6
+ cidr:
+ description: The cidr block of the requested network.
+ type: string
+ required: false
+ start_ip:
+ description: The IP address to be used as the 1st one in a pool of addresses derived from the cidr block full IP range.
+ type: string
+ required: false
+ end_ip:
+ description: The IP address to be used as the last one in a pool of addresses derived from the cidr block full IP range.
+ type: string
+ required: false
+ gateway_ip:
+ description: The gateway IP address.
+ type: string
+ required: false
+ network_name:
+ description: An Identifier that represents an existing Network instance in the underlying cloud infrastructure - OR - be used as the name of the new created network.
+ type: string
+ required: false
+ network_id:
+ description: An Identifier that represents an existing Network instance in the underlying cloud infrastructure. This property is mutually exclusive with all other properties except network_name.
+ type: string
+ required: false
+ segmentation_id:
+ description: A segmentation identifier in the underlying cloud infrastructure (e.g., VLAN id, GRE tunnel id). If the segmentation_id is specified, the network_type or physical_network properties should be provided as well.
+ type: string
+ required: false
+ network_type:
+ description: Optionally, specifies the nature of the physical network in the underlying cloud infrastructure. Examples are flat, vlan, gre or vxlan. For flat and vlan types, physical_network should be provided too.
+ type: string
+ required: false
+ physical_network:
+ description: Optionally, identifies the physical network on top of which the network is implemented, e.g. physnet1. This property is required if network_type is flat or vlan.
+ type: string
+ required: false
+ dhcp_enabled:
+ description: Indicates the TOSCA container to create a virtual network instance with or without a DHCP service.
+ type: boolean
+ default: true
+ required: false
+ capabilities:
+ link:
+ type: tosca.capabilities.network.Linkable
+
+ tosca.nodes.WebServer:
+ derived_from: tosca.nodes.SoftwareComponent
+ description: This TOSCA WebServer Node Type represents an abstract software component or service that is capable of hosting and providing management operations for one or more WebApplication nodes.
+ capabilities:
+ data_endpoint:
+ type: tosca.capabilities.Endpoint
+ admin_endpoint:
+ type: tosca.capabilities.Endpoint.Admin
+ host:
+ type: tosca.capabilities.Container
+ valid_source_types:
+ - tosca.nodes.WebApplication
+
+ tosca.nodes.Container.Application:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA Container Application node represents an application that requires Container-level virtualization technology.
+ requirements:
+ - host:
+ capability: tosca.capabilities.Container
+ relationship: tosca.relationships.HostedOn
+
+ tosca.nodes.Container.Runtime:
+ derived_from: tosca.nodes.SoftwareComponent
+ description: The TOSCA Container Runtime node represents operating system-level virtualization technology used to run multiple application services on a single Compute host.
+ capabilities:
+ host:
+ type: tosca.capabilities.Container
+ scalable:
+ type: tosca.capabilities.Scalable
+
+ tosca.nodes.SoftwareComponent:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA SoftwareComponent node represents a generic software component that can be managed and run by a TOSCA Compute Node Type.
+ properties:
+ component_version:
+ description: The optional software component's version.
+ type: version
+ required: false
+ admin_credential:
+ description: The optional credential that can be used to authenticate to the software component.
+ type: tosca.datatypes.Credential
+ required: false
+ requirements:
+ - host:
+ capability: tosca.capabilities.Container
+ node: tosca.nodes.Compute
+ relationship: tosca.relationships.HostedOn
+
+ tosca.nodes.BlockStorage:
+ derived_from: tosca.nodes.Root
+ description: ''
+ properties:
+ size:
+ description: The requested storage size (default unit is MB).
+ type: scalar-unit.size
+ constraints:
+ - greater_or_equal: 1 MB
+ volume_id:
+ description: ID of an existing volume (that is in the accessible scope of the requesting application).
+ type: string
+ required: false
+ snapshot_id:
+ description: Some identifier that represents an existing snapshot that should be used when creating the block storage (volume).
+ type: string
+ required: false
+ capabilities:
+ attachment:
+ type: tosca.capabilities.Attachment
+
+ tosca.nodes.network.Port:
+ derived_from: tosca.nodes.Root
+ description: |-
+ The TOSCA Port node represents a logical entity that associates between Compute and Network normative types.
+ The Port node type effectively represents a single virtual NIC on the Compute node instance.
+ properties:
+ ip_address:
+ description: Allow the user to set a fixed IP address. Note that this address is a request to the provider which they will attempt to fulfill but may not be able to dependent on the network the port is associated with.
+ type: string
+ required: false
+ order:
+ description: 'The order of the NIC on the compute instance (e.g. eth2). Note:
+ when binding more than one port to a single compute (aka multi vNICs) and
+ ordering is desired, it is *mandatory* that all ports will be set with an
+ order value and. The order values must represent a positive, arithmetic
+ progression that starts with 0 (e.g. 0, 1, 2, ..., n).'
+ type: integer
+ default: 0
+ required: false
+ constraints:
+ - greater_or_equal: 0
+ is_default:
+ description: Set is_default=true to apply a default gateway route on the running compute instance to the associated network gateway. Only one port that is associated to single compute node can set as default=true.
+ type: boolean
+ default: false
+ required: false
+ ip_range_start:
+ description: Defines the starting IP of a range to be allocated for the compute instances that are associated by this Port. Without setting this property the IP allocation is done from the entire CIDR block of the network.
+ type: string
+ required: false
+ ip_range_end:
+ description: Defines the ending IP of a range to be allocated for the compute instances that are associated by this Port. Without setting this property the IP allocation is done from the entire CIDR block of the network.
+ type: string
+ required: false
+ attributes:
+ ip_address:
+ description: The IP address would be assigned to the associated compute instance.
+ type: string
+ requirements:
+ - link:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ - binding:
+ capability: tosca.capabilities.network.Bindable
+ relationship: tosca.relationships.network.BindsTo
+
+ tosca.nodes.LoadBalancer:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA Load Balancer node represents logical function that be used in conjunction with a Floating Address to distribute an application's traffic (load) across a number of instances of the application (e.g., for a clustered or scaled application).
+ capabilities:
+ client:
+ description: The Floating (IP) client's on the public network can connect to.
+ type: tosca.capabilities.Endpoint.Public
+ occurrences:
+ - 0
+ - UNBOUNDED
+ requirements:
+ - application:
+ capability: tosca.capabilities.Endpoint
+ relationship: tosca.relationships.RoutesTo
+ occurrences:
+ - 0
+ - UNBOUNDED
+
+ tosca.nodes.Database:
+ derived_from: tosca.nodes.Root
+ description: The TOSCA Database node represents a logical database that can be managed and hosted by a TOSCA DBMS node.
+ properties:
+ name:
+ description: The logical database Name.
+ type: string
+ port:
+ description: The port the database service will use to listen for incoming data and requests.
+ type: integer
+ required: false
+ user:
+ description: The special user account used for database administration.
+ type: string
+ required: false
+ password:
+ description: The password associated with the user account provided in the 'user' property.
+ type: string
+ required: false
+ capabilities:
+ database_endpoint:
+ type: tosca.capabilities.Endpoint.Database
+ requirements:
+ - host:
+ capability: tosca.capabilities.Container
+ node: tosca.nodes.DBMS
+ relationship: tosca.relationships.HostedOn
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/policies.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/policies.yml
new file mode 100644
index 0000000000..e2819c5360
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/policies.yml
@@ -0,0 +1,43 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: policies.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+policy_types:
+ tosca.policies.Root:
+ description: This is the default (root) TOSCA Policy Type definition that all other TOSCA base Policy Types derive from.
+
+ tosca.policies.Update:
+ derived_from: tosca.policies.Root
+ description: This is the default (root) TOSCA Policy Type definition that is used to govern update of TOSCA nodes or groups of nodes.
+
+ tosca.policies.Placement:
+ derived_from: tosca.policies.Root
+ description: This is the default (root) TOSCA Policy Type definition that is used to govern placement of TOSCA nodes or groups of nodes.
+
+ tosca.policies.Performance:
+ derived_from: tosca.policies.Root
+ description: This is the default (root) TOSCA Policy Type definition that is used to declare performance requirements for TOSCA nodes or groups of nodes.
+
+ tosca.policies.Scaling:
+ derived_from: tosca.policies.Root
+ description: This is the default (root) TOSCA Policy Type definition that is used to govern scaling of TOSCA nodes or groups of nodes.
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/relationships.yml b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/relationships.yml
new file mode 100644
index 0000000000..648626ba7c
--- /dev/null
+++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/resources/mock/globalServiceTemplates/relationships.yml
@@ -0,0 +1,106 @@
+#
+# 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.
+#
+
+tosca_definitions_version: tosca_simple_yaml_1_1
+
+metadata:
+ filename: relationships.yml
+ version: '1.0'
+
+imports:
+- tosca_index:
+ file: _index.yml
+
+relationship_types:
+ tosca.relationships.Root:
+ description: This is the default (root) TOSCA Relationship Type definition that all other TOSCA Relationship Types derive from.
+ attributes:
+ tosca_id:
+ description: A unique identifier of the realized instance of a Relationship Template that derives from any TOSCA normative type.
+ type: string
+ tosca_name:
+ description: This attribute reflects the name of the Relationship Template as defined in the TOSCA service template. This name is not unique to the realized instance model of corresponding deployed application as each template in the model can result in one or more instances (e.g., scaled) when orchestrated to a provider environment.
+ type: string
+ state:
+ description: The state of the relationship instance.
+ type: string
+ default: initial
+ interfaces:
+ Configure:
+ type: tosca.interfaces.relationship.Configure
+
+ tosca.relationships.RoutesTo:
+ derived_from: tosca.relationships.ConnectsTo
+ description: This type represents an intentional network routing between two Endpoints in different networks.
+ valid_target_types:
+ - tosca.capabilities.Endpoint
+
+ tosca.relationships.network.LinksTo:
+ derived_from: tosca.relationships.DependsOn
+ description: This relationship type represents an association relationship between Port and Network node types.
+ valid_target_types:
+ - tosca.capabilities.network.Linkable
+
+ tosca.relationships.AttachesTo:
+ derived_from: tosca.relationships.Root
+ description: This type represents an attachment relationship between two nodes. For example, an AttachesTo relationship type would be used for attaching a storage node to a Compute node.
+ valid_target_types:
+ - tosca.capabilities.Attachment
+ properties:
+ location:
+ description: 'The relative location (e.g., path on the file system), which
+ provides the root location to address an attached node. e.g., a mount point
+ / path such as ''/usr/data''. Note: The user must provide it and it cannot
+ be "root".'
+ type: string
+ constraints:
+ - min_length: 1
+ device:
+ description: The logical device name which for the attached device (which is represented by the target node in the model). e.g., '/dev/hda1'.
+ type: string
+ required: false
+ attributes:
+ device:
+ description: 'The logical name of the device as exposed to the instance. Note:
+ A runtime property that gets set when the model gets instantiated by the
+ orchestrator.'
+ type: string
+
+ tosca.relationships.network.BindsTo:
+ derived_from: tosca.relationships.DependsOn
+ description: This type represents a network association relationship between Port and Compute node types.
+ valid_target_types:
+ - tosca.capabilities.network.Bindable
+
+ tosca.relationships.HostedOn:
+ derived_from: tosca.relationships.Root
+ description: This type represents a hosting relationship between two nodes.
+ valid_target_types:
+ - tosca.capabilities.Container
+
+ tosca.relationships.DependsOn:
+ derived_from: tosca.relationships.Root
+ description: This type represents a general dependency relationship between two nodes.
+ valid_target_types:
+ - tosca.capabilities.Node
+
+ tosca.relationships.ConnectsTo:
+ derived_from: tosca.relationships.Root
+ description: This type represents a network connection relationship between two nodes.
+ valid_target_types:
+ - tosca.capabilities.Endpoint
+ properties:
+ credential:
+ type: tosca.datatypes.Credential
+ required: false