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