a8629aa28792e200ed4850752b7b48cd0afed34c
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.tosca.services;
18
19 import com.fasterxml.jackson.databind.ObjectMapper;
20 import com.fasterxml.jackson.databind.SerializationFeature;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.NotSerializableException;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutputStream;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.ListIterator;
33 import java.util.Map;
34 import java.util.Objects;
35 import java.util.Optional;
36 import java.util.Set;
37
38 import org.apache.commons.collections4.CollectionUtils;
39 import org.apache.commons.collections4.MapUtils;
40 import org.onap.sdc.tosca.datatypes.model.AttributeDefinition;
41 import org.onap.sdc.tosca.datatypes.model.CapabilityAssignment;
42 import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
43 import org.onap.sdc.tosca.datatypes.model.Constraint;
44 import org.onap.sdc.tosca.datatypes.model.EntrySchema;
45 import org.onap.sdc.tosca.datatypes.model.GroupDefinition;
46 import org.onap.sdc.tosca.datatypes.model.Import;
47 import org.onap.sdc.tosca.datatypes.model.InterfaceDefinition;
48 import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionTemplate;
49 import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
50 import org.onap.sdc.tosca.datatypes.model.InterfaceType;
51 import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
52 import org.onap.sdc.tosca.datatypes.model.NodeType;
53 import org.onap.sdc.tosca.datatypes.model.OperationDefinition;
54 import org.onap.sdc.tosca.datatypes.model.OperationDefinitionTemplate;
55 import org.onap.sdc.tosca.datatypes.model.OperationDefinitionType;
56 import org.onap.sdc.tosca.datatypes.model.ParameterDefinition;
57 import org.onap.sdc.tosca.datatypes.model.PolicyDefinition;
58 import org.onap.sdc.tosca.datatypes.model.PropertyDefinition;
59 import org.onap.sdc.tosca.datatypes.model.RelationshipTemplate;
60 import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
61 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
62 import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
63 import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping;
64 import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
65 import org.onap.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt;
66 import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
67 import org.onap.sdc.tosca.services.YamlUtil;
68 import org.openecomp.core.utilities.CommonMethods;
69 import org.openecomp.sdc.common.errors.CoreException;
70 import org.openecomp.sdc.common.utils.CommonUtil;
71 import org.openecomp.sdc.logging.api.Logger;
72 import org.openecomp.sdc.logging.api.LoggerFactory;
73 import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType;
74 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
75 import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType;
76 import org.openecomp.sdc.tosca.errors.CreateInterfaceObjectErrorBuilder;
77 import org.openecomp.sdc.tosca.errors.CreateInterfaceOperationObjectErrorBuilder;
78 import org.openecomp.sdc.tosca.errors.InvalidAddActionNullEntityErrorBuilder;
79 import org.openecomp.sdc.tosca.errors.InvalidRequirementAssignmentErrorBuilder;
80 import org.openecomp.sdc.tosca.errors.ToscaInvalidInterfaceValueErrorBuilder;
81 import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
82
83 /**
84  * The type Data model util.
85  */
86 public class DataModelUtil {
87
88     private static final Logger LOGGER = LoggerFactory.getLogger(DataModelUtil.class);
89     private static final String SERVICE_TEMPLATE = "Service Template";
90     private static final String NODE_TYPE = "Node Type";
91     private static final String OPERATIONS = "operations";
92
93     private DataModelUtil() {
94         // prevent instantiation
95     }
96
97     /**
98      * Add substitution mapping.
99      *
100      * @param serviceTemplate     the service template
101      * @param substitutionMapping the substitution mapping
102      */
103     public static void addSubstitutionMapping(ServiceTemplate serviceTemplate,
104                                               SubstitutionMapping substitutionMapping) {
105         if (serviceTemplate == null) {
106             throw new CoreException(
107                     new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", SERVICE_TEMPLATE)
108                             .build());
109         }
110
111         if (serviceTemplate.getTopology_template() == null) {
112             serviceTemplate.setTopology_template(new TopologyTemplate());
113         }
114         serviceTemplate.getTopology_template().setSubstitution_mappings(substitutionMapping);
115     }
116
117     /**
118      * Gets node template directives.
119      *
120      * @param nodeTemplate the node template
121      * @return the directives
122      */
123     public static List<String> getDirectives(NodeTemplate nodeTemplate) {
124         if (Objects.isNull(nodeTemplate) || Objects.isNull(nodeTemplate.getDirectives())) {
125             return Collections.emptyList();
126         }
127         return nodeTemplate.getDirectives();
128     }
129
130     /**
131      * Add substitution mapping req.
132      *
133      * @param serviceTemplate                    the service template
134      * @param substitutionMappingRequirementId   the substitution mapping requirement id
135      * @param substitutionMappingRequirementList the substitution mapping requirement list
136      */
137     public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate,
138                                                  String substitutionMappingRequirementId,
139                                                  List<String> substitutionMappingRequirementList) {
140         if (serviceTemplate == null) {
141             throw new CoreException(
142                     new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements",
143                             SERVICE_TEMPLATE).build());
144         }
145
146         if (serviceTemplate.getTopology_template() == null) {
147             serviceTemplate.setTopology_template(new TopologyTemplate());
148         }
149         if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
150             serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
151         }
152         if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
153                 == null) {
154             serviceTemplate.getTopology_template().getSubstitution_mappings()
155                     .setRequirements(new HashMap<>());
156         }
157
158         serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
159                 .put(substitutionMappingRequirementId, substitutionMappingRequirementList);
160     }
161
162     /**
163      * Add substitution mapping capability.
164      *
165      * @param serviceTemplate                   the service template
166      * @param substitutionMappingCapabilityId   the substitution mapping capability id
167      * @param substitutionMappingCapabilityList the substitution mapping capability list
168      */
169     public static void addSubstitutionMappingCapability(ServiceTemplate serviceTemplate,
170                                                         String substitutionMappingCapabilityId,
171                                                         List<String> substitutionMappingCapabilityList) {
172         if (serviceTemplate == null) {
173             throw new CoreException(
174                     new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Capabilities",
175                             SERVICE_TEMPLATE).build());
176         }
177
178         if (serviceTemplate.getTopology_template() == null) {
179             serviceTemplate.setTopology_template(new TopologyTemplate());
180         }
181         if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
182             serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
183         }
184         if (serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities()
185                 == null) {
186             serviceTemplate.getTopology_template().getSubstitution_mappings()
187                     .setCapabilities(new HashMap<>());
188         }
189
190         serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities()
191                 .putIfAbsent(substitutionMappingCapabilityId, substitutionMappingCapabilityList);
192     }
193
194     /**
195      * Gets node templates from the service template.
196      *
197      * @param serviceTemplate the service template
198      * @return the service template node templates and empty map if not present
199      */
200     public static Map<String, NodeTemplate> getNodeTemplates(ServiceTemplate serviceTemplate) {
201         if (Objects.isNull(serviceTemplate)
202                 || Objects.isNull(serviceTemplate.getTopology_template())
203                 || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates())) {
204             return new HashMap<>();
205         }
206
207         return serviceTemplate.getTopology_template().getNode_templates();
208     }
209
210     /**
211      * Gets groups from the service template.
212      *
213      * @param serviceTemplate the service template
214      * @return the service template groups and empty map if not present
215      */
216     public static Map<String, GroupDefinition> getGroups(ServiceTemplate serviceTemplate) {
217         if (Objects.isNull(serviceTemplate)
218                 || Objects.isNull(serviceTemplate.getTopology_template())
219                 || MapUtils.isEmpty(serviceTemplate.getTopology_template().getGroups())) {
220             return new HashMap<>();
221         }
222
223         return serviceTemplate.getTopology_template().getGroups();
224     }
225
226     /**
227      * Add node template.
228      *
229      * @param serviceTemplate the service template
230      * @param nodeTemplateId  the node template id
231      * @param nodeTemplate    the node template
232      */
233     public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId,
234                                        NodeTemplate nodeTemplate) {
235         if (serviceTemplate == null) {
236             throw new CoreException(
237                     new InvalidAddActionNullEntityErrorBuilder("Node Template", SERVICE_TEMPLATE).build());
238         }
239         TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
240         if (Objects.isNull(topologyTemplate)) {
241             topologyTemplate = new TopologyTemplate();
242             serviceTemplate.setTopology_template(topologyTemplate);
243         }
244         if (topologyTemplate.getNode_templates() == null) {
245             topologyTemplate.setNode_templates(new HashMap<>());
246         }
247         topologyTemplate.getNode_templates().put(nodeTemplateId, nodeTemplate);
248     }
249
250     /**
251      * Add capabilities def to node type.
252      *
253      * @param nodeType     the node type
254      * @param capabilities the capability definitions
255      */
256     public static void addNodeTypeCapabilitiesDef(NodeType nodeType,
257                                                   Map<String, CapabilityDefinition> capabilities) {
258         if (MapUtils.isEmpty(capabilities) || capabilities.entrySet().isEmpty()) {
259             return;
260         }
261
262         if (nodeType == null) {
263             throw new CoreException(
264                     new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE).build());
265         }
266
267         if (MapUtils.isEmpty(nodeType.getCapabilities())) {
268             nodeType.setCapabilities(new HashMap<>());
269         }
270         if (capabilities.size() > 0) {
271             nodeType.setCapabilities(new HashMap<>());
272         }
273         for (Map.Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
274             nodeType.getCapabilities().put(entry.getKey(), entry.getValue());
275         }
276     }
277
278     /**
279      * Add policy definition.
280      *
281      * @param serviceTemplate  the service template
282      * @param policyId         the policy id
283      * @param policyDefinition the policy definition
284      */
285     public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId,
286                                            PolicyDefinition policyDefinition) {
287         if (serviceTemplate == null) {
288             throw new CoreException(
289                     new InvalidAddActionNullEntityErrorBuilder("Policy Definition", SERVICE_TEMPLATE)
290                             .build());
291         }
292         TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
293         if (Objects.isNull(topologyTemplate)) {
294             topologyTemplate = new TopologyTemplate();
295             serviceTemplate.setTopology_template(topologyTemplate);
296         }
297         if (topologyTemplate.getPolicies() == null) {
298             topologyTemplate.setPolicies(new HashMap<>());
299         }
300         topologyTemplate.getPolicies().put(policyId, policyDefinition);
301     }
302
303     /**
304      * Add node type.
305      *
306      * @param serviceTemplate the service template
307      * @param nodeTypeId      the node type id
308      * @param nodeType        the node type
309      */
310     public static void addNodeType(ServiceTemplate serviceTemplate, String nodeTypeId,
311                                    NodeType nodeType) {
312         if (serviceTemplate == null) {
313             throw new CoreException(
314                     new InvalidAddActionNullEntityErrorBuilder(NODE_TYPE, SERVICE_TEMPLATE).build());
315         }
316         if (serviceTemplate.getNode_types() == null) {
317             serviceTemplate.setNode_types(new HashMap<>());
318         }
319         serviceTemplate.getNode_types().put(nodeTypeId, nodeType);
320     }
321
322     /**
323      * Add relationship template.
324      *
325      * @param serviceTemplate        the service template
326      * @param relationshipTemplateId the relationship template id
327      * @param relationshipTemplate   the relationship template
328      */
329     public static void addRelationshipTemplate(ServiceTemplate serviceTemplate,
330                                                String relationshipTemplateId,
331                                                RelationshipTemplate relationshipTemplate) {
332         if (serviceTemplate == null) {
333             throw new CoreException(
334                     new InvalidAddActionNullEntityErrorBuilder("Relationship Template", SERVICE_TEMPLATE)
335                             .build());
336         }
337         if (serviceTemplate.getTopology_template() == null) {
338             serviceTemplate.setTopology_template(new TopologyTemplate());
339         }
340         if (serviceTemplate.getTopology_template().getRelationship_templates() == null) {
341             serviceTemplate.getTopology_template().setRelationship_templates(new HashMap<>());
342         }
343         serviceTemplate.getTopology_template().getRelationship_templates()
344                 .put(relationshipTemplateId, relationshipTemplate);
345     }
346
347     /**
348      * Add requirement assignment.
349      *
350      * @param nodeTemplate          the node template
351      * @param requirementId         the requirement id
352      * @param requirementAssignment the requirement assignment
353      */
354     public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId,
355                                                 RequirementAssignment requirementAssignment) {
356         if (nodeTemplate == null) {
357             throw new CoreException(
358                     new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", "Node Template")
359                             .build());
360         }
361         if (requirementAssignment.getNode() == null) {
362             throw new CoreException(new InvalidRequirementAssignmentErrorBuilder(requirementId).build());
363         }
364
365         if (nodeTemplate.getRequirements() == null) {
366             nodeTemplate.setRequirements(new ArrayList<>());
367         }
368         Map<String, RequirementAssignment> requirement = new HashMap<>();
369         requirement.put(requirementId, requirementAssignment);
370         nodeTemplate.getRequirements().add(requirement);
371     }
372
373     /**
374      * Creates a new requirement assignment object for attachment requirement.
375      *
376      * @param node the node
377      * @return the attachment requirement assignment object
378      */
379     public static RequirementAssignment createAttachmentRequirementAssignment(String node) {
380         RequirementAssignment requirement = new RequirementAssignment();
381         requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT);
382         requirement.setNode(node);
383         requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO);
384         return requirement;
385     }
386
387     /**
388      * Gets node template.
389      *
390      * @param serviceTemplate the service template
391      * @param nodeTemplateId  the node template id
392      * @return the node template
393      */
394     public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate,
395                                                String nodeTemplateId) {
396         if (serviceTemplate == null
397                 || serviceTemplate.getTopology_template() == null
398                 || serviceTemplate.getTopology_template().getNode_templates() == null) {
399             return null;
400         }
401         return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId);
402     }
403
404     /**
405      * Gets node type.
406      *
407      * @param serviceTemplate the service template
408      * @param nodeTypeId      the node type id
409      * @return the node type
410      */
411     public static NodeType getNodeType(ServiceTemplate serviceTemplate, String nodeTypeId) {
412         if (serviceTemplate == null || serviceTemplate.getNode_types() == null) {
413             return null;
414         }
415         return serviceTemplate.getNode_types().get(nodeTypeId);
416     }
417
418     /**
419      * Gets requirement definition.
420      *
421      * @param nodeType                the node type
422      * @param requirementDefinitionId the requirement definition id
423      * @return the requirement definition
424      */
425     public static Optional<RequirementDefinition> getRequirementDefinition(
426             NodeType nodeType,
427             String requirementDefinitionId) {
428         if (nodeType == null || nodeType.getRequirements() == null || requirementDefinitionId == null) {
429             return Optional.empty();
430         }
431         for (Map<String, RequirementDefinition> reqMap : nodeType.getRequirements()) {
432             if (reqMap.containsKey(requirementDefinitionId)) {
433                 return Optional.of(reqMap.get(requirementDefinitionId));
434             }
435         }
436         return Optional.empty();
437     }
438
439     /**
440      * get requirement definition from requirement definition list by req key.
441      *
442      * @param requirementsDefinitionList requirement definition list
443      * @param requirementKey             requirement key
444      */
445     public static Optional<RequirementDefinition> getRequirementDefinition(
446             List<Map<String, RequirementDefinition>> requirementsDefinitionList,
447             String requirementKey) {
448         if (CollectionUtils.isEmpty(requirementsDefinitionList)) {
449             return Optional.empty();
450         }
451
452         for (Map<String, RequirementDefinition> requirementMap : requirementsDefinitionList) {
453             if (requirementMap.containsKey(requirementKey)) {
454                 return Optional.of(requirementMap.get(requirementKey));
455             }
456         }
457         return Optional.empty();
458     }
459
460     /**
461      * Gets capability definition.
462      *
463      * @param nodeType               the node type
464      * @param capabilityDefinitionId the capability definition id
465      * @return the capability definition
466      */
467     public static Optional<CapabilityDefinition> getCapabilityDefinition(
468             NodeType nodeType,
469             String capabilityDefinitionId) {
470         if (nodeType == null || nodeType.getCapabilities() == null || capabilityDefinitionId == null) {
471             return Optional.empty();
472         }
473         return Optional.ofNullable(nodeType.getCapabilities().get(capabilityDefinitionId));
474     }
475
476     /**
477      * Add group definition to topology template.
478      *
479      * @param serviceTemplate the service template
480      * @param groupName       the group name
481      * @param group           the group
482      */
483     public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate,
484                                                             String groupName, GroupDefinition group) {
485         if (serviceTemplate == null) {
486             throw new CoreException(
487                     new InvalidAddActionNullEntityErrorBuilder("Group Definition", SERVICE_TEMPLATE)
488                             .build());
489         }
490
491         TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
492         if (Objects.isNull(topologyTemplate)) {
493             topologyTemplate = new TopologyTemplate();
494             serviceTemplate.setTopology_template(topologyTemplate);
495         }
496         if (topologyTemplate.getGroups() == null) {
497             topologyTemplate.setGroups(new HashMap<>());
498         }
499         if (serviceTemplate.getTopology_template().getGroups() == null) {
500             Map<String, GroupDefinition> groups = new HashMap<>();
501             serviceTemplate.getTopology_template().setGroups(groups);
502         }
503
504         serviceTemplate.getTopology_template().getGroups().put(groupName, group);
505     }
506
507     /**
508      * Adds a group member to an existing group in the service template.
509      *
510      * @param serviceTemplate the service template
511      * @param groupName       the group name
512      * @param groupMemberId   the group member id
513      */
514     public static void addGroupMember(ServiceTemplate serviceTemplate,
515                                       String groupName,
516                                       String groupMemberId) {
517         TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
518         if (Objects.isNull(topologyTemplate)
519                 || topologyTemplate.getGroups() == null
520                 || topologyTemplate.getGroups().get(groupName) == null) {
521             return;
522         }
523
524         GroupDefinition groupDefinition = topologyTemplate.getGroups().get(groupName);
525         if (CollectionUtils.isEmpty(groupDefinition.getMembers())) {
526             groupDefinition.setMembers(new ArrayList<>());
527         }
528
529         if (!groupDefinition.getMembers().contains(groupMemberId)) {
530             groupDefinition.getMembers().add(groupMemberId);
531         }
532     }
533
534     /**
535      * Create parameter definition property definition.
536      *
537      * @param type        the type
538      * @param description the description
539      * @param required    the required
540      * @param constraints the constraints
541      * @param entrySchema the entry schema
542      * @param defaultVal  the default val
543      * @return the property definition
544      */
545     public static ParameterDefinition createParameterDefinition(String type, String description,
546                                                                 boolean required,
547                                                                 List<Constraint> constraints,
548                                                                 EntrySchema entrySchema,
549                                                                 Object defaultVal) {
550         ParameterDefinition paramDef = new ParameterDefinition();
551         paramDef.setType(type);
552         paramDef.setDescription(description);
553         paramDef.setRequired(required);
554         paramDef.setConstraints(constraints);
555         paramDef.setEntry_schema(entrySchema == null ? null : entrySchema.clone());
556         paramDef.set_default(defaultVal);
557         return paramDef;
558     }
559
560     /**
561      * Create requirement requirement definition.
562      *
563      * @param capability   the capability
564      * @param node         the node
565      * @param relationship the relationship
566      * @param occurrences  the occurrences
567      * @return the requirement definition
568      */
569     public static RequirementDefinition createRequirement(String capability, String node,
570                                                           String relationship, Object[] occurrences) {
571         RequirementDefinition requirementDefinition = new RequirementDefinition();
572         requirementDefinition.setCapability(capability);
573         requirementDefinition.setNode(node);
574         requirementDefinition.setRelationship(relationship);
575         if (occurrences != null) {
576             requirementDefinition.setOccurrences(occurrences);
577         }
578         return requirementDefinition;
579     }
580
581     /**
582      * Create entry schema entry schema.
583      *
584      * @param type        the type
585      * @param description the description
586      * @param constraints the constraints
587      * @return the entry schema
588      */
589     public static EntrySchema createEntrySchema(String type, String description,
590                                                 List<Constraint> constraints) {
591         if (Objects.isNull(type) && Objects.isNull(description)
592                 && CollectionUtils.isEmpty(constraints)) {
593             return null;
594         }
595
596         EntrySchema entrySchema = new EntrySchema();
597         entrySchema.setType(type);
598         entrySchema.setDescription(description);
599         entrySchema.setConstraints(constraints);
600         return entrySchema;
601     }
602
603     /**
604      * Create get input property value from list parameter map.
605      *
606      * @param inputPropertyListName the input property list name
607      * @param indexInTheList        the index in the list
608      * @param nestedPropertyName    the nested property name
609      * @return the map
610      */
611     public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName,
612                                                                    int indexInTheList,
613                                                                    String... nestedPropertyName) {
614         List<Object> propertyList = new ArrayList<>();
615         propertyList.add(inputPropertyListName);
616         propertyList.add(indexInTheList);
617         if (nestedPropertyName != null) {
618             Collections.addAll(propertyList, nestedPropertyName);
619         }
620         Map<String, Object> getInputProperty = new HashMap<>();
621         getInputProperty.put(ToscaFunctions.GET_INPUT.getDisplayName(), propertyList);
622         return getInputProperty;
623     }
624
625     /**
626      * Convert property def to parameter def parameter definition ext.
627      *
628      * @param propertyDefinition the property definition
629      * @return the parameter definition ext
630      */
631     public static ParameterDefinitionExt convertPropertyDefToParameterDef(
632             PropertyDefinition propertyDefinition) {
633         if (propertyDefinition == null) {
634             return null;
635         }
636
637         ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt();
638         parameterDefinition.setType(propertyDefinition.getType());
639         parameterDefinition.setDescription(propertyDefinition.getDescription());
640         parameterDefinition.setRequired(propertyDefinition.getRequired());
641         parameterDefinition.set_default(propertyDefinition.get_default());
642         parameterDefinition.setStatus(propertyDefinition.getStatus());
643         parameterDefinition.setConstraints(propertyDefinition.getConstraints());
644         parameterDefinition.setEntry_schema(Objects.isNull(propertyDefinition.getEntry_schema()) ? null
645                 : propertyDefinition.getEntry_schema().clone());
646         parameterDefinition.setHidden(false);
647         parameterDefinition.setImmutable(false);
648         return parameterDefinition;
649     }
650
651     /**
652      * Convert attribute def to parameter def parameter definition ext.
653      *
654      * @param attributeDefinition the attribute definition
655      * @param outputValue         the output value
656      * @return the parameter definition ext
657      */
658     public static ParameterDefinitionExt convertAttributeDefToParameterDef(
659             AttributeDefinition attributeDefinition, Map<String, List> outputValue) {
660         if (attributeDefinition == null) {
661             return null;
662         }
663         ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt();
664         parameterDefinition.setDescription(attributeDefinition.getDescription());
665         parameterDefinition.setValue(outputValue);
666         return parameterDefinition;
667     }
668
669     public static boolean isNodeTemplate(String entryId, ServiceTemplate serviceTemplate) {
670         return serviceTemplate.getTopology_template().getNode_templates() != null
671                 && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null;
672     }
673
674     /**
675      * Add Input parameter.
676      *
677      * @param serviceTemplate       the service template
678      * @param parameterDefinitionId the parameter definition id
679      * @param parameterDefinition   the parameter definition
680      */
681     public static void addInputParameterToTopologyTemplate(ServiceTemplate serviceTemplate,
682                                                            String parameterDefinitionId,
683                                                            ParameterDefinition parameterDefinition) {
684         if (Objects.isNull(serviceTemplate)) {
685             throw new CoreException(
686                     new InvalidAddActionNullEntityErrorBuilder("Topology Template Input Parameter",
687                             SERVICE_TEMPLATE).build());
688         }
689         TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
690         if (Objects.isNull(topologyTemplate)) {
691             topologyTemplate = new TopologyTemplate();
692             serviceTemplate.setTopology_template(topologyTemplate);
693         }
694         if (topologyTemplate.getInputs() == null) {
695             topologyTemplate.setInputs(new HashMap<>());
696         }
697         topologyTemplate.getInputs().put(parameterDefinitionId, parameterDefinition);
698     }
699
700     /**
701      * Add Output parameter.
702      *
703      * @param serviceTemplate       the service template
704      * @param parameterDefinitionId the parameter definition id
705      * @param parameterDefinition   the parameter definition
706      */
707     public static void addOutputParameterToTopologyTemplate(ServiceTemplate serviceTemplate,
708                                                             String parameterDefinitionId,
709                                                             ParameterDefinition parameterDefinition) {
710         if (Objects.isNull(serviceTemplate)) {
711             throw new CoreException(
712                     new InvalidAddActionNullEntityErrorBuilder("Topology Template Output Parameter",
713                             SERVICE_TEMPLATE).build());
714         }
715         TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
716         if (Objects.isNull(topologyTemplate)) {
717             topologyTemplate = new TopologyTemplate();
718             serviceTemplate.setTopology_template(topologyTemplate);
719         }
720         if (topologyTemplate.getOutputs() == null) {
721             topologyTemplate.setOutputs(new HashMap<>());
722         }
723         topologyTemplate.getOutputs().put(parameterDefinitionId, parameterDefinition);
724     }
725
726     /**
727      * Add requirement def to requirement def list.
728      *
729      * @param requirementList requirement list
730      * @param requirementDef  added requirement def
731      */
732     public static void addRequirementToList(List<Map<String, RequirementDefinition>> requirementList,
733                                             Map<String, RequirementDefinition> requirementDef) {
734         if (requirementDef == null) {
735             return;
736         }
737         if (requirementList == null) {
738             requirementList = new ArrayList<>();
739         }
740
741         for (Map.Entry<String, RequirementDefinition> entry : requirementDef.entrySet()) {
742             CommonMethods.mergeEntryInList(entry.getKey(), entry.getValue(), requirementList);
743         }
744     }
745
746     /**
747      * get node template requirement.
748      *
749      * @param nodeTemplate node template
750      */
751     public static Map<String, RequirementAssignment> getNodeTemplateRequirements(
752             NodeTemplate nodeTemplate) {
753         if (Objects.isNull(nodeTemplate)) {
754             return null;
755         }
756         List<Map<String, RequirementAssignment>> templateRequirements = nodeTemplate.getRequirements();
757
758         Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
759         if (CollectionUtils.isEmpty(templateRequirements)) {
760             return nodeTemplateRequirementsAssignment;
761         }
762         YamlUtil yamlUtil = new YamlUtil();
763         for (Map<String, RequirementAssignment> requirementAssignmentMap : templateRequirements) {
764             for (Map.Entry<String, RequirementAssignment> requirementEntry : requirementAssignmentMap
765                     .entrySet()) {
766                 RequirementAssignment requirementAssignment = (
767                         yamlUtil
768                                 .yamlToObject(yamlUtil.objectToYaml(requirementEntry.getValue()),
769                                         RequirementAssignment.class));
770                 nodeTemplateRequirementsAssignment
771                         .put(requirementEntry.getKey(), requirementAssignment);
772             }
773         }
774         return nodeTemplateRequirementsAssignment;
775     }
776
777     /**
778      * Gets the list of requirements for the node template.
779      *
780      * @param nodeTemplate the node template
781      * @return the node template requirement list and null if the node has no requirements
782      */
783     public static List<Map<String, RequirementAssignment>> getNodeTemplateRequirementList(
784             NodeTemplate nodeTemplate) {
785         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
786         //Creating concrete objects
787         List<Map<String, RequirementAssignment>> requirements = nodeTemplate.getRequirements();
788         List<Map<String, RequirementAssignment>> concreteRequirementList = null;
789         if (requirements != null) {
790             concreteRequirementList = new ArrayList<>();
791             ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements
792                     .listIterator();
793             while (reqListIterator.hasNext()) {
794                 Map<String, RequirementAssignment> requirement = reqListIterator.next();
795                 Map<String, RequirementAssignment> concreteRequirement = new HashMap<>();
796                 for (Map.Entry<String, RequirementAssignment> reqEntry : requirement.entrySet()) {
797                     RequirementAssignment requirementAssignment = (
798                             toscaExtensionYamlUtil
799                                     .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()),
800                                             RequirementAssignment.class));
801                     concreteRequirement.put(reqEntry.getKey(), requirementAssignment);
802                     concreteRequirementList.add(concreteRequirement);
803                     reqListIterator.remove();
804                 }
805             }
806             requirements.clear();
807             requirements.addAll(concreteRequirementList);
808             nodeTemplate.setRequirements(requirements);
809         }
810         return concreteRequirementList;
811     }
812
813     /**
814      * get requirement assignment from requirement assignment list by req key.
815      *
816      * @param requirementsAssignmentList requirement definition list
817      * @param requirementKey             requirement key
818      */
819     public static Optional<List<RequirementAssignment>> getRequirementAssignment(
820             List<Map<String, RequirementAssignment>> requirementsAssignmentList,
821             String requirementKey) {
822         if (CollectionUtils.isEmpty(requirementsAssignmentList)) {
823             return Optional.empty();
824         }
825
826         List<RequirementAssignment> matchRequirementAssignmentList = new ArrayList<>();
827         for (Map<String, RequirementAssignment> requirementMap : requirementsAssignmentList) {
828             if (requirementMap.containsKey(requirementKey)) {
829                 YamlUtil yamlUtil = new YamlUtil();
830                 RequirementAssignment requirementAssignment = (
831                         yamlUtil
832                                 .yamlToObject(yamlUtil.objectToYaml(requirementMap.get(requirementKey)),
833                                         RequirementAssignment.class));
834                 matchRequirementAssignmentList.add(requirementAssignment);
835             }
836         }
837         if (CollectionUtils.isEmpty(matchRequirementAssignmentList)) {
838             return Optional.empty();
839         }
840         return Optional.of(matchRequirementAssignmentList);
841     }
842
843     /**
844      * remove requirement definition from requirement definition list by req key.
845      *
846      * @param requirementsDefinitionList requirement definition list
847      * @param requirementKey             requirement key
848      */
849     public static void removeRequirementsDefinition(
850             List<Map<String, RequirementDefinition>> requirementsDefinitionList,
851             String requirementKey) {
852         if (requirementsDefinitionList == null) {
853             return;
854         }
855
856         List<Map<String, RequirementDefinition>> mapToBeRemoved = new ArrayList<>();
857         for (Map<String, RequirementDefinition> reqMap : requirementsDefinitionList) {
858             reqMap.remove(requirementKey);
859             if (reqMap.isEmpty()) {
860                 mapToBeRemoved.add(reqMap);
861             }
862         }
863         for (Map<String, RequirementDefinition> removeMap : mapToBeRemoved) {
864             requirementsDefinitionList.remove(removeMap);
865         }
866     }
867
868     /**
869      * remove requirement assignment from requirement definition list by req key.
870      *
871      * @param requirementsAssignmentList requirement Assignment list
872      * @param requirementKey             requirement key
873      */
874     public static void removeRequirementsAssignment(
875             List<Map<String, RequirementAssignment>> requirementsAssignmentList,
876             String requirementKey) {
877         if (requirementsAssignmentList == null) {
878             return;
879         }
880
881         List<Map<String, RequirementAssignment>> mapToBeRemoved = new ArrayList<>();
882         for (Map<String, RequirementAssignment> reqMap : requirementsAssignmentList) {
883             reqMap.remove(requirementKey);
884             if (reqMap.isEmpty()) {
885                 mapToBeRemoved.add(reqMap);
886             }
887         }
888         for (Map<String, RequirementAssignment> removeMap : mapToBeRemoved) {
889             requirementsAssignmentList.remove(removeMap);
890         }
891     }
892
893
894     /**
895      * Remove requirement assignment.
896      *
897      * @param nodeTemplate                     the node template
898      * @param requirementKey                   the requirement key
899      * @param requirementAssignmentToBeDeleted the requirement assignment to be deleted
900      */
901     public static void removeRequirementAssignment(
902             NodeTemplate nodeTemplate,
903             String requirementKey,
904             RequirementAssignment requirementAssignmentToBeDeleted) {
905         ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
906         List<Map<String, RequirementAssignment>> nodeTemplateRequirements = nodeTemplate
907                 .getRequirements();
908         if (nodeTemplateRequirements == null) {
909             return;
910         }
911
912         ListIterator<Map<String, RequirementAssignment>> iter = nodeTemplateRequirements.listIterator();
913         while (iter.hasNext()) {
914             Map<String, RequirementAssignment> reqMap = iter.next();
915             RequirementAssignment requirementAssignment = reqMap.get(requirementKey);
916             if (requirementAssignment != null) {
917                 boolean isDesiredRequirementAssignment = toscaAnalyzerService
918                         .isDesiredRequirementAssignment(requirementAssignment,
919                                 requirementAssignmentToBeDeleted.getCapability(),
920                                 requirementAssignmentToBeDeleted.getNode(),
921                                 requirementAssignmentToBeDeleted.getRelationship());
922                 if (isDesiredRequirementAssignment) {
923                     iter.remove();
924                 }
925             }
926         }
927     }
928
929     /**
930      * Return the suffix of the input namespace For an exampale - for abc.sdf.vsrx, return vsrx
931      *
932      * @param namespace namespace
933      * @return String namespace suffix
934      */
935     public static String getNamespaceSuffix(String namespace) {
936         if (namespace == null) {
937             return null;
938         }
939         String delimiterChar = ".";
940         if (namespace.contains(delimiterChar)) {
941             return namespace.substring(namespace.lastIndexOf(delimiterChar) + 1);
942         }
943         return namespace;
944     }
945
946     /**
947      * Return true if the input import exist in the input imports list.
948      *
949      * @param imports  namespace
950      * @param importId namespace
951      * @return true if exist, false if not exist
952      */
953     public static boolean isImportAddedToServiceTemplate(List<Map<String, Import>> imports,
954                                                          String importId) {
955         for (Map<String, Import> anImport : imports) {
956             if (anImport.containsKey(importId)) {
957                 return true;
958             }
959         }
960         return false;
961     }
962
963     /**
964      * Get output parameter according to the input outputParameterId.
965      *
966      * @param serviceTemplate   service template
967      * @param outputParameterId output parameter id
968      * @return ParameterDefinition - output parameter
969      */
970     public static ParameterDefinition getOuputParameter(ServiceTemplate serviceTemplate,
971                                                         String outputParameterId) {
972         if (serviceTemplate == null
973                 || serviceTemplate.getTopology_template() == null
974                 || serviceTemplate.getTopology_template().getOutputs() == null) {
975             return null;
976         }
977         return serviceTemplate.getTopology_template().getOutputs().get(outputParameterId);
978     }
979
980     /**
981      * Gets input parameters in a service template.
982      *
983      * @param serviceTemplate the service template
984      * @return the input parameters
985      */
986     public static Map<String, ParameterDefinition> getInputParameters(ServiceTemplate
987                                                                               serviceTemplate) {
988         if (serviceTemplate == null
989                 || serviceTemplate.getTopology_template() == null
990                 || serviceTemplate.getTopology_template().getInputs() == null) {
991             return null;
992         }
993         return serviceTemplate.getTopology_template().getInputs();
994     }
995
996     /**
997      * Gets relationship templates in a service template.
998      *
999      * @param serviceTemplate the service template
1000      * @return the relationship template
1001      */
1002     public static Map<String, RelationshipTemplate> getRelationshipTemplates(ServiceTemplate
1003                                                                                      serviceTemplate) {
1004         if (serviceTemplate == null
1005                 || serviceTemplate.getTopology_template() == null
1006                 || serviceTemplate.getTopology_template().getRelationship_templates() == null) {
1007             return null;
1008         }
1009         return serviceTemplate.getTopology_template().getRelationship_templates();
1010     }
1011
1012     /**
1013      * Get property value according to the input propertyId.
1014      *
1015      * @param nodeTemplate node template
1016      * @param propertyId   property id
1017      * @return Object        property Value
1018      */
1019     public static Object getPropertyValue(NodeTemplate nodeTemplate,
1020                                           String propertyId) {
1021         if (nodeTemplate == null
1022                 || nodeTemplate.getProperties() == null) {
1023             return null;
1024         }
1025         return nodeTemplate.getProperties().get(propertyId);
1026     }
1027
1028     /**
1029      * Get node template properties according to the input node template id.
1030      *
1031      * @param serviceTemplate service template
1032      * @param nodeTemplateId  node template id
1033      * @return node template properties
1034      */
1035     public static Map<String, Object> getNodeTemplateProperties(ServiceTemplate serviceTemplate,
1036                                                                 String nodeTemplateId) {
1037         if (serviceTemplate == null
1038                 || serviceTemplate.getTopology_template() == null
1039                 || serviceTemplate.getTopology_template().getNode_templates() == null
1040                 || serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) == null) {
1041             return null;
1042         }
1043         return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId)
1044                 .getProperties();
1045     }
1046
1047     /**
1048      * Adds a property to a node template.
1049      *
1050      * @param nodeTemplate  the node template
1051      * @param propertyKey   the property key
1052      * @param propertyValue the property value
1053      */
1054     public static void addNodeTemplateProperty(NodeTemplate nodeTemplate,
1055                                                String propertyKey,
1056                                                Object propertyValue) {
1057         if (Objects.isNull(nodeTemplate)) {
1058             return;
1059         }
1060
1061         if (MapUtils.isEmpty(nodeTemplate.getProperties())) {
1062             nodeTemplate.setProperties(new HashMap<>());
1063         }
1064
1065         nodeTemplate.getProperties().put(propertyKey, propertyValue);
1066     }
1067
1068     /**
1069      * Gets substitution mappings in a service template.
1070      *
1071      * @param serviceTemplate the service template
1072      * @return the substitution mappings
1073      */
1074     public static SubstitutionMapping getSubstitutionMappings(ServiceTemplate serviceTemplate) {
1075         if (serviceTemplate == null
1076                 || serviceTemplate.getTopology_template() == null
1077                 || serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
1078             return null;
1079         }
1080         return serviceTemplate.getTopology_template().getSubstitution_mappings();
1081     }
1082
1083
1084     /**
1085      * Compare two requirement assignment objects for equality.
1086      *
1087      * @param first  the first requirement assignment object
1088      * @param second the second  requirement assignment object
1089      * @return true if objects are equal and false otherwise
1090      */
1091     public static boolean compareRequirementAssignment(RequirementAssignment first,
1092                                                        RequirementAssignment second) {
1093         return (
1094                 first.getCapability().equals(second.getCapability())
1095                         && first.getNode().equals(second.getNode())
1096                         && first.getRelationship().equals(second.getRelationship()));
1097     }
1098
1099     /**
1100      * Gets a deep copy clone of the input object.
1101      *
1102      * @param <T>         the type parameter
1103      * @param objectValue the object value
1104      * @param clazz       the clazz
1105      * @return the cloned object
1106      */
1107     public static <T> Object getClonedObject(Object objectValue, Class<T> clazz) {
1108         YamlUtil yamlUtil = new ToscaExtensionYamlUtil();
1109         Object clonedObjectValue;
1110         String objectToYaml = yamlUtil.objectToYaml(objectValue);
1111         clonedObjectValue = yamlUtil.yamlToObject(objectToYaml, clazz);
1112         return clonedObjectValue;
1113     }
1114
1115     /**
1116      * Gets a deep copy clone of the input object.
1117      *
1118      * @param obj the object to be cloned
1119      * @return the cloned object
1120      */
1121     public static Object getClonedObject(Object obj) {
1122         Object clonedObjectValue;
1123         try {
1124             //Serialize object
1125             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1126             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
1127             objectOutputStream.writeObject(obj);
1128             //Deserialize object
1129             ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream
1130                     .toByteArray());
1131             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
1132             clonedObjectValue = objectInputStream.readObject();
1133         } catch (NotSerializableException ex) {
1134             LOGGER.debug(ex.getMessage(), ex);
1135             return getClonedObject(obj, obj.getClass());
1136         } catch (IOException | ClassNotFoundException ex) {
1137             LOGGER.debug(ex.getMessage(), ex);
1138             return null;
1139         }
1140         return clonedObjectValue;
1141     }
1142
1143     /**
1144      * Add substitution filtering property.
1145      *
1146      * @param templateName the substitution service template name
1147      * @param nodeTemplate the node template
1148      * @param count        the count
1149      */
1150     public static void addSubstitutionFilteringProperty(String templateName,
1151                                                         NodeTemplate nodeTemplate, int count) {
1152         Map<String, Object> serviceTemplateFilterPropertyValue = new HashMap<>();
1153         Map<String, Object> properties = nodeTemplate.getProperties();
1154         serviceTemplateFilterPropertyValue.put(ToscaConstants
1155                 .SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, templateName);
1156         serviceTemplateFilterPropertyValue.put(ToscaConstants.COUNT_PROPERTY_NAME, count);
1157         properties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME,
1158                 serviceTemplateFilterPropertyValue);
1159         nodeTemplate.setProperties(properties);
1160     }
1161
1162     /**
1163      * Adding binding requirement from port node template to compute node template.
1164      *
1165      * @param computeNodeTemplateId compute node template id
1166      * @param portNodeTemplate      port node template
1167      */
1168     public static void addBindingReqFromPortToCompute(String computeNodeTemplateId,
1169                                                       NodeTemplate portNodeTemplate) {
1170         RequirementAssignment requirementAssignment = new RequirementAssignment();
1171         requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
1172         requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
1173         requirementAssignment.setNode(computeNodeTemplateId);
1174         addRequirementAssignment(portNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID,
1175                 requirementAssignment);
1176     }
1177
1178     /**
1179      * Create substitution template substitution mapping.
1180      *
1181      * @param nodeTypeKey          the node type key
1182      * @param substitutionNodeType the substitution node type
1183      * @param mapping              the mapping
1184      * @return the substitution mapping
1185      */
1186     public static SubstitutionMapping createSubstitutionTemplateSubMapping(
1187             String nodeTypeKey,
1188             NodeType substitutionNodeType,
1189             Map<String, Map<String, List<String>>> mapping) {
1190         SubstitutionMapping substitutionMapping = new SubstitutionMapping();
1191         substitutionMapping.setNode_type(nodeTypeKey);
1192         substitutionMapping.setCapabilities(
1193                 manageCapabilityMapping(substitutionNodeType.getCapabilities(), mapping.get(ToscaConstants
1194                         .CAPABILITY)));
1195         substitutionMapping.setRequirements(
1196                 manageRequirementMapping(substitutionNodeType.getRequirements(),
1197                         mapping.get("requirement")));
1198         return substitutionMapping;
1199     }
1200
1201     /**
1202      * Add node template capability.
1203      *
1204      * @param nodeTemplate         the node template
1205      * @param capabilityId         the capability id
1206      * @param capabilityProperties the capability properties
1207      * @param capabilityAttributes the capability attributes
1208      */
1209     public static void addNodeTemplateCapability(NodeTemplate nodeTemplate, String capabilityId,
1210                                                  Map<String, Object> capabilityProperties,
1211                                                  Map<String, Object> capabilityAttributes) {
1212         Map<String, CapabilityAssignment> capabilities = nodeTemplate.getCapabilities();
1213         if (Objects.isNull(capabilities)) {
1214             capabilities = new HashMap<>();
1215         }
1216         CapabilityAssignment capabilityAssignment = new CapabilityAssignment();
1217         capabilityAssignment.setProperties(capabilityProperties);
1218         capabilityAssignment.setAttributes(capabilityAttributes);
1219         capabilities.put(capabilityId, capabilityAssignment);
1220         nodeTemplate.setCapabilities(capabilities);
1221     }
1222
1223     private static Map<String, List<String>> manageRequirementMapping(
1224             List<Map<String, RequirementDefinition>> requirementList,
1225             Map<String, List<String>> requirementSubstitutionMapping) {
1226         if (requirementList == null) {
1227             return null;
1228         }
1229         Map<String, List<String>> requirementMapping = new HashMap<>();
1230         String requirementKey;
1231         List<String> requirementMap;
1232         for (Map<String, RequirementDefinition> requirementDefMap : requirementList) {
1233             for (Map.Entry<String, RequirementDefinition> entry : requirementDefMap.entrySet()) {
1234                 requirementKey = entry.getKey();
1235                 requirementMap = requirementSubstitutionMapping.get(requirementKey);
1236                 requirementMapping.put(requirementKey, requirementMap);
1237             }
1238         }
1239         return requirementMapping;
1240     }
1241
1242     private static Map<String, List<String>> manageCapabilityMapping(
1243             Map<String, CapabilityDefinition> capabilities,
1244             Map<String, List<String>> capabilitySubstitutionMapping) {
1245         if (capabilities == null) {
1246             return null;
1247         }
1248
1249         Map<String, List<String>> capabilityMapping = new HashMap<>();
1250         String capabilityKey;
1251         List<String> capabilityMap;
1252         for (Map.Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
1253             capabilityKey = entry.getKey();
1254             capabilityMap = capabilitySubstitutionMapping.get(capabilityKey);
1255             capabilityMapping.put(capabilityKey, capabilityMap);
1256         }
1257         return capabilityMapping;
1258     }
1259
1260
1261     public static void addInterfaceOperation(ServiceTemplate serviceTemplate,
1262                                              String interfaceId,
1263                                              String operationId,
1264                                              OperationDefinition operationDefinition) {
1265         Map<String, Object> interfaceTypes = serviceTemplate.getInterface_types();
1266         if (MapUtils.isEmpty(interfaceTypes)
1267                 || Objects.isNull(interfaceTypes.get(interfaceId))) {
1268             return;
1269         }
1270
1271         Object interfaceObject = interfaceTypes.get(interfaceId);
1272         Map<String, Object> interfaceAsMap = CommonUtil.getObjectAsMap(interfaceObject);
1273         interfaceAsMap.put(operationId, operationDefinition);
1274     }
1275
1276     public static Map<String, InterfaceType> getInterfaceTypes(ServiceTemplate serviceTemplate) {
1277         Map<String, Object> interfaceTypes = serviceTemplate.getInterface_types();
1278
1279         if (MapUtils.isEmpty(interfaceTypes)) {
1280             return new HashMap<>();
1281         }
1282
1283         Map<String, InterfaceType> convertedInterfaceTypes = new HashMap<>();
1284         for (Map.Entry<String, Object> interfaceEntry : interfaceTypes.entrySet()) {
1285             try {
1286                 Optional<InterfaceType> interfaceType =
1287                         convertObjToInterfaceType(interfaceEntry.getKey(), interfaceEntry.getValue());
1288                 interfaceType.ifPresent(
1289                         interfaceValue -> convertedInterfaceTypes.put(interfaceEntry.getKey(), interfaceValue));
1290             } catch (Exception e) {
1291                 LOGGER.error("Cannot create interface object", e);
1292                 throw new CoreException(
1293                         new ToscaInvalidInterfaceValueErrorBuilder(e.getMessage()).build());
1294             }
1295         }
1296
1297         return convertedInterfaceTypes;
1298     }
1299
1300     public static <T extends InterfaceDefinition> Optional<T> convertObjToInterfaceDefinition(String interfaceId,
1301                                                                                               Object interfaceObj,
1302                                                                                               Class<T> interfaceClass) {
1303         try {
1304             Optional<T> interfaceDefinition =
1305                     CommonUtil.createObjectUsingSetters(interfaceObj, interfaceClass);
1306             interfaceDefinition.ifPresent(interfaceDefinitionType1 -> updateInterfaceDefinitionOperations(
1307                     CommonUtil.getObjectAsMap(interfaceObj),
1308                     interfaceDefinitionType1, getOperationClass(interfaceClass)));
1309             return interfaceDefinition;
1310         } catch (Exception ex) {
1311             LOGGER.error("Could not create {} from {}", InterfaceDefinitionType.class.getName(),
1312                     interfaceId, ex);
1313             throw new CoreException(
1314                     new CreateInterfaceObjectErrorBuilder(InterfaceDefinitionType.class.getName(),
1315                             interfaceId,
1316                             ex.getMessage()).build());
1317         }
1318
1319     }
1320
1321     private static <T extends OperationDefinition, V extends InterfaceDefinition> Class<T> getOperationClass(
1322             Class<V> interfaceClass) {
1323         return interfaceClass.equals(InterfaceDefinitionType.class)
1324                 ? (Class<T>) OperationDefinitionType.class
1325                 : (Class<T>) OperationDefinitionTemplate.class;
1326     }
1327
1328     public static Optional<InterfaceType> convertObjToInterfaceType(String interfaceId,
1329                                                                     Object interfaceObj) {
1330         try {
1331             Optional<InterfaceType> interfaceType =
1332                     CommonUtil.createObjectUsingSetters(interfaceObj, InterfaceType.class);
1333             interfaceType.ifPresent(
1334                     interfaceType1 -> updateInterfaceTypeOperations(CommonUtil.getObjectAsMap(interfaceObj),
1335                             interfaceType1));
1336             return interfaceType;
1337         } catch (Exception ex) {
1338             LOGGER.error("Could not create {} from {}", InterfaceType.class.getName(), interfaceId, ex);
1339             throw new CoreException(
1340                     new CreateInterfaceObjectErrorBuilder(InterfaceType.class.getName(), interfaceId,
1341                             ex.getMessage()).build());
1342         }
1343     }
1344
1345     public static Optional<Object> convertInterfaceTypeToObj(InterfaceType interfaceType) {
1346         return converInterfaceToToscaInterfaceObj(interfaceType);
1347     }
1348
1349     private static Optional<Object> converInterfaceToToscaInterfaceObj(Object interfaceEntity) {
1350         if (Objects.isNull(interfaceEntity)) {
1351             return Optional.empty();
1352         }
1353
1354         Map<String, Object> interfaceAsMap = CommonUtil.getObjectAsMap(interfaceEntity);
1355         Map<String, Object> operations = (Map<String, Object>) interfaceAsMap.get(OPERATIONS);
1356         if (MapUtils.isNotEmpty(operations)) {
1357             interfaceAsMap.remove(OPERATIONS);
1358             interfaceAsMap.putAll(operations);
1359         }
1360
1361         ObjectMapper objectMapper = new ObjectMapper();
1362         objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
1363         return Optional.of(objectMapper.convertValue(interfaceAsMap, Object.class));
1364     }
1365
1366     private static void updateInterfaceTypeOperations(Map<String, Object> interfaceAsMap,
1367                                                       InterfaceType interfaceType) {
1368
1369         Set<String> fieldNames = CommonUtil.getClassFieldNames(InterfaceType.class);
1370
1371         for (Map.Entry<String, Object> entry : interfaceAsMap.entrySet()) {
1372             Optional<? extends OperationDefinition> operationDefinition =
1373                     createOperation(entry.getKey(), entry.getValue(), fieldNames,
1374                             OperationDefinitionType.class);
1375             operationDefinition
1376                     .ifPresent(operation -> interfaceType.addOperation(entry.getKey(), operation));
1377         }
1378     }
1379
1380     private static Optional<? extends OperationDefinition> createOperation(String propertyName,
1381                                                                            Object operationCandidate,
1382                                                                            Set<String> fieldNames,
1383                                                                            Class<? extends OperationDefinition>
1384                                                                                    operationClass) {
1385         if (!fieldNames.contains(propertyName)) {
1386             try {
1387                 return CommonUtil.createObjectUsingSetters(operationCandidate, operationClass);
1388             } catch (Exception ex) {
1389                 LOGGER.error("Could not create Operation from {}", propertyName, ex);
1390                 throw new CoreException(
1391                         new CreateInterfaceOperationObjectErrorBuilder(propertyName, ex.getMessage()).build());
1392             }
1393         }
1394
1395         return Optional.empty();
1396     }
1397
1398     private static <T extends OperationDefinition> void updateInterfaceDefinitionOperations(Map<String, Object>
1399                                                                                                     interfaceAsMap,
1400                                                                                             InterfaceDefinition
1401                                                                                                     interfaceDefinition,
1402                                                                                             Class<T> operationClass) {
1403         Set<String> fieldNames = CommonUtil.getClassFieldNames(interfaceDefinition.getClass());
1404         Optional<? extends OperationDefinition> operationDefinition;
1405
1406         for (Map.Entry<String, Object> entry : interfaceAsMap.entrySet()) {
1407             operationDefinition =
1408                     createOperation(entry.getKey(), entry.getValue(), fieldNames, operationClass);
1409             operationDefinition.ifPresent(operation -> addOperationToInterface(interfaceDefinition,
1410                     entry.getKey(), operation));
1411         }
1412     }
1413
1414     private static void addOperationToInterface(InterfaceDefinition interfaceDefinition,
1415                                                 String operationName,
1416                                                 OperationDefinition operationDefinition) {
1417         if (interfaceDefinition instanceof InterfaceDefinitionType) {
1418             InterfaceDefinitionType interfaceDefinitionType =
1419                     (InterfaceDefinitionType) interfaceDefinition;
1420             interfaceDefinitionType.addOperation(operationName, (OperationDefinitionType)
1421                     operationDefinition);
1422         }
1423         if (interfaceDefinition instanceof InterfaceDefinitionTemplate) {
1424             InterfaceDefinitionTemplate interfaceDefinitionTemplate =
1425                     (InterfaceDefinitionTemplate) interfaceDefinition;
1426             interfaceDefinitionTemplate.addOperation(operationName, (OperationDefinitionTemplate)
1427                     operationDefinition);
1428         }
1429     }
1430
1431     public static void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType,
1432                                                            List<Map<String, RequirementDefinition>>
1433                                                                    requirementsList,
1434                                                            String templateName) {
1435         if (CollectionUtils.isEmpty(requirementsList)) {
1436             return;
1437         }
1438         if (substitutionNodeType.getRequirements() == null) {
1439             substitutionNodeType.setRequirements(new ArrayList<>());
1440         }
1441
1442         for (Map<String, RequirementDefinition> requirementDef : requirementsList) {
1443             for (Map.Entry<String, RequirementDefinition> entry : requirementDef.entrySet()) {
1444                 Map<String, RequirementDefinition> requirementMap = new HashMap<>();
1445                 requirementMap.put(entry.getKey() + "_" + templateName, entry.getValue().clone());
1446                 substitutionNodeType.getRequirements().add(requirementMap);
1447             }
1448         }
1449     }
1450
1451     public static boolean isNodeTemplateSectionMissingFromServiceTemplate(
1452             ServiceTemplate serviceTemplate) {
1453         return Objects.isNull(serviceTemplate.getTopology_template())
1454                 || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates());
1455     }
1456 }