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