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