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