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