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