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