3faf750a732fcafbb7c07920f62edcebd44fe1e5
[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 package org.openecomp.sdc.be.components.csar;
23
24 import static java.util.stream.Collectors.toList;
25 import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
26 import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
27 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaListElement;
28 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement;
29 import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement;
30 import static org.openecomp.sdc.be.components.impl.ImportUtils.loadYamlAsStrictMap;
31 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS;
32 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITIES;
33 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITY;
34 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE;
35 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DESCRIPTION;
36 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.FILE;
37 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GET_INPUT;
38 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GROUPS;
39 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.INPUTS;
40 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD;
41 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS;
42 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE;
43 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES;
44 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TYPE;
45 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES;
46 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES;
47 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS;
48 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_FILTERS;
49 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS;
50 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS;
51 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE;
52 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE;
53 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES;
54
55 import com.google.common.collect.Lists;
56 import com.google.common.collect.Maps;
57 import com.google.gson.Gson;
58 import fj.data.Either;
59 import java.util.ArrayList;
60 import java.util.Collection;
61 import java.util.Collections;
62 import java.util.EnumMap;
63 import java.util.HashMap;
64 import java.util.List;
65 import java.util.Map;
66 import java.util.Objects;
67 import java.util.Set;
68 import java.util.regex.Pattern;
69 import java.util.stream.Collectors;
70 import org.apache.commons.collections.CollectionUtils;
71 import org.apache.commons.collections.MapUtils;
72 import org.apache.commons.lang3.StringUtils;
73 import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
74 import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
75 import org.openecomp.sdc.be.components.impl.ImportUtils;
76 import org.openecomp.sdc.be.components.impl.NodeFilterUploadCreator;
77 import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
78 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
79 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
80 import org.openecomp.sdc.be.config.BeEcompErrorManager;
81 import org.openecomp.sdc.be.dao.api.ActionStatus;
82 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
83 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
84 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
85 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
86 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
87 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
88 import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition;
89 import org.openecomp.sdc.be.model.CapabilityDefinition;
90 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
91 import org.openecomp.sdc.be.model.GroupDefinition;
92 import org.openecomp.sdc.be.model.GroupTypeDefinition;
93 import org.openecomp.sdc.be.model.InputDefinition;
94 import org.openecomp.sdc.be.model.NodeTypeInfo;
95 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
96 import org.openecomp.sdc.be.model.PolicyDefinition;
97 import org.openecomp.sdc.be.model.PolicyTypeDefinition;
98 import org.openecomp.sdc.be.model.PropertyDefinition;
99 import org.openecomp.sdc.be.model.Resource;
100 import org.openecomp.sdc.be.model.UploadArtifactInfo;
101 import org.openecomp.sdc.be.model.UploadCapInfo;
102 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
103 import org.openecomp.sdc.be.model.UploadPropInfo;
104 import org.openecomp.sdc.be.model.UploadReqInfo;
105 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
106 import org.openecomp.sdc.be.utils.TypeUtils;
107 import org.openecomp.sdc.common.log.wrappers.Logger;
108 import org.springframework.stereotype.Component;
109 import org.yaml.snakeyaml.parser.ParserException;
110
111 /**
112  * A handler class designed to parse the YAML file of the service template for a JAVA object
113  */
114 @Component
115 public class YamlTemplateParsingHandler {
116
117     private static final Pattern propertyValuePattern = Pattern.compile("[ ]*\\{[ ]*(str_replace=|token=|get_property=|concat=|get_attribute=)+");
118     private static final int SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX = 0;
119     private static final int SUB_MAPPING_CAPABILITY_NAME_IDX = 1;
120     private static final Logger log = Logger.getLogger(YamlTemplateParsingHandler.class);
121     private Gson gson = new Gson();
122     private JanusGraphDao janusGraphDao;
123     private GroupTypeBusinessLogic groupTypeBusinessLogic;
124     private AnnotationBusinessLogic annotationBusinessLogic;
125     private PolicyTypeBusinessLogic policyTypeBusinessLogic;
126
127     public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao, GroupTypeBusinessLogic groupTypeBusinessLogic,
128                                       AnnotationBusinessLogic annotationBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) {
129         this.janusGraphDao = janusGraphDao;
130         this.groupTypeBusinessLogic = groupTypeBusinessLogic;
131         this.annotationBusinessLogic = annotationBusinessLogic;
132         this.policyTypeBusinessLogic = policyTypeBusinessLogic;
133     }
134
135     public ParsedToscaYamlInfo parseResourceInfoFromYAML(String fileName, String resourceYml, Map<String, String> createdNodesToscaResourceNames,
136                                                          Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName,
137                                                          org.openecomp.sdc.be.model.Component component, String interfaceTemplateYaml) {
138         log.debug("#parseResourceInfoFromYAML - Going to parse yaml {} ", fileName);
139         Map<String, Object> mappedToscaTemplate = getMappedToscaTemplate(fileName, resourceYml, nodeTypesInfo, nodeName);
140         ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
141         Map<String, Object> mappedTopologyTemplate = (Map<String, Object>) findToscaElement(mappedToscaTemplate, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL).left().on(err -> failIfNotTopologyTemplate(fileName));
142         Map<String, Object> mappedTopologyTemplateInputs  = mappedTopologyTemplate.entrySet().stream().filter(entry -> entry.getKey().equals(INPUTS.getElementName())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
143         parsedToscaYamlInfo.setInputs(getInputs(mappedTopologyTemplateInputs));
144         parsedToscaYamlInfo.setInstances(getInstances(fileName, mappedToscaTemplate, createdNodesToscaResourceNames));
145         parsedToscaYamlInfo.setGroups(getGroups(fileName, mappedToscaTemplate, component.getModel()));
146         if (component instanceof Resource) {
147             parsedToscaYamlInfo.setPolicies(getPolicies(fileName, mappedToscaTemplate, component.getModel()));
148         }
149         if (getSubstitutionMappings(mappedToscaTemplate) != null) {
150             if (component.isService() && !interfaceTemplateYaml.isEmpty()) {
151                 parsedToscaYamlInfo.setProperties(getProperties(loadYamlAsStrictMap(interfaceTemplateYaml)));
152                 parsedToscaYamlInfo.setSubstitutionFilterProperties(getSubstitutionFilterProperties(mappedToscaTemplate));
153             }
154             parsedToscaYamlInfo.setSubstitutionMappingNodeType((String) getSubstitutionMappings(mappedToscaTemplate).get(NODE_TYPE.getElementName()));
155         }
156         log.debug("#parseResourceInfoFromYAML - The yaml {} has been parsed ", fileName);
157         return parsedToscaYamlInfo;
158     }
159
160     private Map<String, Object> getMappedToscaTemplate(String fileName, String resourceYml, Map<String, NodeTypeInfo> nodeTypesInfo,
161                                                        String nodeName) {
162         Map<String, Object> mappedToscaTemplate;
163         if (isNodeExist(nodeTypesInfo, nodeName)) {
164             mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
165         } else {
166             mappedToscaTemplate = loadYaml(fileName, resourceYml);
167         }
168         return mappedToscaTemplate;
169     }
170
171     private Map<String, Object> loadYaml(String fileName, String resourceYml) {
172         Map<String, Object> mappedToscaTemplate = null;
173         try {
174             mappedToscaTemplate = loadYamlAsStrictMap(resourceYml);
175         } catch (ParserException e) {
176             log.debug("#getMappedToscaTemplate - Failed to load YAML file {}", fileName, e);
177             rollbackWithException(ActionStatus.TOSCA_PARSE_ERROR, fileName, e.getMessage());
178         }
179         return mappedToscaTemplate;
180     }
181
182     private boolean isNodeExist(Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
183         return nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName);
184     }
185
186     private Map<String, InputDefinition> getInputs(Map<String, Object> toscaJson) {
187         Map<String, InputDefinition> inputs = ImportUtils.getInputs(toscaJson, annotationBusinessLogic.getAnnotationTypeOperations()).left()
188             .on(err -> new HashMap<>());
189         annotationBusinessLogic.validateAndMergeAnnotationsAndAssignToInput(inputs);
190         return inputs;
191     }
192
193     private Map<String, PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
194         return ImportUtils.getProperties(toscaJson).left().on(err -> new HashMap<>());
195     }
196
197     private ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> getSubstitutionFilterProperties(Map<String, Object> toscaJson) {
198         ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> propertyList = new ListDataDefinition<>();
199         Map<String, Object> substitutionFilters = findFirstToscaMapElement(toscaJson, SUBSTITUTION_FILTERS).left().on(err -> new HashMap<>());
200         if (MapUtils.isEmpty(substitutionFilters)) {
201             return propertyList;
202         }
203         ArrayList<Map<String, List<Map<String, Object>>>> substitutionFilterProperties =
204             (ArrayList<Map<String, List<Map<String, Object>>>>) substitutionFilters.get("properties");
205         if (CollectionUtils.isEmpty(substitutionFilterProperties)) {
206             return propertyList;
207         }
208         for (Map<String, List<Map<String, Object>>> filterProps : substitutionFilterProperties) {
209             for (Map.Entry<String, List<Map<String, Object>>> filterPropsMap : filterProps.entrySet()) {
210                 for (Map<String, Object> mapValue : filterPropsMap.getValue()) {
211                     RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition =
212                         new RequirementSubstitutionFilterPropertyDataDefinition();
213                     requirementSubstitutionFilterPropertyDataDefinition.setName(filterPropsMap.getKey());
214                     requirementSubstitutionFilterPropertyDataDefinition.setConstraints(
215                         getSubstitutionFilterConstraints(filterPropsMap.getKey(), mapValue));
216                     propertyList.add(requirementSubstitutionFilterPropertyDataDefinition);
217                 }
218             }
219         }
220         return propertyList;
221     }
222
223     private List<String> getSubstitutionFilterConstraints(String name, Map<String, Object> value) {
224         List<String> constraints = new ArrayList<>();
225         for (Map.Entry<String, Object> valueMap : value.entrySet()) {
226             constraints.add(name + ": {" + valueMap.getKey() + ": " + valueMap.getValue() + "}");
227         }
228         return constraints;
229     }
230
231     private Map<String, PolicyDefinition> getPolicies(String fileName, Map<String, Object> toscaJson, String model) {
232         Map<String, Object> foundPolicies = findFirstToscaMapElement(toscaJson, POLICIES).left().on(err -> logPoliciesNotFound(fileName));
233         if (MapUtils.isNotEmpty(foundPolicies)) {
234             return foundPolicies.entrySet().stream().map(policyToCreate -> createPolicy(policyToCreate, model)).collect(Collectors.toMap(PolicyDefinition::getName, p -> p));
235         }
236         return Collections.emptyMap();
237     }
238
239     private PolicyDefinition createPolicy(Map.Entry<String, Object> policyNameValue, String model) {
240         PolicyDefinition emptyPolicyDef = new PolicyDefinition();
241         String policyName = policyNameValue.getKey();
242         emptyPolicyDef.setName(policyName);
243         try {
244             // 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.
245             if (policyNameValue.getValue() instanceof Map) {
246                 Map<String, Object> policyTemplateJsonMap = (Map<String, Object>) policyNameValue.getValue();
247                 validateAndFillPolicy(emptyPolicyDef, policyTemplateJsonMap, model);
248             } else {
249                 rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
250             }
251         } catch (ClassCastException e) {
252             log.debug("#createPolicy - Failed to create the policy {}. The exception occurred", policyName, e);
253             rollbackWithException(ActionStatus.INVALID_YAML);
254         }
255         return emptyPolicyDef;
256     }
257
258     private Map<String, Object> logPoliciesNotFound(String fileName) {
259         log.debug("#logPoliciesNotFound - Policies were not found in the yaml template {}.", fileName);
260         return Collections.emptyMap();
261     }
262
263     private void validateAndFillPolicy(PolicyDefinition emptyPolicyDefinition, Map<String, Object> policyTemplateJsonMap, String model) {
264         String policyTypeName = (String) policyTemplateJsonMap.get(TYPE.getElementName());
265         if (StringUtils.isEmpty(policyTypeName)) {
266             log.debug("#validateAndFillPolicy - The 'type' member is not found under policy {}", emptyPolicyDefinition.getName());
267             rollbackWithException(ActionStatus.POLICY_MISSING_POLICY_TYPE, emptyPolicyDefinition.getName());
268         }
269         emptyPolicyDefinition.setType(policyTypeName);
270         // set policy targets
271         emptyPolicyDefinition.setTargets(validateFillPolicyTargets(policyTemplateJsonMap));
272         PolicyTypeDefinition policyTypeDefinition = validateGetPolicyTypeDefinition(policyTypeName, model);
273         // set policy properties
274         emptyPolicyDefinition.setProperties(validateFillPolicyProperties(policyTypeDefinition, policyTemplateJsonMap));
275     }
276
277     private PolicyTypeDefinition validateGetPolicyTypeDefinition(String policyType, String modelName) {
278         PolicyTypeDefinition policyTypeDefinition = policyTypeBusinessLogic.getLatestPolicyTypeByType(policyType, modelName);
279         if (policyTypeDefinition == null) {
280             log.debug("#validateAndFillPolicy - The policy type {} not found", policyType);
281             rollbackWithException(ActionStatus.POLICY_TYPE_IS_INVALID, policyType);
282         }
283         return policyTypeDefinition;
284     }
285
286     private List<PropertyDataDefinition> validateFillPolicyProperties(PolicyTypeDefinition policyTypeDefinition,
287                                                                       Map<String, Object> policyTemplateJsonMap) {
288         if (MapUtils.isEmpty(policyTemplateJsonMap) || Objects.isNull(policyTypeDefinition)) {
289             return Collections.emptyList();
290         }
291         List<PropertyDataDefinition> propertyDataDefinitionList = new ArrayList<>();
292         Map<String, Object> propertiesMap = (Map<String, Object>) policyTemplateJsonMap.get(PROPERTIES.getElementName());
293         if (MapUtils.isEmpty(propertiesMap)) {
294             return Collections.emptyList();
295         }
296         if (CollectionUtils.isNotEmpty(policyTypeDefinition.getProperties())) {
297             propertyDataDefinitionList = policyTypeDefinition.getProperties().stream()
298                 .map(propertyDefinition -> setPropertyValue(propertiesMap, propertyDefinition)).collect(Collectors.toList());
299         }
300         return propertyDataDefinitionList;
301     }
302
303     private PropertyDataDefinition setPropertyValue(Map<String, Object> propertiesMap, PropertyDataDefinition srcPropertyDataDefinition) {
304         PropertyDataDefinition newPropertyDef = new PropertyDataDefinition(srcPropertyDataDefinition);
305         String propertyName = newPropertyDef.getName();
306         if (Objects.nonNull(propertiesMap.get(propertyName))) {
307             Object propValue = propertiesMap.get(propertyName);
308             newPropertyDef.setValue(PropertiesUtils.trimQuotes(gson.toJson(propValue)));
309         }
310         return newPropertyDef;
311     }
312
313     private Map<PolicyTargetType, List<String>> validateFillPolicyTargets(Map<String, Object> policyTemplateJson) {
314         Map<PolicyTargetType, List<String>> targets = new EnumMap<>(PolicyTargetType.class);
315         if (policyTemplateJson.containsKey(TARGETS.getElementName()) && policyTemplateJson.get(TARGETS.getElementName()) instanceof List) {
316             List<String> targetsElement = (List<String>) policyTemplateJson.get(TARGETS.getElementName());
317             targets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsElement);
318         }
319         return targets;
320     }
321
322     private Map<String, UploadComponentInstanceInfo> getInstances(String yamlName, Map<String, Object> toscaJson,
323                                                                   Map<String, String> createdNodesToscaResourceNames) {
324         Map<String, Object> nodeTemplates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES).left().on(err -> new HashMap<>());
325         if (nodeTemplates.isEmpty()) {
326             return Collections.emptyMap();
327         }
328         return getInstances(toscaJson, createdNodesToscaResourceNames, nodeTemplates);
329     }
330
331     private Map<String, UploadComponentInstanceInfo> getInstances(Map<String, Object> toscaJson, Map<String, String> createdNodesToscaResourceNames,
332                                                                   Map<String, Object> nodeTemplates) {
333         Map<String, UploadComponentInstanceInfo> moduleComponentInstances;
334         Map<String, Object> substitutionMappings = getSubstitutionMappings(toscaJson);
335         moduleComponentInstances = nodeTemplates.entrySet().stream()
336             .map(node -> buildModuleComponentInstanceInfo(node, substitutionMappings, createdNodesToscaResourceNames))
337             .collect(Collectors.toMap(UploadComponentInstanceInfo::getName, i -> i));
338         return moduleComponentInstances;
339     }
340
341     private Map<String, Object> getSubstitutionMappings(Map<String, Object> toscaJson) {
342         Map<String, Object> substitutionMappings = null;
343         Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = findFirstToscaMapElement(toscaJson, SUBSTITUTION_MAPPINGS);
344         if (eitherSubstitutionMappings.isLeft()) {
345             substitutionMappings = eitherSubstitutionMappings.left().value();
346         }
347         return substitutionMappings;
348     }
349
350     @SuppressWarnings("unchecked")
351     private Map<String, GroupDefinition> getGroups(String fileName, Map<String, Object> toscaJson, String model) {
352         Map<String, Object> foundGroups = findFirstToscaMapElement(toscaJson, GROUPS).left().on(err -> logGroupsNotFound(fileName));
353         if (MapUtils.isNotEmpty(foundGroups) && matcheKey(foundGroups)) {
354             Map<String, GroupDefinition> groups = foundGroups.entrySet().stream().map(groupToCreate -> createGroup(groupToCreate, model))
355                 .collect(Collectors.toMap(GroupDefinition::getName, g -> g));
356             Map<String, Object> substitutionMappings = getSubstitutionMappings(toscaJson);
357             if (capabilitiesSubstitutionMappingsExist(substitutionMappings)) {
358                 groups.entrySet().forEach(entry -> updateCapabilitiesNames(entry.getValue(),
359                     getNamesToUpdate(entry.getKey(), (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName()))));
360             }
361             return groups;
362         }
363         return new HashMap<>();
364     }
365
366     private boolean matcheKey(Map<String, Object> foundGroups) {
367         if (foundGroups != null && !foundGroups.isEmpty()) {
368             for (Map.Entry<String, Object> stringObjectEntry : foundGroups.entrySet()) {
369                 String key = stringObjectEntry.getKey();
370                 if (key.contains("group")) {
371                     if (foundGroups.get(key) instanceof Map) {
372                         return true;
373                     }
374                 }
375             }
376         }
377         return false;
378     }
379
380     private Map<String, Object> logGroupsNotFound(String fileName) {
381         log.debug("#logGroupsNotFound - Groups were not found in the yaml template {}.", fileName);
382         return new HashMap<>();
383     }
384
385     private void updateCapabilitiesNames(GroupDefinition group, Map<String, String> capabilityNames) {
386         if (MapUtils.isNotEmpty(group.getCapabilities())) {
387             group.getCapabilities().values().stream().flatMap(Collection::stream).filter(cap -> capabilityNames.containsKey(cap.getName()))
388                 .forEach(cap -> cap.setName(capabilityNames.get(cap.getName())));
389         }
390     }
391
392     private Map<String, String> getNamesToUpdate(String name, Map<String, List<String>> pair) {
393         return pair.entrySet().stream().filter(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX).equalsIgnoreCase(name))
394             .collect(Collectors.toMap(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_NAME_IDX), Map.Entry::getKey, (n1, n2) -> n1));
395     }
396
397     private boolean capabilitiesSubstitutionMappingsExist(Map<String, Object> substitutionMappings) {
398         return substitutionMappings != null && substitutionMappings.containsKey(CAPABILITIES.getElementName());
399     }
400
401     private GroupDefinition createGroup(Map.Entry<String, Object> groupNameValue, String model) {
402         GroupDefinition group = new GroupDefinition();
403         group.setName(groupNameValue.getKey());
404         try {
405             if (groupNameValue.getValue() instanceof Map) {
406                 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupNameValue.getValue();
407                 validateAndFillGroup(group, groupTemplateJsonMap, model);
408                 validateUpdateGroupProperties(group, groupTemplateJsonMap);
409                 validateUpdateGroupCapabilities(group, groupTemplateJsonMap);
410             } else {
411                 rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
412             }
413         } catch (ClassCastException e) {
414             log.debug("#createGroup - Failed to create the group {}. The exception occure", groupNameValue.getKey(), e);
415             rollbackWithException(ActionStatus.INVALID_YAML);
416         }
417         return group;
418     }
419
420     private Map<String, CapabilityDefinition> addCapabilities(Map<String, CapabilityDefinition> cap, Map<String, CapabilityDefinition> otherCap) {
421         cap.putAll(otherCap);
422         return cap;
423     }
424
425     private Map<String, CapabilityDefinition> addCapability(CapabilityDefinition cap) {
426         Map<String, CapabilityDefinition> map = Maps.newHashMap();
427         map.put(cap.getName(), cap);
428         return map;
429     }
430
431     private void setMembers(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
432         if (groupTemplateJsonMap.containsKey(MEMBERS.getElementName())) {
433             Object members = groupTemplateJsonMap.get(MEMBERS.getElementName());
434             if (members != null) {
435                 if (members instanceof List) {
436                     setMembersFromList(groupInfo, (List<?>) members);
437                 } else {
438                     log.debug("The 'members' member is not of type list under group {}", groupInfo.getName());
439                     rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
440                 }
441             }
442         }
443     }
444
445     private void setMembersFromList(GroupDefinition groupInfo, List<?> membersAsList) {
446         groupInfo.setMembers(membersAsList.stream().collect(Collectors.toMap(Object::toString, member -> "")));
447     }
448
449     @SuppressWarnings("unchecked")
450     private void validateUpdateGroupProperties(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
451         if (groupTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
452             Object propertiesElement = groupTemplateJsonMap.get(PROPERTIES.getElementName());
453             if (propertiesElement instanceof Map) {
454                 mergeGroupProperties(groupInfo, (Map<String, Object>) propertiesElement);
455             }
456         }
457     }
458
459     private void mergeGroupProperties(GroupDefinition groupInfo, Map<String, Object> parsedProperties) {
460         if (CollectionUtils.isNotEmpty(groupInfo.getProperties())) {
461             validateGroupProperties(parsedProperties, groupInfo);
462             groupInfo.getProperties().forEach(p -> mergeGroupProperty(p, parsedProperties));
463         }
464     }
465
466     private void mergeGroupProperty(PropertyDataDefinition property, Map<String, Object> parsedProperties) {
467         if (parsedProperties.containsKey(property.getName())) {
468             Object propValue = parsedProperties.get(property.getName());
469             if (valueNotContainsPattern(propertyValuePattern, propValue)) {
470                 setPropertyValueAndGetInputsValues(property, propValue);
471             }
472         }
473     }
474
475     private void setPropertyValueAndGetInputsValues(PropertyDataDefinition property, Object propValue) {
476         if (propValue != null) {
477             UploadPropInfo uploadPropInfo = buildProperty(property.getName(), propValue);
478             property.setValue(convertPropertyValue(ToscaPropertyType.isValidType(property.getType()), uploadPropInfo.getValue()));
479             property.setGetInputValues(uploadPropInfo.getGet_input());
480         }
481     }
482
483     private String convertPropertyValue(ToscaPropertyType type, Object value) {
484         String convertedValue = null;
485         if (value != null) {
486             if (type == null || value instanceof Map || value instanceof List) {
487                 convertedValue = gson.toJson(value);
488             } else {
489                 convertedValue = value.toString();
490             }
491         }
492         return convertedValue;
493     }
494
495     private void setDescription(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
496         if (groupTemplateJsonMap.containsKey(DESCRIPTION.getElementName())) {
497             groupInfo.setDescription((String) groupTemplateJsonMap.get(DESCRIPTION.getElementName()));
498         }
499     }
500
501     private void validateAndFillGroup(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap, String model) {
502         String type = (String) groupTemplateJsonMap.get(TYPE.getElementName());
503         if (StringUtils.isEmpty(type)) {
504             log.debug("#validateAndFillGroup - The 'type' member is not found under group {}", groupInfo.getName());
505             rollbackWithException(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupInfo.getName());
506         }
507         groupInfo.setType(type);
508         GroupTypeDefinition groupType = groupTypeBusinessLogic.getLatestGroupTypeByType(type, model);
509         if (groupType == null) {
510             log.debug("#validateAndFillGroup - The group type {} not found", groupInfo.getName());
511             rollbackWithException(ActionStatus.GROUP_TYPE_IS_INVALID, type);
512         }
513         groupInfo.convertFromGroupProperties(groupType.getProperties());
514         groupInfo.convertCapabilityDefinitions(groupType.getCapabilities());
515         setDescription(groupInfo, groupTemplateJsonMap);
516         setMembers(groupInfo, groupTemplateJsonMap);
517     }
518
519     @SuppressWarnings("unchecked")
520     private void validateUpdateGroupCapabilities(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
521         if (groupTemplateJsonMap.containsKey(CAPABILITIES.getElementName())) {
522             Object capabilities = groupTemplateJsonMap.get(CAPABILITIES.getElementName());
523             if (capabilities instanceof List) {
524                 validateUpdateCapabilities(groupInfo, ((List<Object>) capabilities).stream().map(o -> buildGroupCapability(groupInfo, o))
525                     .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
526             } else if (capabilities instanceof Map) {
527                 validateUpdateCapabilities(groupInfo,
528                     ((Map<String, Object>) capabilities).entrySet().stream().map(e -> buildGroupCapability(groupInfo, e))
529                         .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
530             } else {
531                 log.debug("#setCapabilities - Failed to import the capabilities of the group {}. ", groupInfo.getName());
532                 rollbackWithException(ActionStatus.INVALID_YAML);
533             }
534         }
535     }
536
537     private void validateUpdateCapabilities(GroupDefinition groupInfo, Map<String, Map<String, CapabilityDefinition>> capabilityInfo) {
538         validateGroupCapabilities(groupInfo, capabilityInfo);
539         groupInfo.updateCapabilitiesProperties(capabilityInfo);
540     }
541
542     private void validateGroupCapabilities(GroupDefinition group, Map<String, Map<String, CapabilityDefinition>> parsedCapabilities) {
543         if (MapUtils.isNotEmpty(parsedCapabilities)) {
544             if (MapUtils.isEmpty(group.getCapabilities())) {
545                 failOnMissingCapabilityTypes(group, Lists.newArrayList(parsedCapabilities.keySet()));
546             }
547             List<String> missingCapTypes = parsedCapabilities.keySet().stream().filter(ct -> !group.getCapabilities().containsKey(ct))
548                 .collect(toList());
549             if (CollectionUtils.isNotEmpty(missingCapTypes)) {
550                 failOnMissingCapabilityTypes(group, missingCapTypes);
551             }
552             group.getCapabilities().entrySet().forEach(e -> validateCapabilities(group, e.getValue(), parsedCapabilities.get(e.getKey())));
553         }
554     }
555
556     private void validateCapabilities(GroupDefinition group, List<CapabilityDefinition> capabilities,
557                                       Map<String, CapabilityDefinition> parsedCapabilities) {
558         List<String> allowedCapNames = capabilities.stream().map(CapabilityDefinition::getName).distinct().collect(toList());
559         List<String> missingCapNames = parsedCapabilities.keySet().stream().filter(c -> !allowedCapNames.contains(c)).collect(toList());
560         if (CollectionUtils.isNotEmpty(missingCapNames)) {
561             failOnMissingCapabilityNames(group, missingCapNames);
562         }
563         validateCapabilitiesProperties(capabilities, parsedCapabilities);
564     }
565
566     private void validateCapabilitiesProperties(List<CapabilityDefinition> capabilities, Map<String, CapabilityDefinition> parsedCapabilities) {
567         capabilities.forEach(c -> validateCapabilityProperties(c, parsedCapabilities.get(c.getName())));
568     }
569
570     private void validateCapabilityProperties(CapabilityDefinition capability, CapabilityDefinition parsedCapability) {
571         if (parsedCapability != null && parsedCapability.getProperties() != null) {
572             List<String> parsedPropertiesNames = parsedCapability.getProperties().stream().map(ComponentInstanceProperty::getName).collect(toList());
573             validateProperties(capability.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames,
574                 ActionStatus.PROPERTY_NOT_FOUND, capability.getName(), capability.getType());
575         }
576     }
577
578     private void validateGroupProperties(Map<String, Object> parsedProperties, GroupDefinition groupInfo) {
579         List<String> parsedPropertiesNames = parsedProperties.entrySet().stream().map(Map.Entry::getKey).collect(toList());
580         validateProperties(groupInfo.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames,
581             ActionStatus.GROUP_PROPERTY_NOT_FOUND, groupInfo.getName(), groupInfo.getType());
582     }
583
584     private void validateProperties(List<String> validProperties, List<String> parsedProperties, ActionStatus actionStatus, String name,
585                                     String type) {
586         if (CollectionUtils.isNotEmpty(parsedProperties)) {
587             verifyMissingProperties(actionStatus, name, type, parsedProperties.stream().filter(n -> !validProperties.contains(n)).collect(toList()));
588         }
589     }
590
591     private void verifyMissingProperties(ActionStatus actionStatus, String name, String type, List<String> missingProperties) {
592         if (CollectionUtils.isNotEmpty(missingProperties)) {
593             if (log.isDebugEnabled()) {
594                 log.debug("#validateProperties - Failed to validate properties. The properties {} are missing on {} of the type {}. ",
595                         missingProperties.toString(), name, type);
596             }
597             rollbackWithException(actionStatus, missingProperties.toString(), missingProperties.toString(), name, type);
598         }
599     }
600
601     @SuppressWarnings("unchecked")
602     private CapabilityDefinition buildGroupCapability(GroupDefinition groupInfo, Object capObject) {
603         if (!(capObject instanceof Map)) {
604             log.debug("#convertToGroupCapability - Failed to import the capability {}. ", capObject);
605             rollbackWithException(ActionStatus.INVALID_YAML);
606         }
607         return buildGroupCapability(groupInfo, ((Map<String, Object>) capObject).entrySet().iterator().next());
608     }
609
610     @SuppressWarnings("unchecked")
611     private CapabilityDefinition buildGroupCapability(GroupDefinition groupInfo, Map.Entry<String, Object> capEntry) {
612         CapabilityDefinition capability = new CapabilityDefinition();
613         capability.setOwnerType(CapabilityDataDefinition.OwnerType.GROUP);
614         capability.setName(capEntry.getKey());
615         capability.setParentName(capEntry.getKey());
616         capability.setOwnerId(groupInfo.getName());
617         if (!(capEntry.getValue() instanceof Map)) {
618             log.debug("#convertMapEntryToCapabilityDefinition - Failed to import the capability {}. ", capEntry.getKey());
619             rollbackWithException(ActionStatus.INVALID_YAML);
620         }
621         Map<String, Object> capabilityValue = (Map<String, Object>) capEntry.getValue();
622         String type = (String) capabilityValue.get(TYPE.getElementName());
623         if (StringUtils.isEmpty(type)) {
624             log.debug("#convertMapEntryToCapabilityDefinition - Failed to import the capability {}. Missing capability type. ", capEntry.getKey());
625             rollbackWithException(ActionStatus.INVALID_YAML);
626         }
627         capability.setType(type);
628         if (!(capabilityValue.get(PROPERTIES.getElementName()) instanceof Map)) {
629             log.debug("#convertMapEntryToCapabilityDefinition - Failed to import the capability {}. ", capEntry.getKey());
630             rollbackWithException(ActionStatus.INVALID_YAML);
631         }
632         Map<String, Object> properties = (Map<String, Object>) capabilityValue.get(PROPERTIES.getElementName());
633         capability.setProperties(properties.entrySet().stream().map(this::convertToProperty).collect(toList()));
634         return capability;
635     }
636
637     private ComponentInstanceProperty convertToProperty(Map.Entry<String, Object> e) {
638         ComponentInstanceProperty property = new ComponentInstanceProperty();
639         property.setName(e.getKey());
640         property.setValue((String) e.getValue());
641         return property;
642     }
643
644     @SuppressWarnings("unchecked")
645     private UploadComponentInstanceInfo buildModuleComponentInstanceInfo(Map.Entry<String, Object> nodeTemplateJsonEntry,
646                                                                          Map<String, Object> substitutionMappings,
647                                                                          Map<String, String> createdNodesToscaResourceNames) {
648         UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
649         nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
650         try {
651             if (nodeTemplateJsonEntry.getValue() instanceof String) {
652                 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
653                 nodeTemplateInfo.setType(nodeTemplateJsonString);
654             } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
655                 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
656                 setToscaResourceType(createdNodesToscaResourceNames, nodeTemplateInfo, nodeTemplateJsonMap);
657                 setRequirements(nodeTemplateInfo, nodeTemplateJsonMap);
658                 setCapabilities(nodeTemplateInfo, nodeTemplateJsonMap);
659                 setArtifacts(nodeTemplateInfo, nodeTemplateJsonMap);
660                 updateProperties(nodeTemplateInfo, nodeTemplateJsonMap);
661                 setDirectives(nodeTemplateInfo, nodeTemplateJsonMap);
662                 setNodeFilter(nodeTemplateInfo, nodeTemplateJsonMap);
663                 setSubstitutions(substitutionMappings, nodeTemplateInfo);
664             } else {
665                 rollbackWithException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
666             }
667         } catch (ClassCastException e) {
668             BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
669             log.debug("error when creating capability, message:{}", e.getMessage(), e);
670             rollbackWithException(ActionStatus.INVALID_YAML);
671         }
672         return nodeTemplateInfo;
673     }
674
675     @SuppressWarnings("unchecked")
676     private void setSubstitutions(Map<String, Object> substitutionMappings, UploadComponentInstanceInfo nodeTemplateInfo) {
677         if (substitutionMappings != null) {
678             if (substitutionMappings.containsKey(CAPABILITIES.getElementName())) {
679                 nodeTemplateInfo.setCapabilitiesNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(),
680                     (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName())));
681             }
682             if (substitutionMappings.containsKey(REQUIREMENTS.getElementName())) {
683                 nodeTemplateInfo.setRequirementsNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(),
684                     (Map<String, List<String>>) substitutionMappings.get(REQUIREMENTS.getElementName())));
685             }
686         }
687     }
688
689     private void updateProperties(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
690         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
691             Map<String, List<UploadPropInfo>> properties = buildPropModuleFromYaml(nodeTemplateJsonMap);
692             if (!properties.isEmpty()) {
693                 nodeTemplateInfo.setProperties(properties);
694             }
695         }
696     }
697
698     private void setCapabilities(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
699         if (nodeTemplateJsonMap.containsKey(CAPABILITIES.getElementName())) {
700             Map<String, List<UploadCapInfo>> eitherCapRes = createCapModuleFromYaml(nodeTemplateJsonMap);
701             if (!eitherCapRes.isEmpty()) {
702                 nodeTemplateInfo.setCapabilities(eitherCapRes);
703             }
704         }
705     }
706
707     private void setArtifacts(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
708         if (nodeTemplateJsonMap.containsKey(ARTIFACTS.getElementName())) {
709             Map<String, Map<String, UploadArtifactInfo>> eitherArtifactsRes = createArtifactsModuleFromYaml(nodeTemplateJsonMap);
710             if (!eitherArtifactsRes.isEmpty()) {
711                 nodeTemplateInfo.setArtifacts(eitherArtifactsRes);
712             }
713         }
714     }
715
716     private void setRequirements(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
717         if (nodeTemplateJsonMap.containsKey(REQUIREMENTS.getElementName())) {
718             Map<String, List<UploadReqInfo>> regResponse = createReqModuleFromYaml(nodeTemplateJsonMap);
719             if (!regResponse.isEmpty()) {
720                 nodeTemplateInfo.setRequirements(regResponse);
721             }
722         }
723     }
724
725     private void setToscaResourceType(Map<String, String> createdNodesToscaResourceNames, UploadComponentInstanceInfo nodeTemplateInfo,
726                                       Map<String, Object> nodeTemplateJsonMap) {
727         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
728             String toscaResourceType = (String) nodeTemplateJsonMap.get(TYPE.getElementName());
729             if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
730                 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
731             }
732             nodeTemplateInfo.setType(toscaResourceType);
733         }
734     }
735
736     private void setDirectives(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
737         List<String> directives = (List<String>) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.DIRECTIVES.getElementName());
738         nodeTemplateInfo.setDirectives(directives);
739     }
740
741     private void setNodeFilter(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
742         if (nodeTemplateJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())) {
743             nodeTemplateInfo.setUploadNodeFilterInfo(new NodeFilterUploadCreator()
744                 .createNodeFilterData(nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())));
745         }
746     }
747
748     @SuppressWarnings("unchecked")
749     private Map<String, List<UploadReqInfo>> createReqModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
750         Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<>();
751         Either<List<Object>, ResultStatusEnum> requirementsListRes = findFirstToscaListElement(nodeTemplateJsonMap, REQUIREMENTS);
752         if (requirementsListRes.isLeft()) {
753             for (Object jsonReqObj : requirementsListRes.left().value()) {
754                 String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
755                 Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
756                 addModuleNodeTemplateReq(moduleRequirements, reqJson, reqName);
757             }
758         } else {
759             Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, REQUIREMENTS);
760             if (requirementsMapRes.isLeft()) {
761                 for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) {
762                     String reqName = entry.getKey();
763                     Object reqJson = entry.getValue();
764                     addModuleNodeTemplateReq(moduleRequirements, reqJson, reqName);
765                 }
766             }
767         }
768         return moduleRequirements;
769     }
770
771     private void addModuleNodeTemplateReq(Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
772         UploadReqInfo requirement = buildModuleNodeTemplateReg(requirementJson);
773         requirement.setName(requirementName);
774         if (moduleRequirements.containsKey(requirementName)) {
775             moduleRequirements.get(requirementName).add(requirement);
776         } else {
777             List<UploadReqInfo> list = new ArrayList<>();
778             list.add(requirement);
779             moduleRequirements.put(requirementName, list);
780         }
781     }
782
783     @SuppressWarnings("unchecked")
784     private Map<String, Map<String, UploadArtifactInfo>> createArtifactsModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
785         Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts = new HashMap<>();
786         Either<List<Object>, ResultStatusEnum> artifactsListRes = findFirstToscaListElement(nodeTemplateJsonMap, ARTIFACTS);
787         if (artifactsListRes.isLeft()) {
788             for (Object jsonArtifactObj : artifactsListRes.left().value()) {
789                 String key = ((Map<String, Object>) jsonArtifactObj).keySet().iterator().next();
790                 Object artifactJson = ((Map<String, Object>) jsonArtifactObj).get(key);
791                 addModuleNodeTemplateArtifacts(moduleArtifacts, artifactJson, key);
792             }
793         } else {
794             Either<Map<String, Map<String, Object>>, ResultStatusEnum> artifactsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, ARTIFACTS);
795             if (artifactsMapRes.isLeft()) {
796                 for (Map.Entry<String, Map<String, Object>> entry : artifactsMapRes.left().value().entrySet()) {
797                     String artifactName = entry.getKey();
798                     Object artifactJson = entry.getValue();
799                     addModuleNodeTemplateArtifacts(moduleArtifacts, artifactJson, artifactName);
800                 }
801             }
802         }
803         return moduleArtifacts;
804     }
805
806     private void addModuleNodeTemplateArtifacts(Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts, Object artifactJson,
807                                                 String artifactName) {
808         UploadArtifactInfo artifact = buildModuleNodeTemplateArtifact(artifactJson);
809         artifact.setName(artifactName);
810         if (moduleArtifacts.containsKey(ARTIFACTS.getElementName())) {
811             moduleArtifacts.get(ARTIFACTS.getElementName()).put(artifactName, artifact);
812         } else {
813             Map<String, UploadArtifactInfo> map = new HashMap<>();
814             map.put(artifactName, artifact);
815             moduleArtifacts.put(ARTIFACTS.getElementName(), map);
816         }
817     }
818
819     @SuppressWarnings("unchecked")
820     private UploadArtifactInfo buildModuleNodeTemplateArtifact(Object artifactObject) {
821         UploadArtifactInfo artifactTemplateInfo = new UploadArtifactInfo();
822         if (artifactObject instanceof Map) {
823             fillArtifact(artifactTemplateInfo, (Map<String, Object>) artifactObject);
824         }
825         return artifactTemplateInfo;
826     }
827
828     private void fillArtifact(UploadArtifactInfo artifactTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
829         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
830             artifactTemplateInfo.setType((String) nodeTemplateJsonMap.get(TYPE.getElementName()));
831         }
832         if (nodeTemplateJsonMap.containsKey(FILE.getElementName())) {
833             artifactTemplateInfo.setFile((String) nodeTemplateJsonMap.get(FILE.getElementName()));
834         }
835         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
836             Map<String, List<UploadPropInfo>> props = buildPropModuleFromYaml(nodeTemplateJsonMap);
837             if (!props.isEmpty()) {
838                 List<UploadPropInfo> properties = props.values().stream().flatMap(Collection::stream).collect(toList());
839                 artifactTemplateInfo.setProperties(properties);
840             }
841         }
842     }
843
844     @SuppressWarnings("unchecked")
845     private Map<String, List<UploadCapInfo>> createCapModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
846         Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
847         Either<List<Object>, ResultStatusEnum> capabilitiesListRes = findFirstToscaListElement(nodeTemplateJsonMap, CAPABILITIES);
848         if (capabilitiesListRes.isLeft()) {
849             for (Object jsonCapObj : capabilitiesListRes.left().value()) {
850                 String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
851                 Object capJson = ((Map<String, Object>) jsonCapObj).get(key);
852                 addModuleNodeTemplateCap(moduleCap, capJson, key);
853             }
854         } else {
855             Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, CAPABILITIES);
856             if (capabilitiesMapRes.isLeft()) {
857                 for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) {
858                     String capName = entry.getKey();
859                     Object capJson = entry.getValue();
860                     addModuleNodeTemplateCap(moduleCap, capJson, capName);
861                 }
862             }
863         }
864         return moduleCap;
865     }
866
867     private void addModuleNodeTemplateCap(Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
868         UploadCapInfo capabilityDef = buildModuleNodeTemplateCap(capJson);
869         capabilityDef.setKey(key);
870         if (moduleCap.containsKey(key)) {
871             moduleCap.get(key).add(capabilityDef);
872         } else {
873             List<UploadCapInfo> list = new ArrayList<>();
874             list.add(capabilityDef);
875             moduleCap.put(key, list);
876         }
877     }
878
879     @SuppressWarnings("unchecked")
880     private UploadCapInfo buildModuleNodeTemplateCap(Object capObject) {
881         UploadCapInfo capTemplateInfo = new UploadCapInfo();
882         if (capObject instanceof String) {
883             String nodeTemplateJsonString = (String) capObject;
884             capTemplateInfo.setNode(nodeTemplateJsonString);
885         } else if (capObject instanceof Map) {
886             fillCapability(capTemplateInfo, (Map<String, Object>) capObject);
887         }
888         return capTemplateInfo;
889     }
890
891     private void fillCapability(UploadCapInfo capTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
892         if (nodeTemplateJsonMap.containsKey(NODE.getElementName())) {
893             capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(NODE.getElementName()));
894         }
895         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
896             capTemplateInfo.setType((String) nodeTemplateJsonMap.get(TYPE.getElementName()));
897         }
898         if (nodeTemplateJsonMap.containsKey(VALID_SOURCE_TYPES.getElementName())) {
899             Either<List<Object>, ResultStatusEnum> validSourceTypesRes = findFirstToscaListElement(nodeTemplateJsonMap, VALID_SOURCE_TYPES);
900             if (validSourceTypesRes.isLeft()) {
901                 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(Object::toString).collect(toList()));
902             }
903         }
904         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
905             Map<String, List<UploadPropInfo>> props = buildPropModuleFromYaml(nodeTemplateJsonMap);
906             if (!props.isEmpty()) {
907                 List<UploadPropInfo> properties = props.values().stream().flatMap(Collection::stream).collect(toList());
908                 capTemplateInfo.setProperties(properties);
909             }
910         }
911     }
912
913     @SuppressWarnings("unchecked")
914     private UploadReqInfo buildModuleNodeTemplateReg(Object regObject) {
915         UploadReqInfo regTemplateInfo = new UploadReqInfo();
916         if (regObject instanceof String) {
917             String nodeTemplateJsonString = (String) regObject;
918             regTemplateInfo.setNode(nodeTemplateJsonString);
919         } else if (regObject instanceof Map) {
920             Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
921             if (nodeTemplateJsonMap.containsKey(NODE.getElementName())) {
922                 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(NODE.getElementName()));
923             }
924             if (nodeTemplateJsonMap.containsKey(CAPABILITY.getElementName())) {
925                 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(CAPABILITY.getElementName()));
926             }
927         }
928         return regTemplateInfo;
929     }
930
931     private Map<String, List<UploadPropInfo>> buildPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
932         Map<String, List<UploadPropInfo>> moduleProp = new HashMap<>();
933         Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(nodeTemplateJsonMap, PROPERTIES);
934         if (toscaProperties.isLeft()) {
935             Map<String, Object> jsonProperties = toscaProperties.left().value();
936             for (Map.Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
937                 if (valueNotContainsPattern(propertyValuePattern, jsonPropObj.getValue())) {
938                     addProperty(moduleProp, jsonPropObj);
939                 }
940             }
941         }
942         return moduleProp;
943     }
944
945     private void addProperty(Map<String, List<UploadPropInfo>> moduleProp, Map.Entry<String, Object> jsonPropObj) {
946         UploadPropInfo propertyDef = buildProperty(jsonPropObj.getKey(), jsonPropObj.getValue());
947         if (moduleProp.containsKey(propertyDef.getName())) {
948             moduleProp.get(propertyDef.getName()).add(propertyDef);
949         } else {
950             List<UploadPropInfo> list = new ArrayList<>();
951             list.add(propertyDef);
952             moduleProp.put(propertyDef.getName(), list);
953         }
954     }
955
956     @SuppressWarnings("unchecked")
957     private UploadPropInfo buildProperty(String propName, Object propValue) {
958         UploadPropInfo propertyDef = new UploadPropInfo();
959         propertyDef.setValue(propValue);
960         propertyDef.setName(propName);
961         if (propValue instanceof Map) {
962             if (((Map<String, Object>) propValue).containsKey(TYPE.getElementName())) {
963                 propertyDef.setType(((Map<String, Object>) propValue).get(TYPE.getElementName()).toString());
964             }
965             if (containsGetInput(propValue)) {
966                 fillInputRecursively(propName, (Map<String, Object>) propValue, propertyDef);
967             }
968             if (((Map<String, Object>) propValue).containsKey(DESCRIPTION.getElementName())) {
969                 propertyDef.setDescription(((Map<String, Object>) propValue).get(DESCRIPTION.getElementName()).toString());
970             }
971             if (((Map<String, Object>) propValue).containsKey(DEFAULT_VALUE.getElementName())) {
972                 propertyDef.setValue(((Map<String, Object>) propValue).get(DEFAULT_VALUE.getElementName()));
973             }
974             if (((Map<String, Object>) propValue).containsKey(IS_PASSWORD.getElementName())) {
975                 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(IS_PASSWORD.getElementName()).toString()));
976             } else {
977                 propertyDef.setValue(propValue);
978             }
979         } else if (propValue instanceof List) {
980             List<Object> propValueList = (List<Object>) propValue;
981             fillInputsListRecursively(propertyDef, propValueList);
982             propertyDef.setValue(propValue);
983         }
984         return propertyDef;
985     }
986
987     @SuppressWarnings("unchecked")
988     private boolean containsGetInput(Object propValue) {
989         return ((Map<String, Object>) propValue).containsKey(GET_INPUT.getElementName()) || ImportUtils.containsGetInput(propValue);
990     }
991
992     @SuppressWarnings("unchecked")
993     private void fillInputsListRecursively(UploadPropInfo propertyDef, List<Object> propValueList) {
994         for (Object objValue : propValueList) {
995             if (objValue instanceof Map) {
996                 Map<String, Object> objMap = (Map<String, Object>) objValue;
997                 if (objMap.containsKey(GET_INPUT.getElementName())) {
998                     fillInputRecursively(propertyDef.getName(), objMap, propertyDef);
999                 } else {
1000                     Set<String> keys = objMap.keySet();
1001                     findAndFillInputsListRecursively(propertyDef, objMap, keys);
1002                 }
1003             } else if (objValue instanceof List) {
1004                 List<Object> propSubValueList = (List<Object>) objValue;
1005                 fillInputsListRecursively(propertyDef, propSubValueList);
1006             }
1007         }
1008     }
1009
1010     @SuppressWarnings("unchecked")
1011     private void findAndFillInputsListRecursively(UploadPropInfo propertyDef, Map<String, Object> objMap, Set<String> keys) {
1012         for (String key : keys) {
1013             Object value = objMap.get(key);
1014             if (value instanceof Map) {
1015                 fillInputRecursively(key, (Map<String, Object>) value, propertyDef);
1016             } else if (value instanceof List) {
1017                 List<Object> propSubValueList = (List<Object>) value;
1018                 fillInputsListRecursively(propertyDef, propSubValueList);
1019             }
1020         }
1021     }
1022
1023     private void fillInputRecursively(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
1024         if (propValue.containsKey(GET_INPUT.getElementName())) {
1025             Object getInput = propValue.get(GET_INPUT.getElementName());
1026             GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
1027             List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
1028             if (getInputs == null) {
1029                 getInputs = new ArrayList<>();
1030             }
1031             if (getInput instanceof String) {
1032                 getInputInfo.setInputName((String) getInput);
1033                 getInputInfo.setPropName(propName);
1034             } else if (getInput instanceof List) {
1035                 fillInput(propName, getInput, getInputInfo);
1036             }
1037             getInputs.add(getInputInfo);
1038             propertyDef.setGet_input(getInputs);
1039             propertyDef.setValue(propValue);
1040         } else {
1041             findAndFillInputRecursively(propValue, propertyDef);
1042         }
1043     }
1044
1045     @SuppressWarnings("unchecked")
1046     private void findAndFillInputRecursively(Map<String, Object> propValue, UploadPropInfo propertyDef) {
1047         for (Map.Entry<String,Object> entry : propValue.entrySet()) {
1048             String propName = entry.getKey();
1049             Object value = entry.getValue();
1050             if (value instanceof Map) {
1051                 fillInputRecursively(propName, (Map<String, Object>) value, propertyDef);
1052             } else if (value instanceof List) {
1053                 fillInputsRecursively(propertyDef, propName, (List<Object>) value);
1054             }
1055         }
1056     }
1057
1058     private void fillInputsRecursively(UploadPropInfo propertyDef, String propName, List<Object> inputs) {
1059         inputs.stream()
1060                 .filter(Map.class::isInstance)
1061                 .forEach(o -> fillInputRecursively(propName, (Map<String, Object>) o, propertyDef));
1062     }
1063
1064     @SuppressWarnings("unchecked")
1065     private void fillInput(String propName, Object getInput, GetInputValueDataDefinition getInputInfo) {
1066         List<Object> getInputList = (List<Object>) getInput;
1067         getInputInfo.setPropName(propName);
1068         getInputInfo.setInputName((String) getInputList.get(0));
1069         if (getInputList.size() > 1) {
1070             Object indexObj = getInputList.get(1);
1071             if (indexObj instanceof Integer) {
1072                 getInputInfo.setIndexValue((Integer) indexObj);
1073             } else if (indexObj instanceof Float) {
1074                 int index = ((Float) indexObj).intValue();
1075                 getInputInfo.setIndexValue(index);
1076             } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(GET_INPUT.getElementName())) {
1077                 Object index = ((Map<String, Object>) indexObj).get(GET_INPUT.getElementName());
1078                 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
1079                 getInputInfoIndex.setInputName((String) index);
1080                 getInputInfoIndex.setPropName(propName);
1081                 getInputInfo.setGetInputIndex(getInputInfoIndex);
1082             }
1083             getInputInfo.setList(true);
1084         }
1085     }
1086
1087     private boolean valueNotContainsPattern(Pattern pattern, Object propValue) {
1088         return propValue == null || !pattern.matcher(propValue.toString()).find();
1089     }
1090
1091     private Map<String, Object> failIfNoNodeTemplates(String fileName) {
1092         janusGraphDao.rollback();
1093         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, fileName);
1094     }
1095
1096     private Object failIfNotTopologyTemplate(String fileName) {
1097         janusGraphDao.rollback();
1098         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, fileName);
1099     }
1100
1101     private void rollbackWithException(ActionStatus actionStatus, String... params) {
1102         janusGraphDao.rollback();
1103         throw new ByActionStatusComponentException(actionStatus, params);
1104     }
1105
1106     private void failOnMissingCapabilityTypes(GroupDefinition groupDefinition, List<String> missingCapTypes) {
1107         if (log.isDebugEnabled()) {
1108             log.debug(
1109                     "#failOnMissingCapabilityTypes - Failed to validate the capabilities of the group {}. The capability types {} are missing on the group type {}. ",
1110                     groupDefinition.getName(), missingCapTypes.toString(), groupDefinition.getType());
1111         }
1112         if (CollectionUtils.isNotEmpty(missingCapTypes)) {
1113             rollbackWithException(ActionStatus.MISSING_CAPABILITY_TYPE, missingCapTypes.toString());
1114         }
1115     }
1116
1117     private void failOnMissingCapabilityNames(GroupDefinition groupDefinition, List<String> missingCapNames) {
1118         if (log.isDebugEnabled()) {
1119             log.debug(
1120                     "#failOnMissingCapabilityNames - Failed to validate the capabilities of the group {}. The capabilities with the names {} are missing on the group type {}. ",
1121                     groupDefinition.getName(), missingCapNames.toString(), groupDefinition.getType());
1122         }
1123         rollbackWithException(ActionStatus.MISSING_CAPABILITIES, missingCapNames.toString(), CapabilityDataDefinition.OwnerType.GROUP.getValue(),
1124             groupDefinition.getName());
1125     }
1126 }