Fix 'Substitution Node not updated during import'-bug
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / csar / YamlTemplateParsingHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22
23 package org.openecomp.sdc.be.components.csar;
24
25 import static java.util.stream.Collectors.toList;
26 import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.QUOTE;
27 import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
28 import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
29 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaListElement;
30 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement;
31 import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement;
32 import static org.openecomp.sdc.be.components.impl.ImportUtils.loadYamlAsStrictMap;
33 import static org.openecomp.sdc.be.model.tosca.ToscaType.STRING;
34 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS;
35 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ATTRIBUTES;
36 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITIES;
37 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITY;
38 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE;
39 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DESCRIPTION;
40 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.FILE;
41 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GET_INPUT;
42 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GROUPS;
43 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IMPLEMENTATION;
44 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.INPUTS;
45 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.INTERFACES;
46 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD;
47 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS;
48 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE;
49 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES;
50 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TYPE;
51 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.OPERATIONS;
52 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.OUTPUTS;
53 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES;
54 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES;
55 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.RELATIONSHIP;
56 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.RELATIONSHIP_TEMPLATES;
57 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS;
58 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_FILTERS;
59 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS;
60 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS;
61 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE;
62 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE;
63 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES;
64
65 import com.att.aft.dme2.internal.gson.reflect.TypeToken;
66 import com.google.common.collect.Lists;
67 import com.google.common.collect.Maps;
68 import com.google.gson.Gson;
69 import fj.data.Either;
70 import java.lang.reflect.Type;
71 import java.util.ArrayList;
72 import java.util.Collection;
73 import java.util.Collections;
74 import java.util.EnumMap;
75 import java.util.HashMap;
76 import java.util.LinkedHashMap;
77 import java.util.List;
78 import java.util.Map;
79 import java.util.Map.Entry;
80 import java.util.Objects;
81 import java.util.Optional;
82 import java.util.Set;
83 import java.util.UUID;
84 import java.util.stream.Collectors;
85 import org.apache.commons.collections.CollectionUtils;
86 import org.apache.commons.collections.MapUtils;
87 import org.apache.commons.lang3.StringUtils;
88 import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
89 import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
90 import org.openecomp.sdc.be.components.impl.ImportUtils;
91 import org.openecomp.sdc.be.components.impl.NodeFilterUploadCreator;
92 import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
93 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
94 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
95 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
96 import org.openecomp.sdc.be.config.BeEcompErrorManager;
97 import org.openecomp.sdc.be.dao.api.ActionStatus;
98 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
99 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
100 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
101 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
102 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
103 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
104 import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;
105 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
106 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
107 import org.openecomp.sdc.be.datatypes.elements.PropertyFilterConstraintDataDefinition;
108 import org.openecomp.sdc.be.datatypes.elements.SubPropertyToscaFunction;
109 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterPropertyDataDefinition;
110 import org.openecomp.sdc.be.datatypes.elements.ToscaFunction;
111 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
112 import org.openecomp.sdc.be.datatypes.elements.ToscaFunctionType;
113 import org.openecomp.sdc.be.datatypes.enums.ConstraintType;
114 import org.openecomp.sdc.be.datatypes.enums.FilterValueType;
115 import org.openecomp.sdc.be.datatypes.enums.PropertyFilterTargetType;
116 import org.openecomp.sdc.be.model.CapabilityDefinition;
117 import org.openecomp.sdc.be.model.Component;
118 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
119 import org.openecomp.sdc.be.model.GroupDefinition;
120 import org.openecomp.sdc.be.model.GroupTypeDefinition;
121 import org.openecomp.sdc.be.model.InputDefinition;
122 import org.openecomp.sdc.be.model.NodeTypeInfo;
123 import org.openecomp.sdc.be.model.OutputDefinition;
124 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
125 import org.openecomp.sdc.be.model.PolicyDefinition;
126 import org.openecomp.sdc.be.model.PolicyTypeDefinition;
127 import org.openecomp.sdc.be.model.PropertyDefinition;
128 import org.openecomp.sdc.be.model.Resource;
129 import org.openecomp.sdc.be.model.UploadArtifactInfo;
130 import org.openecomp.sdc.be.model.UploadAttributeInfo;
131 import org.openecomp.sdc.be.model.UploadCapInfo;
132 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
133 import org.openecomp.sdc.be.model.UploadInterfaceInfo;
134 import org.openecomp.sdc.be.model.UploadPropInfo;
135 import org.openecomp.sdc.be.model.UploadReqInfo;
136 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
137 import org.openecomp.sdc.be.tosca.model.ToscaInterfaceDefinition;
138 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
139 import org.openecomp.sdc.be.ui.model.OperationUi;
140 import org.openecomp.sdc.be.ui.model.PropertyAssignmentUi;
141 import org.openecomp.sdc.be.utils.PropertyFilterConstraintDataDefinitionHelper;
142 import org.openecomp.sdc.be.utils.TypeUtils;
143 import org.openecomp.sdc.common.log.wrappers.Logger;
144 import org.yaml.snakeyaml.parser.ParserException;
145
146 /**
147  * A handler class designed to parse the YAML file of the service template for a JAVA object
148  */
149 @org.springframework.stereotype.Component
150 public class YamlTemplateParsingHandler {
151
152     private static final int SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX = 0;
153     private static final int SUB_MAPPING_CAPABILITY_NAME_IDX = 1;
154     private static final Logger log = Logger.getLogger(YamlTemplateParsingHandler.class);
155     private final Gson gson = new Gson();
156     private final JanusGraphDao janusGraphDao;
157     private final GroupTypeBusinessLogic groupTypeBusinessLogic;
158     private final AnnotationBusinessLogic annotationBusinessLogic;
159     private final PolicyTypeBusinessLogic policyTypeBusinessLogic;
160     private final ServiceBusinessLogic serviceBusinessLogic;
161     private final ToscaFunctionYamlParsingHandler toscaFunctionYamlParsingHandler;
162
163     public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao,
164                                       GroupTypeBusinessLogic groupTypeBusinessLogic,
165                                       AnnotationBusinessLogic annotationBusinessLogic,
166                                       PolicyTypeBusinessLogic policyTypeBusinessLogic,
167                                       ServiceBusinessLogic serviceBusinessLogic,
168                                       final ToscaFunctionYamlParsingHandler toscaFunctionYamlParsingHandler
169     ) {
170         this.janusGraphDao = janusGraphDao;
171         this.groupTypeBusinessLogic = groupTypeBusinessLogic;
172         this.annotationBusinessLogic = annotationBusinessLogic;
173         this.policyTypeBusinessLogic = policyTypeBusinessLogic;
174         this.serviceBusinessLogic = serviceBusinessLogic;
175         this.toscaFunctionYamlParsingHandler = toscaFunctionYamlParsingHandler;
176     }
177
178     public ParsedToscaYamlInfo parseResourceInfoFromYAML(String fileName, String resourceYml, Map<String, String> createdNodesToscaResourceNames,
179                                                          Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName,
180                                                          Component component, String interfaceTemplateYaml) {
181         log.debug("#parseResourceInfoFromYAML - Going to parse yaml {} ", fileName);
182         Map<String, Object> mappedToscaTemplate = getMappedToscaTemplate(fileName, resourceYml, nodeTypesInfo, nodeName);
183         ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
184         Map<String, Object> mappedTopologyTemplate = (Map<String, Object>) findToscaElement(mappedToscaTemplate, TOPOLOGY_TEMPLATE,
185             ToscaElementTypeEnum.ALL).left().on(err -> failIfNotTopologyTemplate(fileName));
186         final Map<String, Object> mappedTopologyTemplateInputs = mappedTopologyTemplate.entrySet().stream()
187             .filter(entry -> entry.getKey().equals(INPUTS.getElementName())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
188         final Map<String, Object> mappedTopologyTemplateOutputs = mappedTopologyTemplate.entrySet().stream()
189             .filter(entry -> entry.getKey().equals(OUTPUTS.getElementName())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
190         parsedToscaYamlInfo.setInputs(getInputs(mappedTopologyTemplateInputs));
191         parsedToscaYamlInfo.setOutputs(getOutputs(mappedTopologyTemplateOutputs));
192         parsedToscaYamlInfo.setInstances(getInstances(
193             mappedToscaTemplate,
194             createdNodesToscaResourceNames
195         ));
196         associateRelationshipTemplatesToInstances(parsedToscaYamlInfo.getInstances(), mappedTopologyTemplate);
197         parsedToscaYamlInfo.setGroups(getGroups(mappedToscaTemplate, component.getModel()));
198         parsedToscaYamlInfo.setPolicies(getPolicies(mappedToscaTemplate, component.getModel()));
199         Map<String, Object> substitutionMappings = getSubstitutionMappings(mappedToscaTemplate);
200         if (substitutionMappings != null) {
201             if (component.isService()) {
202                 if (interfaceTemplateYaml.isEmpty()) {
203                     List<PropertyDefinition> properties = serviceBusinessLogic.fetchDerivedFromGenericType(component, null).getProperties();
204                     parsedToscaYamlInfo.setProperties(properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, prop -> prop)));
205                 } else {
206                     parsedToscaYamlInfo.setProperties(getProperties(loadYamlAsStrictMap(interfaceTemplateYaml)));
207                 }
208                 parsedToscaYamlInfo.setSubstitutionFilterProperties(getSubstitutionFilterProperties(mappedToscaTemplate));
209             }
210             if (substitutionMappings.get("properties") != null) {
211                 parsedToscaYamlInfo.setSubstitutionMappingProperties((Map<String, List<String>>) substitutionMappings.get("properties"));
212             }
213             parsedToscaYamlInfo.setSubstitutionMappingNodeType((String) substitutionMappings.get(NODE_TYPE.getElementName()));
214         }
215         log.debug("#parseResourceInfoFromYAML - The yaml {} has been parsed ", fileName);
216         return parsedToscaYamlInfo;
217     }
218
219     private Map<String, Object> getMappedToscaTemplate(String fileName, String resourceYml, Map<String, NodeTypeInfo> nodeTypesInfo,
220                                                        String nodeName) {
221         Map<String, Object> mappedToscaTemplate;
222         if (isNodeExist(nodeTypesInfo, nodeName)) {
223             mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
224         } else {
225             mappedToscaTemplate = loadYaml(fileName, resourceYml);
226         }
227         return mappedToscaTemplate;
228     }
229
230     private Map<String, Object> loadYaml(String fileName, String resourceYml) {
231         Map<String, Object> mappedToscaTemplate = null;
232         try {
233             mappedToscaTemplate = loadYamlAsStrictMap(resourceYml);
234         } catch (ParserException e) {
235             log.debug("#getMappedToscaTemplate - Failed to load YAML file {}", fileName, e);
236             rollbackWithException(ActionStatus.TOSCA_PARSE_ERROR, fileName, e.getMessage());
237         }
238         return mappedToscaTemplate;
239     }
240
241     private boolean isNodeExist(Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
242         return nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName);
243     }
244
245     private Map<String, InputDefinition> getInputs(Map<String, Object> toscaJson) {
246         Map<String, InputDefinition> inputs = ImportUtils.getInputs(toscaJson, annotationBusinessLogic.getAnnotationTypeOperations()).left()
247             .on(err -> new HashMap<>());
248         annotationBusinessLogic.validateAndMergeAnnotationsAndAssignToInput(inputs);
249         return inputs;
250     }
251
252     private Map<String, OutputDefinition> getOutputs(Map<String, Object> toscaJson) {
253         return ImportUtils.getOutputs(toscaJson).left().on(err -> new HashMap<>());
254     }
255
256     private Map<String, PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
257         return ImportUtils.getProperties(toscaJson).left().on(err -> new HashMap<>());
258     }
259
260     private ListDataDefinition<SubstitutionFilterPropertyDataDefinition> getSubstitutionFilterProperties(Map<String, Object> toscaJson) {
261         ListDataDefinition<SubstitutionFilterPropertyDataDefinition> propertyList = new ListDataDefinition<>();
262         Map<String, Object> substitutionFilters = findFirstToscaMapElement(toscaJson, SUBSTITUTION_FILTERS).left().on(err -> new HashMap<>());
263         if (MapUtils.isEmpty(substitutionFilters)) {
264             return propertyList;
265         }
266         ArrayList<Map<String, List<Map<String, Object>>>> substitutionFilterProperties =
267             (ArrayList<Map<String, List<Map<String, Object>>>>) substitutionFilters.get("properties");
268         if (CollectionUtils.isEmpty(substitutionFilterProperties)) {
269             return propertyList;
270         }
271         for (Map<String, List<Map<String, Object>>> filterProps : substitutionFilterProperties) {
272             for (Map.Entry<String, List<Map<String, Object>>> propertyFilterEntry : filterProps.entrySet()) {
273                 final String propertyName = propertyFilterEntry.getKey();
274                 for (Map<String, Object> filterValueMap : propertyFilterEntry.getValue()) {
275                     final var substitutionFilterPropertyDataDefinition = new SubstitutionFilterPropertyDataDefinition();
276                     substitutionFilterPropertyDataDefinition.setName(propertyName);
277                     substitutionFilterPropertyDataDefinition.setConstraints(createSubstitutionFilterConstraints(propertyName, filterValueMap));
278                     propertyList.add(substitutionFilterPropertyDataDefinition);
279                 }
280             }
281         }
282         return propertyList;
283     }
284
285     private List<PropertyFilterConstraintDataDefinition> createSubstitutionFilterConstraints(final String name, final Map<String, Object> value) {
286         final List<PropertyFilterConstraintDataDefinition> constraints = new ArrayList<>();
287         for (final Map.Entry<String, Object> valueEntry : value.entrySet()) {
288             final var propertyFilterConstraint = new PropertyFilterConstraintDataDefinition();
289             propertyFilterConstraint.setPropertyName(name);
290             propertyFilterConstraint.setOperator(ConstraintType.findByType(valueEntry.getKey()).orElse(null));
291             propertyFilterConstraint.setTargetType(PropertyFilterTargetType.PROPERTY);
292             final Optional<ToscaFunction> toscaFunction = PropertyFilterConstraintDataDefinitionHelper
293                 .createToscaFunctionFromLegacyConstraintValue(valueEntry.getValue());
294             if (toscaFunction.isPresent()) {
295                 final ToscaFunction toscaFunction1 = toscaFunction.get();
296                 propertyFilterConstraint.setValue(toscaFunction1);
297                 propertyFilterConstraint.setValueType(
298                     PropertyFilterConstraintDataDefinitionHelper.convertFromToscaFunctionType(toscaFunction1.getType()).orElse(null)
299                 );
300             } else {
301                 propertyFilterConstraint.setValue(valueEntry.getValue());
302                 propertyFilterConstraint.setValueType(FilterValueType.STATIC);
303             }
304             constraints.add(propertyFilterConstraint);
305         }
306
307         return constraints;
308     }
309
310     private Map<String, PolicyDefinition> getPolicies(Map<String, Object> toscaJson, String model) {
311         Map<String, Object> mappedTopologyTemplate = (Map<String, Object>) findToscaElement(toscaJson, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL)
312             .left().on(err -> new HashMap<>());
313         Map<String, Object> foundPolicies = (Map<String, Object>) mappedTopologyTemplate.get(POLICIES.getElementName());
314         if (MapUtils.isNotEmpty(foundPolicies)) {
315             return foundPolicies.entrySet().stream().map(policyToCreate -> createPolicy(policyToCreate, model))
316                 .collect(Collectors.toMap(PolicyDefinition::getName, p -> p));
317         }
318         return Collections.emptyMap();
319     }
320
321     private PolicyDefinition createPolicy(Map.Entry<String, Object> policyNameValue, String model) {
322         PolicyDefinition emptyPolicyDef = new PolicyDefinition();
323         String policyName = policyNameValue.getKey();
324         emptyPolicyDef.setName(policyName);
325         try {
326             // There's no need to null test in conjunction with an instanceof test. null is not an instanceof anything, so a null check is redundant.
327             if (policyNameValue.getValue() instanceof Map) {
328                 Map<String, Object> policyTemplateJsonMap = (Map<String, Object>) policyNameValue.getValue();
329                 validateAndFillPolicy(emptyPolicyDef, policyTemplateJsonMap, model);
330             } else {
331                 rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
332             }
333         } catch (ClassCastException e) {
334             log.debug("#createPolicy - Failed to create the policy {}. The exception occurred", policyName, e);
335             rollbackWithException(ActionStatus.INVALID_YAML);
336         }
337         return emptyPolicyDef;
338     }
339
340     private void validateAndFillPolicy(PolicyDefinition emptyPolicyDefinition, Map<String, Object> policyTemplateJsonMap, String model) {
341         String policyTypeName = (String) policyTemplateJsonMap.get(TYPE.getElementName());
342         if (StringUtils.isEmpty(policyTypeName)) {
343             log.debug("#validateAndFillPolicy - The 'type' member is not found under policy {}", emptyPolicyDefinition.getName());
344             rollbackWithException(ActionStatus.POLICY_MISSING_POLICY_TYPE, emptyPolicyDefinition.getName());
345         }
346         emptyPolicyDefinition.setType(policyTypeName);
347         // set policy targets
348         emptyPolicyDefinition.setTargets(validateFillPolicyTargets(policyTemplateJsonMap));
349         PolicyTypeDefinition policyTypeDefinition = validateGetPolicyTypeDefinition(policyTypeName, model);
350         // set policy properties
351         emptyPolicyDefinition.setProperties(validateFillPolicyProperties(policyTypeDefinition, policyTemplateJsonMap));
352     }
353
354     private PolicyTypeDefinition validateGetPolicyTypeDefinition(String policyType, String modelName) {
355         PolicyTypeDefinition policyTypeDefinition = policyTypeBusinessLogic.getLatestPolicyTypeByType(policyType, modelName);
356         if (policyTypeDefinition == null) {
357             log.debug("#validateAndFillPolicy - The policy type {} not found", policyType);
358             rollbackWithException(ActionStatus.POLICY_TYPE_IS_INVALID, policyType);
359         }
360         return policyTypeDefinition;
361     }
362
363     private List<PropertyDataDefinition> validateFillPolicyProperties(final PolicyTypeDefinition policyTypeDefinition,
364                                                                       final Map<String, Object> policyTemplateJsonMap) {
365         if (policyTypeDefinition == null || CollectionUtils.isEmpty(policyTypeDefinition.getProperties())
366             || MapUtils.isEmpty(policyTemplateJsonMap)) {
367             return Collections.emptyList();
368         }
369         final Map<String, Object> propertiesJsonMap = (Map<String, Object>) policyTemplateJsonMap.get(PROPERTIES.getElementName());
370         if (MapUtils.isEmpty(propertiesJsonMap)) {
371             return Collections.emptyList();
372         }
373         return propertiesJsonMap.entrySet().stream()
374             .map(propertyJson -> {
375                 final PropertyDefinition originalProperty =
376                     policyTypeDefinition.getProperties().stream()
377                         .filter(propertyDefinition -> propertyDefinition.getName().equals(propertyJson.getKey()))
378                         .findFirst()
379                         .orElse(null);
380                 if (originalProperty == null) {
381                     return null;
382                 }
383                 final UploadPropInfo uploadPropInfo = buildProperty(propertyJson.getKey(), propertyJson.getValue());
384                 final PropertyDefinition propertyDefinition = new PropertyDefinition(originalProperty);
385                 propertyDefinition.setToscaFunction(uploadPropInfo.getToscaFunction());
386                 propertyDefinition.setSubPropertyToscaFunctions(uploadPropInfo.getSubPropertyToscaFunctions());
387                 propertyDefinition.setGetInputValues(uploadPropInfo.getGet_input());
388                 propertyDefinition.setDescription(uploadPropInfo.getDescription());
389                 String propertyValue = gson.toJson(uploadPropInfo.getValue());
390                 if (!propertyDefinition.isToscaFunction()) {
391                     propertyValue = PropertiesUtils.trimQuotes(propertyValue);
392                 }
393                 propertyDefinition.setValue(propertyValue);
394                 return propertyDefinition;
395             })
396             .filter(Objects::nonNull)
397             .collect(Collectors.toList());
398     }
399
400     private Map<PolicyTargetType, List<String>> validateFillPolicyTargets(Map<String, Object> policyTemplateJson) {
401         Map<PolicyTargetType, List<String>> targets = new EnumMap<>(PolicyTargetType.class);
402         if (policyTemplateJson.containsKey(TARGETS.getElementName()) && policyTemplateJson.get(TARGETS.getElementName()) instanceof List) {
403             List<String> targetsElement = (List<String>) policyTemplateJson.get(TARGETS.getElementName());
404             targets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsElement);
405         }
406         return targets;
407     }
408
409     private Map<String, UploadComponentInstanceInfo> getInstances(
410         Map<String, Object> toscaJson,
411         Map<String, String> createdNodesToscaResourceNames
412     ) {
413         Map<String, Object> nodeTemplates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES)
414             .left().on(err -> new HashMap<>());
415         if (nodeTemplates.isEmpty()) {
416             return Collections.emptyMap();
417         }
418         return getInstances(
419             toscaJson,
420             createdNodesToscaResourceNames,
421             nodeTemplates
422         );
423     }
424
425     private Map<String, UploadComponentInstanceInfo> getInstances(
426         Map<String, Object> toscaJson,
427         Map<String, String> createdNodesToscaResourceNames,
428         Map<String, Object> nodeTemplates
429     ) {
430         Map<String, Object> substitutionMappings = getSubstitutionMappings(toscaJson);
431         return nodeTemplates.entrySet().stream()
432             .map(node -> buildModuleComponentInstanceInfo(
433                 node,
434                 substitutionMappings,
435                 createdNodesToscaResourceNames
436             ))
437             .collect(Collectors.toMap(UploadComponentInstanceInfo::getName, i -> i));
438     }
439
440     private Map<String, Object> getSubstitutionMappings(Map<String, Object> toscaJson) {
441         Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = findFirstToscaMapElement(toscaJson, SUBSTITUTION_MAPPINGS);
442         if (eitherSubstitutionMappings.isLeft()) {
443             return eitherSubstitutionMappings.left().value();
444         }
445         return null;
446     }
447
448     private void associateRelationshipTemplatesToInstances(final Map<String, UploadComponentInstanceInfo> instances,
449                                                            final Map<String, Object> toscaJson) {
450         if (MapUtils.isEmpty(instances)) {
451             return;
452         }
453         for (UploadComponentInstanceInfo instance : instances.values()) {
454             final Map<String, List<OperationUi>> operations = new HashMap<>();
455             final Map<String, List<UploadReqInfo>> requirements = instance.getRequirements();
456             if (MapUtils.isNotEmpty(requirements)) {
457                 requirements.values()
458                     .forEach(requirementInfoList -> requirementInfoList.stream()
459                         .filter(requirement -> StringUtils.isNotEmpty(requirement.getRelationshipTemplate()))
460                         .forEach(requirement -> operations.put(requirement.getRelationshipTemplate(),
461                             getOperationsFromRelationshipTemplate(toscaJson, requirement.getRelationshipTemplate()))));
462             }
463             instance.setOperations(operations);
464         }
465     }
466
467     private Map<String, Object> getRelationshipTemplates(final Map<String, Object> toscaJson, final String relationshipTemplate) {
468         final Either<Map<String, Object>, ResultStatusEnum> eitherRelationshipTemplates = findFirstToscaMapElement(toscaJson, RELATIONSHIP_TEMPLATES);
469         if (eitherRelationshipTemplates.isRight()) {
470             throw new ByActionStatusComponentException(ActionStatus.RELATIONSHIP_TEMPLATE_NOT_FOUND);
471         }
472         final Map<String, Object> relationshipTemplateMap = eitherRelationshipTemplates.left().value();
473         final Map<String, Map<String, Object>> relationship = (Map<String, Map<String, Object>>) relationshipTemplateMap.get(relationshipTemplate);
474         if (relationship == null) {
475             throw new ByActionStatusComponentException(ActionStatus.RELATIONSHIP_TEMPLATE_DEFINITION_NOT_FOUND);
476         }
477         return relationship.get(INTERFACES.getElementName());
478     }
479
480     private List<ToscaInterfaceDefinition> buildToscaInterfacesFromRelationship(final Map<String, Object> interfaces) {
481         return interfaces.entrySet().stream()
482             .map(entry -> {
483                 final var toscaInterfaceDefinition = new ToscaInterfaceDefinition();
484                 toscaInterfaceDefinition.setType(entry.getKey());
485                 final Map<String, Object> toscaInterfaceMap = (Map<String, Object>) entry.getValue();
486                 toscaInterfaceDefinition.setOperations((Map<String, Object>) toscaInterfaceMap.get(OPERATIONS.getElementName()));
487                 return toscaInterfaceDefinition;
488             })
489             .collect(toList());
490     }
491
492     private Optional<Object> getImplementation(final Map<String, Object> operationToscaMap) {
493         if (MapUtils.isEmpty(operationToscaMap) || !operationToscaMap.containsKey(IMPLEMENTATION.getElementName())) {
494             return Optional.empty();
495         }
496         return Optional.ofNullable(operationToscaMap.get(IMPLEMENTATION.getElementName()));
497     }
498
499     private List<PropertyAssignmentUi> getOperationsInputs(final Map<String, Object> operationToscaMap) {
500         if (MapUtils.isEmpty(operationToscaMap) || !operationToscaMap.containsKey(INPUTS.getElementName())) {
501             return Collections.emptyList();
502         }
503         final Map<String, Object> inputsMap = (Map<String, Object>) operationToscaMap.get(INPUTS.getElementName());
504         return inputsMap.entrySet().stream().map(this::buildInputAssignment).collect(toList());
505     }
506
507     private PropertyAssignmentUi buildInputAssignment(final Entry<String, Object> inputAssignmentMap) {
508         var propertyAssignmentUi = new PropertyAssignmentUi();
509         propertyAssignmentUi.setName(inputAssignmentMap.getKey());
510         propertyAssignmentUi.setValue(inputAssignmentMap.getValue().toString());
511         propertyAssignmentUi.setType(STRING.getType());
512         return propertyAssignmentUi;
513     }
514
515     private List<OperationUi> getOperationsFromRelationshipTemplate(final Map<String, Object> toscaJson, final String relationshipTemplate) {
516         final List<OperationUi> operationUiList = new ArrayList<>();
517         final List<ToscaInterfaceDefinition> interfaces =
518             buildToscaInterfacesFromRelationship(getRelationshipTemplates(toscaJson, relationshipTemplate));
519         interfaces.stream()
520             .filter(interfaceDefinition -> MapUtils.isNotEmpty(interfaceDefinition.getOperations()))
521             .forEach(interfaceDefinition ->
522                 interfaceDefinition.getOperations()
523                     .forEach((operationType, operationValue) ->
524                         operationUiList.add(buildOperation(interfaceDefinition.getType(), operationType, (Map<String, Object>) operationValue))
525                     ));
526         return operationUiList;
527     }
528
529     private OperationUi buildOperation(final String interfaceType, final String operationType, final Map<String, Object> operationToscaMap) {
530         var operationUi = new OperationUi();
531         operationUi.setInterfaceType(interfaceType);
532         operationUi.setOperationType(operationType);
533         getImplementation(operationToscaMap).ifPresent(operationUi::setImplementation);
534         final List<PropertyAssignmentUi> operationsInputs = getOperationsInputs(operationToscaMap);
535         if (CollectionUtils.isNotEmpty(operationsInputs)) {
536             operationUi.setInputs(operationsInputs);
537         }
538         return operationUi;
539     }
540
541     @SuppressWarnings("unchecked")
542     private Map<String, GroupDefinition> getGroups(Map<String, Object> toscaJson, String model) {
543         Map<String, Object> mappedTopologyTemplate = (Map<String, Object>) findToscaElement(toscaJson, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL)
544             .left().on(err -> new HashMap<>());
545         Map<String, Object> foundGroups = (Map<String, Object>) mappedTopologyTemplate.get(GROUPS.getElementName());
546         if (MapUtils.isNotEmpty(foundGroups)) {
547             Map<String, GroupDefinition> groups = foundGroups.entrySet().stream().map(groupToCreate -> createGroup(groupToCreate, model))
548                 .collect(Collectors.toMap(GroupDefinition::getName, g -> g));
549             Map<String, Object> substitutionMappings = getSubstitutionMappings(toscaJson);
550             if (capabilitiesSubstitutionMappingsExist(substitutionMappings)) {
551                 groups.forEach((key, value) -> updateCapabilitiesNames(value,
552                     getNamesToUpdate(key, (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName()))));
553             }
554             return groups;
555         }
556         return new HashMap<>();
557     }
558
559     private void updateCapabilitiesNames(GroupDefinition group, Map<String, String> capabilityNames) {
560         if (MapUtils.isNotEmpty(group.getCapabilities())) {
561             group.getCapabilities().values().stream().flatMap(Collection::stream).filter(cap -> capabilityNames.containsKey(cap.getName()))
562                 .forEach(cap -> cap.setName(capabilityNames.get(cap.getName())));
563         }
564     }
565
566     private Map<String, String> getNamesToUpdate(String name, Map<String, List<String>> pair) {
567         return pair.entrySet().stream().filter(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX).equalsIgnoreCase(name))
568             .collect(Collectors.toMap(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_NAME_IDX), Map.Entry::getKey, (n1, n2) -> n1));
569     }
570
571     private boolean capabilitiesSubstitutionMappingsExist(Map<String, Object> substitutionMappings) {
572         return substitutionMappings != null && substitutionMappings.containsKey(CAPABILITIES.getElementName());
573     }
574
575     private GroupDefinition createGroup(Map.Entry<String, Object> groupNameValue, String model) {
576         GroupDefinition group = new GroupDefinition();
577         group.setName(groupNameValue.getKey());
578         try {
579             if (groupNameValue.getValue() instanceof Map) {
580                 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupNameValue.getValue();
581                 validateAndFillGroup(group, groupTemplateJsonMap, model);
582                 validateUpdateGroupProperties(group, groupTemplateJsonMap);
583                 validateUpdateGroupCapabilities(group, groupTemplateJsonMap);
584             } else {
585                 rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
586             }
587         } catch (ClassCastException e) {
588             log.debug("#createGroup - Failed to create the group {}. The exception occurres", groupNameValue.getKey(), e);
589             rollbackWithException(ActionStatus.INVALID_YAML);
590         }
591         return group;
592     }
593
594     private Map<String, CapabilityDefinition> addCapabilities(Map<String, CapabilityDefinition> cap, Map<String, CapabilityDefinition> otherCap) {
595         cap.putAll(otherCap);
596         return cap;
597     }
598
599     private Map<String, CapabilityDefinition> addCapability(CapabilityDefinition cap) {
600         Map<String, CapabilityDefinition> map = Maps.newHashMap();
601         map.put(cap.getName(), cap);
602         return map;
603     }
604
605     private void setMembers(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
606         if (groupTemplateJsonMap.containsKey(MEMBERS.getElementName())) {
607             Object members = groupTemplateJsonMap.get(MEMBERS.getElementName());
608             if (members != null) {
609                 if (members instanceof List) {
610                     setMembersFromList(groupInfo, (List<?>) members);
611                 } else {
612                     log.debug("The 'members' member is not of type list under group {}", groupInfo.getName());
613                     rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
614                 }
615             }
616         }
617     }
618
619     private void setMembersFromList(GroupDefinition groupInfo, List<?> membersAsList) {
620         groupInfo.setMembers(membersAsList.stream().collect(Collectors.toMap(Object::toString, member -> "")));
621     }
622
623     @SuppressWarnings("unchecked")
624     private void validateUpdateGroupProperties(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
625         if (groupTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
626             Object propertiesElement = groupTemplateJsonMap.get(PROPERTIES.getElementName());
627             if (propertiesElement instanceof Map) {
628                 mergeGroupProperties(groupInfo, (Map<String, Object>) propertiesElement);
629             }
630         }
631     }
632
633     private void mergeGroupProperties(final GroupDefinition groupDefinition, final Map<String, Object> parsedProperties) {
634         if (CollectionUtils.isEmpty(groupDefinition.getProperties())) {
635             return;
636         }
637         validateGroupProperties(parsedProperties, groupDefinition);
638         groupDefinition.getProperties().stream()
639             .filter(property -> parsedProperties.containsKey(property.getName()))
640             .forEach(property -> mergeGroupProperty(property, parsedProperties.get(property.getName())));
641     }
642
643     private void mergeGroupProperty(final PropertyDataDefinition property, final Object propertyYaml) {
644         final UploadPropInfo uploadPropInfo = buildProperty(property.getName(), propertyYaml);
645         property.setToscaFunction(uploadPropInfo.getToscaFunction());
646         property.setSubPropertyToscaFunctions(uploadPropInfo.getSubPropertyToscaFunctions());
647         property.setValue(convertPropertyValue(ToscaPropertyType.isValidType(property.getType()), uploadPropInfo.getValue()));
648         property.setGetInputValues(uploadPropInfo.getGet_input());
649     }
650
651     private String convertPropertyValue(ToscaPropertyType type, Object value) {
652         String convertedValue = null;
653         if (value != null) {
654             if (type == null || value instanceof Map || value instanceof List) {
655                 convertedValue = gson.toJson(value);
656             } else {
657                 convertedValue = value.toString();
658             }
659         }
660         return convertedValue;
661     }
662
663     private void setDescription(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
664         if (groupTemplateJsonMap.containsKey(DESCRIPTION.getElementName())) {
665             groupInfo.setDescription((String) groupTemplateJsonMap.get(DESCRIPTION.getElementName()));
666         }
667     }
668
669     private void validateAndFillGroup(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap, String model) {
670         String type = (String) groupTemplateJsonMap.get(TYPE.getElementName());
671         if (StringUtils.isEmpty(type)) {
672             log.debug("#validateAndFillGroup - The 'type' member is not found under group {}", groupInfo.getName());
673             rollbackWithException(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupInfo.getName());
674         }
675         groupInfo.setType(type);
676         GroupTypeDefinition groupType = groupTypeBusinessLogic.getLatestGroupTypeByType(type, model);
677         if (groupType == null) {
678             log.debug("#validateAndFillGroup - The group type {} not found", groupInfo.getName());
679             rollbackWithException(ActionStatus.GROUP_TYPE_IS_INVALID, type);
680         }
681         groupInfo.convertFromGroupProperties(groupType.getProperties());
682         groupInfo.convertCapabilityDefinitions(groupType.getCapabilities());
683         setDescription(groupInfo, groupTemplateJsonMap);
684         setMembers(groupInfo, groupTemplateJsonMap);
685     }
686
687     @SuppressWarnings("unchecked")
688     private void validateUpdateGroupCapabilities(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
689         if (groupTemplateJsonMap.containsKey(CAPABILITIES.getElementName())) {
690             Object capabilities = groupTemplateJsonMap.get(CAPABILITIES.getElementName());
691             if (capabilities instanceof List) {
692                 validateUpdateCapabilities(groupInfo, ((List<Object>) capabilities).stream().map(o -> buildGroupCapability(groupInfo, o))
693                     .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
694             } else if (capabilities instanceof Map) {
695                 validateUpdateCapabilities(groupInfo,
696                     ((Map<String, Object>) capabilities).entrySet().stream().map(e -> buildGroupCapability(groupInfo, e))
697                         .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
698             } else {
699                 log.debug("#setCapabilities - Failed to import the capabilities of the group {}. ", groupInfo.getName());
700                 rollbackWithException(ActionStatus.INVALID_YAML);
701             }
702         }
703     }
704
705     private void validateUpdateCapabilities(GroupDefinition groupInfo, Map<String, Map<String, CapabilityDefinition>> capabilityInfo) {
706         validateGroupCapabilities(groupInfo, capabilityInfo);
707         groupInfo.updateCapabilitiesProperties(capabilityInfo);
708     }
709
710     private void validateGroupCapabilities(GroupDefinition group, Map<String, Map<String, CapabilityDefinition>> parsedCapabilities) {
711         if (MapUtils.isNotEmpty(parsedCapabilities)) {
712             if (MapUtils.isEmpty(group.getCapabilities())) {
713                 failOnMissingCapabilityTypes(group, Lists.newArrayList(parsedCapabilities.keySet()));
714             }
715             List<String> missingCapTypes = parsedCapabilities.keySet().stream().filter(ct -> !group.getCapabilities().containsKey(ct))
716                 .collect(toList());
717             if (CollectionUtils.isNotEmpty(missingCapTypes)) {
718                 failOnMissingCapabilityTypes(group, missingCapTypes);
719             }
720             group.getCapabilities().entrySet().forEach(e -> validateCapabilities(group, e.getValue(), parsedCapabilities.get(e.getKey())));
721         }
722     }
723
724     private void validateCapabilities(GroupDefinition group, List<CapabilityDefinition> capabilities,
725                                       Map<String, CapabilityDefinition> parsedCapabilities) {
726         List<String> allowedCapNames = capabilities.stream().map(CapabilityDefinition::getName).distinct().collect(toList());
727         List<String> missingCapNames = parsedCapabilities.keySet().stream().filter(c -> !allowedCapNames.contains(c)).collect(toList());
728         if (CollectionUtils.isNotEmpty(missingCapNames)) {
729             failOnMissingCapabilityNames(group, missingCapNames);
730         }
731         validateCapabilitiesProperties(capabilities, parsedCapabilities);
732     }
733
734     private void validateCapabilitiesProperties(List<CapabilityDefinition> capabilities, Map<String, CapabilityDefinition> parsedCapabilities) {
735         capabilities.forEach(c -> validateCapabilityProperties(c, parsedCapabilities.get(c.getName())));
736     }
737
738     private void validateCapabilityProperties(CapabilityDefinition capability, CapabilityDefinition parsedCapability) {
739         if (parsedCapability != null && parsedCapability.getProperties() != null) {
740             List<String> parsedPropertiesNames = parsedCapability.getProperties().stream().map(ComponentInstanceProperty::getName).collect(toList());
741             validateProperties(capability.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames,
742                 ActionStatus.PROPERTY_NOT_FOUND, capability.getName(), capability.getType());
743         }
744     }
745
746     private void validateGroupProperties(Map<String, Object> parsedProperties, GroupDefinition groupInfo) {
747         List<String> parsedPropertiesNames = new ArrayList<>(parsedProperties.keySet());
748         validateProperties(groupInfo.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames,
749             ActionStatus.GROUP_PROPERTY_NOT_FOUND, groupInfo.getName(), groupInfo.getType());
750     }
751
752     private void validateProperties(List<String> validProperties, List<String> parsedProperties, ActionStatus actionStatus, String name,
753                                     String type) {
754         if (CollectionUtils.isNotEmpty(parsedProperties)) {
755             verifyMissingProperties(actionStatus, name, type, parsedProperties.stream().filter(n -> !validProperties.contains(n)).collect(toList()));
756         }
757     }
758
759     private void verifyMissingProperties(ActionStatus actionStatus, String name, String type, List<String> missingProperties) {
760         if (CollectionUtils.isNotEmpty(missingProperties)) {
761             if (log.isDebugEnabled()) {
762                 log.debug("#validateProperties - Failed to validate properties. The properties {} are missing on {} of the type {}. ",
763                     missingProperties.toString(), name, type);
764             }
765             rollbackWithException(actionStatus, missingProperties.toString(), missingProperties.toString(), name, type);
766         }
767     }
768
769     @SuppressWarnings("unchecked")
770     private CapabilityDefinition buildGroupCapability(GroupDefinition groupInfo, Object capObject) {
771         if (!(capObject instanceof Map)) {
772             log.debug("#convertToGroupCapability - Failed to import the capability {}. ", capObject);
773             rollbackWithException(ActionStatus.INVALID_YAML);
774         }
775         return buildGroupCapability(groupInfo, ((Map<String, Object>) capObject).entrySet().iterator().next());
776     }
777
778     @SuppressWarnings("unchecked")
779     private CapabilityDefinition buildGroupCapability(GroupDefinition groupInfo, Map.Entry<String, Object> capEntry) {
780         CapabilityDefinition capability = new CapabilityDefinition();
781         capability.setOwnerType(CapabilityDataDefinition.OwnerType.GROUP);
782         capability.setName(capEntry.getKey());
783         capability.setParentName(capEntry.getKey());
784         capability.setOwnerId(groupInfo.getName());
785         if (!(capEntry.getValue() instanceof Map)) {
786             log.debug("#convertMapEntryToCapabilityDefinition - Failed to import the capability {}. ", capEntry.getKey());
787             rollbackWithException(ActionStatus.INVALID_YAML);
788         }
789         Map<String, Object> capabilityValue = (Map<String, Object>) capEntry.getValue();
790         String type = (String) capabilityValue.get(TYPE.getElementName());
791         if (StringUtils.isEmpty(type)) {
792             log.debug("#convertMapEntryToCapabilityDefinition - Failed to import the capability {}. Missing capability type. ", capEntry.getKey());
793             rollbackWithException(ActionStatus.INVALID_YAML);
794         }
795         capability.setType(type);
796         if (!(capabilityValue.get(PROPERTIES.getElementName()) instanceof Map)) {
797             log.debug("#convertMapEntryToCapabilityDefinition - Failed to import the capability {}. ", capEntry.getKey());
798             rollbackWithException(ActionStatus.INVALID_YAML);
799         }
800         Map<String, Object> properties = (Map<String, Object>) capabilityValue.get(PROPERTIES.getElementName());
801         capability.setProperties(properties.entrySet().stream().map(this::convertToProperty).collect(toList()));
802         return capability;
803     }
804
805     private ComponentInstanceProperty convertToProperty(Map.Entry<String, Object> e) {
806         ComponentInstanceProperty property = new ComponentInstanceProperty();
807         property.setName(e.getKey());
808         property.setValue((String) e.getValue());
809         return property;
810     }
811
812     @SuppressWarnings("unchecked")
813     private UploadComponentInstanceInfo buildModuleComponentInstanceInfo(
814         Map.Entry<String, Object> nodeTemplateJsonEntry,
815         Map<String, Object> substitutionMappings,
816         Map<String, String> createdNodesToscaResourceNames
817     ) {
818         UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
819         nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
820         try {
821             if (nodeTemplateJsonEntry.getValue() instanceof String) {
822                 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
823                 nodeTemplateInfo.setType(nodeTemplateJsonString);
824             } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
825                 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
826                 setToscaResourceType(createdNodesToscaResourceNames, nodeTemplateInfo, nodeTemplateJsonMap);
827                 setRequirements(nodeTemplateInfo, nodeTemplateJsonMap);
828                 setCapabilities(nodeTemplateInfo, nodeTemplateJsonMap);
829                 setArtifacts(nodeTemplateInfo, nodeTemplateJsonMap);
830                 updateProperties(nodeTemplateInfo, nodeTemplateJsonMap);
831                 updateAttributes(nodeTemplateInfo, nodeTemplateJsonMap);
832                 updateInterfaces(nodeTemplateInfo, nodeTemplateJsonMap);
833                 setDirectives(nodeTemplateInfo, nodeTemplateJsonMap);
834                 setNodeFilter(nodeTemplateInfo, nodeTemplateJsonMap);
835                 setSubstitutions(substitutionMappings, nodeTemplateInfo);
836                 setOccurrencesAndInstanceCount(nodeTemplateInfo, nodeTemplateJsonMap);
837             } else {
838                 rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
839             }
840         } catch (ClassCastException e) {
841             BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
842             log.debug("error when creating capability, message:{}", e.getMessage(), e);
843             rollbackWithException(ActionStatus.INVALID_YAML);
844         }
845         return nodeTemplateInfo;
846     }
847
848     @SuppressWarnings("unchecked")
849     private void setSubstitutions(Map<String, Object> substitutionMappings, UploadComponentInstanceInfo nodeTemplateInfo) {
850         if (substitutionMappings != null) {
851             if (substitutionMappings.containsKey(CAPABILITIES.getElementName())) {
852                 nodeTemplateInfo.setCapabilitiesNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(),
853                     (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName())));
854             }
855             if (substitutionMappings.containsKey(REQUIREMENTS.getElementName())) {
856                 nodeTemplateInfo.setRequirementsNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(),
857                     (Map<String, List<String>>) substitutionMappings.get(REQUIREMENTS.getElementName())));
858             }
859         }
860     }
861
862     private void updateProperties(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
863         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
864             Map<String, List<UploadPropInfo>> properties =
865                 buildPropModuleFromYaml((Map<String, Object>) nodeTemplateJsonMap.get(PROPERTIES.getElementName()));
866             if (!properties.isEmpty()) {
867                 nodeTemplateInfo.setProperties(properties);
868             }
869         }
870     }
871
872     private void updateAttributes(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
873         if (nodeTemplateJsonMap.containsKey(ATTRIBUTES.getElementName())) {
874             Map<String, UploadAttributeInfo> attributes = buildAttributeModuleFromYaml(nodeTemplateJsonMap);
875             if (!attributes.isEmpty()) {
876                 nodeTemplateInfo.setAttributes(attributes);
877             }
878         }
879     }
880
881     private void updateInterfaces(
882         UploadComponentInstanceInfo nodeTemplateInfo,
883         Map<String, Object> nodeTemplateJsonMap
884     ) {
885         if (nodeTemplateJsonMap.containsKey(INTERFACES.getElementName())) {
886             Map<String, UploadInterfaceInfo> interfaces = buildInterfacesModuleFromYaml(
887                 nodeTemplateJsonMap
888             );
889             if (!interfaces.isEmpty()) {
890                 nodeTemplateInfo.setInterfaces(interfaces);
891             }
892         }
893     }
894
895     private void setCapabilities(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
896         if (nodeTemplateJsonMap.containsKey(CAPABILITIES.getElementName())) {
897             Map<String, List<UploadCapInfo>> eitherCapRes = createCapModuleFromYaml(nodeTemplateJsonMap);
898             if (!eitherCapRes.isEmpty()) {
899                 nodeTemplateInfo.setCapabilities(eitherCapRes);
900             }
901         }
902     }
903
904     private void setArtifacts(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
905         if (nodeTemplateJsonMap.containsKey(ARTIFACTS.getElementName())) {
906             Map<String, Map<String, UploadArtifactInfo>> eitherArtifactsRes = createArtifactsModuleFromYaml(nodeTemplateJsonMap);
907             if (!eitherArtifactsRes.isEmpty()) {
908                 nodeTemplateInfo.setArtifacts(eitherArtifactsRes);
909             }
910         }
911     }
912
913     private void setRequirements(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
914         if (nodeTemplateJsonMap.containsKey(REQUIREMENTS.getElementName())) {
915             Map<String, List<UploadReqInfo>> regResponse = createReqModuleFromYaml(nodeTemplateJsonMap, nodeTemplateInfo.getName());
916             if (!regResponse.isEmpty()) {
917                 nodeTemplateInfo.setRequirements(regResponse);
918             }
919         }
920     }
921
922     private void setToscaResourceType(Map<String, String> createdNodesToscaResourceNames, UploadComponentInstanceInfo nodeTemplateInfo,
923                                       Map<String, Object> nodeTemplateJsonMap) {
924         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
925             String toscaResourceType = (String) nodeTemplateJsonMap.get(TYPE.getElementName());
926             if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
927                 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
928             }
929             nodeTemplateInfo.setType(toscaResourceType);
930         }
931     }
932
933     private void setDirectives(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
934         List<String> directives = (List<String>) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.DIRECTIVES.getElementName());
935         nodeTemplateInfo.setDirectives(directives);
936     }
937
938     private void setNodeFilter(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
939         if (nodeTemplateJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())) {
940             nodeTemplateInfo.setUploadNodeFilterInfo(new NodeFilterUploadCreator()
941                 .createNodeFilterData(nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())));
942         }
943     }
944
945     @SuppressWarnings("unchecked")
946     private void setOccurrencesAndInstanceCount(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
947         if (nodeTemplateJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
948             List<Object> occurrences = (List<Object>) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
949             nodeTemplateInfo.setMinOccurrences(occurrences.get(0).toString());
950             nodeTemplateInfo.setMaxOccurrences(occurrences.get(1).toString());
951         }
952         if (nodeTemplateJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.INSTANCE_COUNT.getElementName())) {
953             Object instanceCount = nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.INSTANCE_COUNT.getElementName());
954             if (instanceCount instanceof Map) {
955                 String instanceCountAsString = "{get_input:" + (String)((Map)instanceCount).get("get_input") + "}";
956                 nodeTemplateInfo.setInstanceCount(instanceCountAsString);
957             } else {
958                 nodeTemplateInfo.setInstanceCount(instanceCount.toString());
959             }
960         }
961     }
962
963     @SuppressWarnings("unchecked")
964     private Map<String, List<UploadReqInfo>> createReqModuleFromYaml(Map<String, Object> nodeTemplateJsonMap, String nodeName) {
965         Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<>();
966         Either<List<Object>, ResultStatusEnum> requirementsListRes = findFirstToscaListElement(nodeTemplateJsonMap, REQUIREMENTS);
967         if (requirementsListRes.isLeft()) {
968             for (Object jsonReqObj : requirementsListRes.left().value()) {
969                 String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
970                 Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
971                 addModuleNodeTemplateReq(moduleRequirements, reqJson, reqName, nodeName);
972             }
973         } else {
974             Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, REQUIREMENTS);
975             if (requirementsMapRes.isLeft()) {
976                 for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) {
977                     String reqName = entry.getKey();
978                     Object reqJson = entry.getValue();
979                     addModuleNodeTemplateReq(moduleRequirements, reqJson, reqName, nodeName);
980                 }
981             }
982         }
983         return moduleRequirements;
984     }
985
986     private void addModuleNodeTemplateReq(Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName,
987                                           String nodeName) {
988         UploadReqInfo requirement = buildModuleNodeTemplateReg(requirementJson, nodeName);
989         requirement.setName(requirementName);
990         if (moduleRequirements.containsKey(requirementName)) {
991             moduleRequirements.get(requirementName).add(requirement);
992         } else {
993             List<UploadReqInfo> list = new ArrayList<>();
994             list.add(requirement);
995             moduleRequirements.put(requirementName, list);
996         }
997     }
998
999     @SuppressWarnings("unchecked")
1000     private Map<String, Map<String, UploadArtifactInfo>> createArtifactsModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
1001         Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts = new HashMap<>();
1002         Either<List<Object>, ResultStatusEnum> artifactsListRes = findFirstToscaListElement(nodeTemplateJsonMap, ARTIFACTS);
1003         if (artifactsListRes.isLeft()) {
1004             for (Object jsonArtifactObj : artifactsListRes.left().value()) {
1005                 String key = ((Map<String, Object>) jsonArtifactObj).keySet().iterator().next();
1006                 Object artifactJson = ((Map<String, Object>) jsonArtifactObj).get(key);
1007                 addModuleNodeTemplateArtifacts(moduleArtifacts, artifactJson, key);
1008             }
1009         } else {
1010             Either<Map<String, Map<String, Object>>, ResultStatusEnum> artifactsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, ARTIFACTS);
1011             if (artifactsMapRes.isLeft()) {
1012                 for (Map.Entry<String, Map<String, Object>> entry : artifactsMapRes.left().value().entrySet()) {
1013                     String artifactName = entry.getKey();
1014                     Object artifactJson = entry.getValue();
1015                     addModuleNodeTemplateArtifacts(moduleArtifacts, artifactJson, artifactName);
1016                 }
1017             }
1018         }
1019         return moduleArtifacts;
1020     }
1021
1022     private void addModuleNodeTemplateArtifacts(Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts, Object artifactJson,
1023                                                 String artifactName) {
1024         UploadArtifactInfo artifact = buildModuleNodeTemplateArtifact(artifactJson);
1025         artifact.setName(artifactName);
1026         if (moduleArtifacts.containsKey(ARTIFACTS.getElementName())) {
1027             moduleArtifacts.get(ARTIFACTS.getElementName()).put(artifactName, artifact);
1028         } else {
1029             Map<String, UploadArtifactInfo> map = new HashMap<>();
1030             map.put(artifactName, artifact);
1031             moduleArtifacts.put(ARTIFACTS.getElementName(), map);
1032         }
1033     }
1034
1035     @SuppressWarnings("unchecked")
1036     private UploadArtifactInfo buildModuleNodeTemplateArtifact(Object artifactObject) {
1037         UploadArtifactInfo artifactTemplateInfo = new UploadArtifactInfo();
1038         if (artifactObject instanceof Map) {
1039             fillArtifact(artifactTemplateInfo, (Map<String, Object>) artifactObject);
1040         }
1041         return artifactTemplateInfo;
1042     }
1043
1044     private void fillArtifact(UploadArtifactInfo artifactTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
1045         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
1046             artifactTemplateInfo.setType((String) nodeTemplateJsonMap.get(TYPE.getElementName()));
1047         }
1048         if (nodeTemplateJsonMap.containsKey(FILE.getElementName())) {
1049             artifactTemplateInfo.setFile((String) nodeTemplateJsonMap.get(FILE.getElementName()));
1050         }
1051         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
1052             Map<String, List<UploadPropInfo>> props =
1053                 buildPropModuleFromYaml((Map<String, Object>) nodeTemplateJsonMap.get(PROPERTIES.getElementName()));
1054             if (!props.isEmpty()) {
1055                 List<UploadPropInfo> properties = props.values().stream().flatMap(Collection::stream).collect(toList());
1056                 artifactTemplateInfo.setProperties(properties);
1057             }
1058         }
1059     }
1060
1061     @SuppressWarnings("unchecked")
1062     private Map<String, List<UploadCapInfo>> createCapModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
1063         Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
1064         Map<String, Object> capabilities = (Map<String, Object>) nodeTemplateJsonMap.get(CAPABILITIES.getElementName());
1065         if (MapUtils.isNotEmpty(capabilities)) {
1066             for (Map.Entry<String, Object> entry : capabilities.entrySet()) {
1067                 String capName = entry.getKey();
1068                 Object capJson = entry.getValue();
1069                 addModuleNodeTemplateCap(moduleCap, capJson, capName);
1070             }
1071         }
1072         return moduleCap;
1073     }
1074
1075     private void addModuleNodeTemplateCap(Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
1076         UploadCapInfo capabilityDef = buildModuleNodeTemplateCap(capJson);
1077         capabilityDef.setKey(key);
1078         if (moduleCap.containsKey(key)) {
1079             moduleCap.get(key).add(capabilityDef);
1080         } else {
1081             List<UploadCapInfo> list = new ArrayList<>();
1082             list.add(capabilityDef);
1083             moduleCap.put(key, list);
1084         }
1085     }
1086
1087     @SuppressWarnings("unchecked")
1088     private UploadCapInfo buildModuleNodeTemplateCap(Object capObject) {
1089         UploadCapInfo capTemplateInfo = new UploadCapInfo();
1090         if (capObject instanceof String) {
1091             String nodeTemplateJsonString = (String) capObject;
1092             capTemplateInfo.setNode(nodeTemplateJsonString);
1093         } else if (capObject instanceof Map) {
1094             fillCapability(capTemplateInfo, (Map<String, Object>) capObject);
1095         }
1096         return capTemplateInfo;
1097     }
1098
1099     private void fillCapability(UploadCapInfo capTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
1100         if (nodeTemplateJsonMap.containsKey(NODE.getElementName())) {
1101             capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(NODE.getElementName()));
1102         }
1103         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
1104             capTemplateInfo.setType((String) nodeTemplateJsonMap.get(TYPE.getElementName()));
1105         }
1106         if (nodeTemplateJsonMap.containsKey(VALID_SOURCE_TYPES.getElementName())) {
1107             Either<List<Object>, ResultStatusEnum> validSourceTypesRes = findFirstToscaListElement(nodeTemplateJsonMap, VALID_SOURCE_TYPES);
1108             if (validSourceTypesRes.isLeft()) {
1109                 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(Object::toString).collect(toList()));
1110             }
1111         }
1112         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
1113             Map<String, List<UploadPropInfo>> props =
1114                 buildPropModuleFromYaml((Map<String, Object>) nodeTemplateJsonMap.get(PROPERTIES.getElementName()));
1115             if (!props.isEmpty()) {
1116                 List<UploadPropInfo> properties = props.values().stream().flatMap(Collection::stream).collect(toList());
1117                 capTemplateInfo.setProperties(properties);
1118             }
1119         }
1120     }
1121
1122     @SuppressWarnings("unchecked")
1123     private UploadReqInfo buildModuleNodeTemplateReg(Object regObject, String nodeName) {
1124         UploadReqInfo regTemplateInfo = new UploadReqInfo();
1125         if (regObject instanceof String) {
1126             String nodeTemplateJsonString = (String) regObject;
1127             regTemplateInfo.setNode(nodeTemplateJsonString);
1128         } else if (regObject instanceof Map) {
1129             Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
1130             if (nodeTemplateJsonMap.containsKey(NODE.getElementName())) {
1131                 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(NODE.getElementName()));
1132             }
1133             if (nodeTemplateJsonMap.containsKey(CAPABILITY.getElementName())) {
1134                 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(CAPABILITY.getElementName()));
1135             }
1136             if (nodeTemplateJsonMap.containsKey(RELATIONSHIP.getElementName())) {
1137                 final String template = (String) nodeTemplateJsonMap.get(RELATIONSHIP.getElementName());
1138                 if (StringUtils.isNotEmpty(nodeName) && template.contains(nodeName)) {
1139                     regTemplateInfo.setRelationshipTemplate(template);
1140                 }
1141             }
1142         }
1143         return regTemplateInfo;
1144     }
1145
1146     private Map<String, UploadAttributeInfo> buildAttributeModuleFromYaml(
1147         Map<String, Object> nodeTemplateJsonMap) {
1148         Map<String, UploadAttributeInfo> moduleAttribute = new HashMap<>();
1149         Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(nodeTemplateJsonMap, ATTRIBUTES);
1150         if (toscaAttributes.isLeft()) {
1151             Map<String, Object> jsonAttributes = toscaAttributes.left().value();
1152             for (Map.Entry<String, Object> jsonAttributeObj : jsonAttributes.entrySet()) {
1153                 UploadAttributeInfo attributeDef = buildAttribute(jsonAttributeObj.getKey(), jsonAttributeObj.getValue());
1154                 moduleAttribute.put(attributeDef.getName(), attributeDef);
1155             }
1156         }
1157         return moduleAttribute;
1158     }
1159
1160     private UploadAttributeInfo buildAttribute(String attributeName, Object attributeValue) {
1161         UploadAttributeInfo attributeDef = new UploadAttributeInfo();
1162         attributeDef.setValue(attributeValue);
1163         attributeDef.setName(attributeName);
1164         return attributeDef;
1165     }
1166
1167     private Map<String, List<UploadPropInfo>> buildPropModuleFromYaml(final Map<String, Object> propertyMap) {
1168         final Map<String, List<UploadPropInfo>> moduleProp = new HashMap<>();
1169         propertyMap.entrySet().forEach(propertyMapEntry -> addProperty(moduleProp, propertyMapEntry));
1170         return moduleProp;
1171     }
1172
1173     private Map<String, UploadInterfaceInfo> buildInterfacesModuleFromYaml(
1174         Map<String, Object> nodeTemplateJsonMap
1175     ) {
1176         Map<String, UploadInterfaceInfo> moduleInterfaces = new HashMap<>();
1177         Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = findFirstToscaMapElement(nodeTemplateJsonMap, INTERFACES);
1178         if (toscaInterfaces.isLeft()) {
1179             Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
1180             for (Map.Entry<String, Object> jsonInterfacesObj : jsonInterfaces.entrySet()) {
1181                 addInterfaces(moduleInterfaces, jsonInterfacesObj);
1182             }
1183         }
1184         return moduleInterfaces;
1185     }
1186
1187     private void addProperty(Map<String, List<UploadPropInfo>> moduleProp, Map.Entry<String, Object> jsonPropObj) {
1188         UploadPropInfo propertyDef = buildProperty(jsonPropObj.getKey(), jsonPropObj.getValue());
1189         if (moduleProp.containsKey(propertyDef.getName())) {
1190             moduleProp.get(propertyDef.getName()).add(propertyDef);
1191         } else {
1192             List<UploadPropInfo> list = new ArrayList<>();
1193             list.add(propertyDef);
1194             moduleProp.put(propertyDef.getName(), list);
1195         }
1196     }
1197
1198     private void addInterfaces(Map<String, UploadInterfaceInfo> moduleInterface, Map.Entry<String, Object> jsonPropObj) {
1199         UploadInterfaceInfo interfaceInfo = buildInterface(jsonPropObj.getKey(), jsonPropObj.getValue());
1200         moduleInterface.put(jsonPropObj.getKey(), interfaceInfo);
1201     }
1202
1203     @SuppressWarnings("unchecked")
1204     private UploadPropInfo buildProperty(String propName, Object propValueObj) {
1205         final var propertyDef = new UploadPropInfo();
1206         propertyDef.setValue(propValueObj);
1207         propertyDef.setName(propName);
1208         if (propValueObj instanceof Map) {
1209             final Map<String, Object> propValueMap = (Map<String, Object>) propValueObj;
1210             if (propValueMap.containsKey(TYPE.getElementName())) {
1211                 propertyDef.setType(propValueMap.get(TYPE.getElementName()).toString());
1212             }
1213             if (containsGetInput(propValueObj)) {
1214                 fillInputRecursively(propName, propValueMap, propertyDef);
1215             }
1216             if (toscaFunctionYamlParsingHandler.isPropertyValueToscaFunction(propValueObj)) {
1217                 toscaFunctionYamlParsingHandler.buildToscaFunctionBasedOnPropertyValue(propValueMap).ifPresent(propertyDef::setToscaFunction);
1218             } else {
1219                 final Collection<SubPropertyToscaFunction> subPropertyToscaFunctions =
1220                     buildSubPropertyToscaFunctions(propValueMap, new ArrayList<>());
1221                 if (CollectionUtils.isNotEmpty(subPropertyToscaFunctions)) {
1222                     Collection<SubPropertyToscaFunction> existingSubPropertyToscaFunctions = propertyDef.getSubPropertyToscaFunctions();
1223                     if (existingSubPropertyToscaFunctions == null) {
1224                         propertyDef.setSubPropertyToscaFunctions(subPropertyToscaFunctions);
1225                     } else {
1226                         propertyDef.getSubPropertyToscaFunctions().addAll(subPropertyToscaFunctions);
1227                     }
1228                 }
1229             }
1230             if (propValueMap.containsKey(DESCRIPTION.getElementName())) {
1231                 propertyDef.setDescription((propValueMap).get(DESCRIPTION.getElementName()).toString());
1232             }
1233             if (propValueMap.containsKey(DEFAULT_VALUE.getElementName())) {
1234                 propertyDef.setValue(propValueMap.get(DEFAULT_VALUE.getElementName()));
1235             }
1236             if (propValueMap.containsKey(IS_PASSWORD.getElementName())) {
1237                 propertyDef.setPassword(Boolean.getBoolean(propValueMap.get(IS_PASSWORD.getElementName()).toString()));
1238             } else {
1239                 propertyDef.setValue(propValueObj);
1240             }
1241         } else if (propValueObj instanceof List) {
1242             fillInputsListRecursively(propertyDef, (List<Object>) propValueObj);
1243             propertyDef.setValue(propValueObj);
1244         }
1245         return propertyDef;
1246     }
1247
1248     private Collection<SubPropertyToscaFunction> buildSubPropertyToscaFunctions(final Map<String, Object> propValueMap, final List<String> path) {
1249         Collection<SubPropertyToscaFunction> subPropertyToscaFunctions = new ArrayList<>();
1250         propValueMap.entrySet().stream().filter(entry -> entry.getValue() instanceof Map).forEach(entry -> {
1251             List<String> subPropertyPath = new ArrayList<>(path);
1252             subPropertyPath.add(entry.getKey());
1253             if (ToscaFunctionType.findType(((Map<String, Object>) entry.getValue()).keySet().iterator().next()).isPresent()) {
1254                 Optional<ToscaFunction> toscaFunction =
1255                     toscaFunctionYamlParsingHandler.buildToscaFunctionBasedOnPropertyValue((Map) entry.getValue());
1256                 if (toscaFunction.isPresent()) {
1257                     SubPropertyToscaFunction subPropertyToscaFunction = new SubPropertyToscaFunction();
1258                     subPropertyToscaFunction.setToscaFunction(toscaFunction.get());
1259                     subPropertyToscaFunction.setSubPropertyPath(subPropertyPath);
1260                     subPropertyToscaFunctions.add(subPropertyToscaFunction);
1261                 }
1262             } else {
1263                 subPropertyToscaFunctions.addAll(buildSubPropertyToscaFunctions((Map<String, Object>) entry.getValue(), subPropertyPath));
1264             }
1265         });
1266         return subPropertyToscaFunctions;
1267     }
1268
1269     private UploadInterfaceInfo buildInterface(String interfaceName, Object interfaceValue) {
1270         UploadInterfaceInfo interfaceDef = new UploadInterfaceInfo();
1271         interfaceDef.setValue(interfaceValue);
1272         interfaceDef.setName(interfaceName);
1273         interfaceDef.setKey(interfaceName);
1274         Map<String, OperationDataDefinition> operations = new HashMap<>();
1275         if (interfaceValue instanceof Map) {
1276             Map<String, Object> operationsMap = (Map<String, Object>) interfaceValue;
1277             for (Map.Entry<String, Object> operationEntry : operationsMap.entrySet()) {
1278                 OperationDataDefinition operationDef = new OperationDataDefinition();
1279                 operationDef.setName(operationEntry.getKey());
1280                 Map<String, Object> operationValue = (Map<String, Object>) operationEntry.getValue();
1281                 if (operationValue.containsKey(DESCRIPTION.getElementName())) {
1282                     operationDef.setDescription(operationValue.get(DESCRIPTION.getElementName()).toString());
1283                 }
1284                 operationDef.setImplementation(handleOperationImplementation(operationValue).orElse(new ArtifactDataDefinition()));
1285                 if (operationValue.containsKey(INPUTS.getElementName())) {
1286                     final Map<String, Object> interfaceInputs = (Map<String, Object>) operationValue.get(INPUTS.getElementName());
1287                     operationDef.setInputs(handleInterfaceOperationInputs(interfaceInputs));
1288                 }
1289                 operations.put(operationEntry.getKey(), operationDef);
1290             }
1291             interfaceDef.setOperations(operations);
1292             if (operationsMap.containsKey(TYPE.getElementName())) {
1293                 interfaceDef.setType(((Map<String, Object>) interfaceValue).get(TYPE.getElementName()).toString());
1294             }
1295         }
1296         return interfaceDef;
1297     }
1298
1299     private ListDataDefinition<OperationInputDefinition> handleInterfaceOperationInputs(final Map<String, Object> interfaceInputs) {
1300         final ListDataDefinition<OperationInputDefinition> inputs = new ListDataDefinition<>();
1301         for (final Entry<String, Object> interfaceInput : interfaceInputs.entrySet()) {
1302             final OperationInputDefinition operationInput = new OperationInputDefinition();
1303             operationInput.setUniqueId(UUID.randomUUID().toString());
1304             operationInput.setInputId(operationInput.getUniqueId());
1305             operationInput.setName(interfaceInput.getKey());
1306
1307             handleInputToscaDefinition(interfaceInput.getKey(), interfaceInput.getValue(), operationInput);
1308             inputs.add(operationInput);
1309         }
1310         return inputs;
1311     }
1312
1313     private void handleInputToscaDefinition(
1314         final String inputName,
1315         final Object value,
1316         final OperationInputDefinition operationInput
1317     ) {
1318         if (value instanceof Map) {
1319             final Map<String, Object> valueMap = (Map<String, Object>) value;
1320             log.debug("Creating interface operation input '{}'", inputName);
1321             Type type = new TypeToken<LinkedHashMap<String, Object>>() {
1322             }.getType();
1323             String stringValue = gson.toJson(value, type);
1324             if (toscaFunctionYamlParsingHandler.isPropertyValueToscaFunction(value)) {
1325                 toscaFunctionYamlParsingHandler.buildToscaFunctionBasedOnPropertyValue((Map<String, Object>) value)
1326                     .ifPresent(operationInput::setToscaFunction);
1327             } else {
1328                 final Collection<SubPropertyToscaFunction> subPropertyToscaFunctions = buildSubPropertyToscaFunctions(valueMap, new ArrayList<>());
1329                 if (CollectionUtils.isNotEmpty(subPropertyToscaFunctions)) {
1330                     Collection<SubPropertyToscaFunction> existingSubPropertyToscaFunctions = operationInput.getSubPropertyToscaFunctions();
1331                     if (existingSubPropertyToscaFunctions == null) {
1332                         operationInput.setSubPropertyToscaFunctions(subPropertyToscaFunctions);
1333                     } else {
1334                         operationInput.getSubPropertyToscaFunctions().addAll(subPropertyToscaFunctions);
1335                     }
1336                 }
1337             }
1338             operationInput.setValue(stringValue);
1339         }
1340         if (value instanceof String) {
1341             final String stringValue = (String) value;
1342             operationInput.setDefaultValue(stringValue);
1343             operationInput.setToscaDefaultValue(stringValue);
1344             operationInput.setValue(stringValue);
1345         }
1346         operationInput.setType("string");
1347         if (operationInput.getValue() == null) {
1348             operationInput.setValue(String.valueOf(value));
1349         }
1350     }
1351
1352     private Optional<ArtifactDataDefinition> handleOperationImplementation(
1353         final Map<String, Object> operationDefinitionMap
1354     ) {
1355         if (!operationDefinitionMap.containsKey(IMPLEMENTATION.getElementName())) {
1356             return Optional.empty();
1357         }
1358         final ArtifactDataDefinition artifactDataDefinition = new ArtifactDataDefinition();
1359         if (operationDefinitionMap.get(IMPLEMENTATION.getElementName()) instanceof Map &&
1360             ((Map) operationDefinitionMap.get(IMPLEMENTATION.getElementName())).containsKey("primary")) {
1361
1362             final Object primary = ((Map) operationDefinitionMap.get(IMPLEMENTATION.getElementName())).get("primary");
1363             if (primary instanceof Map) {
1364                 Map<String, Object> implDetails = (Map) primary;
1365
1366                 if (implDetails.get("file") != null) {
1367                     final String file = implDetails.get("file").toString();
1368                     artifactDataDefinition.setArtifactName(generateArtifactName(file));
1369                 }
1370                 if (implDetails.get("type") != null) {
1371                     artifactDataDefinition.setArtifactType(implDetails.get("type").toString());
1372                 }
1373                 if (implDetails.get("artifact_version") != null) {
1374                     artifactDataDefinition.setArtifactVersion(implDetails.get("artifact_version").toString());
1375                 }
1376
1377                 if (implDetails.get("properties") instanceof Map) {
1378                     Map<String, Object> properties = (Map<String, Object>) implDetails.get("properties");
1379                     properties.forEach((k, v) -> {
1380                         ToscaPropertyType type = getTypeFromObject(v);
1381                         if (type != null) {
1382                             PropertyDataDefinition propertyDef = new PropertyDataDefinition();
1383                             propertyDef.setName(k);
1384                             propertyDef.setValue(v.toString());
1385                             artifactDataDefinition.addProperty(propertyDef);
1386                         }
1387                     });
1388                 }
1389             } else {
1390                 artifactDataDefinition.setArtifactName(generateArtifactName(primary.toString()));
1391             }
1392         }
1393
1394         if (operationDefinitionMap.get(IMPLEMENTATION.getElementName()) instanceof Map &&
1395             ((Map) operationDefinitionMap.get(IMPLEMENTATION.getElementName())).containsKey("timeout")) {
1396             final Object timeOut = ((Map) operationDefinitionMap.get(IMPLEMENTATION.getElementName())).get("timeout");
1397             artifactDataDefinition.setTimeout((Integer)timeOut);
1398         }
1399
1400         if (operationDefinitionMap.get(IMPLEMENTATION.getElementName()) instanceof String) {
1401             final String implementation = (String) operationDefinitionMap.get(IMPLEMENTATION.getElementName());
1402             artifactDataDefinition.setArtifactName(generateArtifactName(implementation));
1403         }
1404         return Optional.of(artifactDataDefinition);
1405     }
1406
1407     private String generateArtifactName(final String name) {
1408         if (OperationArtifactUtil.artifactNameIsALiteralValue(name)) {
1409             return name;
1410         } else {
1411             return QUOTE + name + QUOTE;
1412         }
1413     }
1414
1415     private ToscaPropertyType getTypeFromObject(final Object value) {
1416         if (value instanceof String) {
1417             return ToscaPropertyType.STRING;
1418         }
1419         if (value instanceof Integer) {
1420             return ToscaPropertyType.INTEGER;
1421         }
1422         if (value instanceof Boolean) {
1423             return ToscaPropertyType.BOOLEAN;
1424         }
1425         if (value instanceof Float || value instanceof Double) {
1426             return ToscaPropertyType.FLOAT;
1427         }
1428         return null;
1429     }
1430
1431     @SuppressWarnings("unchecked")
1432     private boolean containsGetInput(Object propValue) {
1433         return ((Map<String, Object>) propValue).containsKey(GET_INPUT.getElementName()) || ImportUtils.containsGetInput(propValue);
1434     }
1435
1436     @SuppressWarnings("unchecked")
1437     private void fillInputsListRecursively(UploadPropInfo propertyDef, List<Object> propValueList) {
1438         int index = 0;
1439         for (Object objValue : propValueList) {
1440             if (objValue instanceof Map) {
1441                 Map<String, Object> objMap = (Map<String, Object>) objValue;
1442                 Map<String, Object> propValueMap = new HashMap<>();
1443                 propValueMap.put(String.valueOf(index), objValue);
1444                 final Collection<SubPropertyToscaFunction> subPropertyToscaFunctions =
1445                     buildSubPropertyToscaFunctions(propValueMap, new ArrayList<>());
1446                 if (CollectionUtils.isNotEmpty(subPropertyToscaFunctions)) {
1447                     Collection<SubPropertyToscaFunction> existingSubPropertyToscaFunctions = propertyDef.getSubPropertyToscaFunctions();
1448                     if (existingSubPropertyToscaFunctions == null) {
1449                         propertyDef.setSubPropertyToscaFunctions(subPropertyToscaFunctions);
1450                     } else {
1451                         propertyDef.getSubPropertyToscaFunctions().addAll(subPropertyToscaFunctions);
1452                     }
1453                 }
1454                 if (objMap.containsKey(GET_INPUT.getElementName())) {
1455                     fillInputRecursively(propertyDef.getName(), objMap, propertyDef);
1456                 } else {
1457                     Set<String> keys = objMap.keySet();
1458                     findAndFillInputsListRecursively(propertyDef, objMap, keys);
1459                 }
1460             } else if (objValue instanceof List) {
1461                 List<Object> propSubValueList = (List<Object>) objValue;
1462                 fillInputsListRecursively(propertyDef, propSubValueList);
1463             }
1464             index++;
1465         }
1466     }
1467
1468     @SuppressWarnings("unchecked")
1469     private void findAndFillInputsListRecursively(UploadPropInfo propertyDef, Map<String, Object> objMap, Set<String> keys) {
1470         for (String key : keys) {
1471             Object value = objMap.get(key);
1472             if (value instanceof Map) {
1473                 fillInputRecursively(key, (Map<String, Object>) value, propertyDef);
1474             } else if (value instanceof List) {
1475                 List<Object> propSubValueList = (List<Object>) value;
1476                 fillInputsListRecursively(propertyDef, propSubValueList);
1477             }
1478         }
1479     }
1480
1481     private void fillInputRecursively(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
1482         if (propValue.containsKey(GET_INPUT.getElementName())) {
1483             Object getInput = propValue.get(GET_INPUT.getElementName());
1484             GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
1485             List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
1486             if (getInputs == null) {
1487                 getInputs = new ArrayList<>();
1488             }
1489             if (getInput instanceof String) {
1490                 getInputInfo.setInputName((String) getInput);
1491                 getInputInfo.setPropName(propName);
1492             } else if (getInput instanceof List) {
1493                 fillInput(propName, getInput, getInputInfo);
1494             }
1495             getInputs.add(getInputInfo);
1496             propertyDef.setGet_input(getInputs);
1497             propertyDef.setValue(propValue);
1498         } else {
1499             findAndFillInputRecursively(propValue, propertyDef);
1500         }
1501     }
1502
1503     @SuppressWarnings("unchecked")
1504     private void findAndFillInputRecursively(Map<String, Object> propValue, UploadPropInfo propertyDef) {
1505         for (Map.Entry<String, Object> entry : propValue.entrySet()) {
1506             String propName = entry.getKey();
1507             Object value = entry.getValue();
1508             if (value instanceof Map) {
1509                 fillInputRecursively(propName, (Map<String, Object>) value, propertyDef);
1510             } else if (value instanceof List) {
1511                 fillInputsRecursively(propertyDef, propName, (List<Object>) value);
1512             }
1513         }
1514     }
1515
1516     private void fillInputsRecursively(UploadPropInfo propertyDef, String propName, List<Object> inputs) {
1517         inputs.stream().filter(Map.class::isInstance).forEach(o -> fillInputRecursively(propName, (Map<String, Object>) o, propertyDef));
1518     }
1519
1520     @SuppressWarnings("unchecked")
1521     private void fillInput(String propName, Object getInput, GetInputValueDataDefinition getInputInfo) {
1522         List<Object> getInputList = (List<Object>) getInput;
1523         getInputInfo.setPropName(propName);
1524         getInputInfo.setInputName((String) getInputList.get(0));
1525         if (getInputList.size() > 1) {
1526             Object indexObj = getInputList.get(1);
1527             if (indexObj instanceof Integer) {
1528                 getInputInfo.setIndexValue((Integer) indexObj);
1529             } else if (indexObj instanceof Float) {
1530                 int index = ((Float) indexObj).intValue();
1531                 getInputInfo.setIndexValue(index);
1532             } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(GET_INPUT.getElementName())) {
1533                 Object index = ((Map<String, Object>) indexObj).get(GET_INPUT.getElementName());
1534                 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
1535                 getInputInfoIndex.setInputName((String) index);
1536                 getInputInfoIndex.setPropName(propName);
1537                 getInputInfo.setGetInputIndex(getInputInfoIndex);
1538             }
1539             getInputInfo.setList(true);
1540         }
1541     }
1542
1543     private Object failIfNotTopologyTemplate(String fileName) {
1544         janusGraphDao.rollback();
1545         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, fileName);
1546     }
1547
1548     private void rollbackWithException(ActionStatus actionStatus, String... params) {
1549         janusGraphDao.rollback();
1550         throw new ByActionStatusComponentException(actionStatus, params);
1551     }
1552
1553     private void failOnMissingCapabilityTypes(GroupDefinition groupDefinition, List<String> missingCapTypes) {
1554         if (log.isDebugEnabled()) {
1555             log.debug(
1556                 "#failOnMissingCapabilityTypes - Failed to validate the capabilities of the group {}. The capability types {} are missing on the group type {}. ",
1557                 groupDefinition.getName(), missingCapTypes.toString(), groupDefinition.getType());
1558         }
1559         if (CollectionUtils.isNotEmpty(missingCapTypes)) {
1560             rollbackWithException(ActionStatus.MISSING_CAPABILITY_TYPE, missingCapTypes.toString());
1561         }
1562     }
1563
1564     private void failOnMissingCapabilityNames(GroupDefinition groupDefinition, List<String> missingCapNames) {
1565         if (log.isDebugEnabled()) {
1566             log.debug(
1567                 "#failOnMissingCapabilityNames - Failed to validate the capabilities of the group {}. The capabilities with the names {} are missing on the group type {}. ",
1568                 groupDefinition.getName(), missingCapNames.toString(), groupDefinition.getType());
1569         }
1570         rollbackWithException(ActionStatus.MISSING_CAPABILITIES, missingCapNames.toString(), CapabilityDataDefinition.OwnerType.GROUP.getValue(),
1571             groupDefinition.getName());
1572     }
1573 }