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