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