Merge "Port mirroring"
[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.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.context.impl.MdcDataDebugMessage;
31 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
32 import org.openecomp.sdc.logging.types.LoggerConstants;
33 import org.openecomp.sdc.logging.types.LoggerErrorCode;
34 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
35 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
36 import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType;
37 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
38 import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType;
39 import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition;
40 import org.openecomp.sdc.tosca.datatypes.model.CapabilityAssignment;
41 import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition;
42 import org.openecomp.sdc.tosca.datatypes.model.CapabilityType;
43 import org.openecomp.sdc.tosca.datatypes.model.Constraint;
44 import org.openecomp.sdc.tosca.datatypes.model.EntrySchema;
45 import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition;
46 import org.openecomp.sdc.tosca.datatypes.model.Import;
47 import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate;
48 import org.openecomp.sdc.tosca.datatypes.model.NodeType;
49 import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition;
50 import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition;
51 import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition;
52 import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate;
53 import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment;
54 import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition;
55 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
56 import org.openecomp.sdc.tosca.datatypes.model.Status;
57 import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping;
58 import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate;
59 import org.openecomp.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt;
60 import org.openecomp.sdc.tosca.errors.InvalidAddActionNullEntityErrorBuilder;
61 import org.openecomp.sdc.tosca.errors.InvalidRequirementAssignmentErrorBuilder;
62 import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
63
64 import java.io.ByteArrayInputStream;
65 import java.io.ByteArrayOutputStream;
66 import java.io.IOException;
67 import java.io.NotSerializableException;
68 import java.io.ObjectInputStream;
69 import java.io.ObjectOutputStream;
70 import java.util.ArrayList;
71 import java.util.Arrays;
72 import java.util.Collections;
73 import java.util.HashMap;
74 import java.util.List;
75 import java.util.ListIterator;
76 import java.util.Map;
77 import java.util.Objects;
78 import java.util.Optional;
79
80 /**
81  * The type Data model util.
82  */
83 public class DataModelUtil {
84
85   /**
86    * Add substitution mapping.
87    */
88
89   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
90   private static final Logger logger = LoggerFactory.getLogger(DataModelUtil.class);
91
92   /**
93    * Add substitution mapping.
94    *
95    * @param serviceTemplate     the service template
96    * @param substitutionMapping the substitution mapping
97    */
98   public static void addSubstitutionMapping(ServiceTemplate serviceTemplate,
99                                             SubstitutionMapping substitutionMapping) {
100     mdcDataDebugMessage.debugEntryMessage(null, null);
101
102     if (serviceTemplate == null) {
103       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
104           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
105           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
106       throw new CoreException(
107           new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", "Service Template")
108               .build());
109     }
110
111     if (serviceTemplate.getTopology_template() == null) {
112       serviceTemplate.setTopology_template(new TopologyTemplate());
113     }
114     serviceTemplate.getTopology_template().setSubstitution_mappings(substitutionMapping);
115
116     mdcDataDebugMessage.debugExitMessage(null, null);
117   }
118
119   /**
120    * Add substitution mapping req.
121    *
122    * @param serviceTemplate                    the service template
123    * @param substitutionMappingRequirementId   the substitution mapping requirement id
124    * @param substitutionMappingRequirementList the substitution mapping requirement list
125    */
126   public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate,
127                                                String substitutionMappingRequirementId,
128                                                List<String> substitutionMappingRequirementList) {
129
130
131     mdcDataDebugMessage.debugEntryMessage(null, null);
132
133     if (serviceTemplate == null) {
134       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
135           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
136           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
137       throw new CoreException(
138           new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements",
139               "Service Template").build());
140     }
141
142     if (serviceTemplate.getTopology_template() == null) {
143       serviceTemplate.setTopology_template(new TopologyTemplate());
144     }
145     if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
146       serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
147     }
148     if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
149         == null) {
150       serviceTemplate.getTopology_template().getSubstitution_mappings()
151           .setRequirements(new HashMap<>());
152     }
153
154     serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
155         .put(substitutionMappingRequirementId, substitutionMappingRequirementList);
156
157     mdcDataDebugMessage.debugExitMessage(null, null);
158   }
159
160   /**
161    * Add substitution mapping capability.
162    *
163    * @param serviceTemplate                   the service template
164    * @param substitutionMappingCapabilityId   the substitution mapping capability id
165    * @param substitutionMappingCapabilityList the substitution mapping capability list
166    */
167   public static void addSubstitutionMappingCapability(ServiceTemplate serviceTemplate,
168                                                       String substitutionMappingCapabilityId,
169                                                       List<String> substitutionMappingCapabilityList) {
170
171
172     mdcDataDebugMessage.debugEntryMessage(null, null);
173
174     if (serviceTemplate == null) {
175       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
176           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
177           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
178       throw new CoreException(
179           new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Capabilities",
180               "Service Template").build());
181     }
182
183     if (serviceTemplate.getTopology_template() == null) {
184       serviceTemplate.setTopology_template(new TopologyTemplate());
185     }
186     if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
187       serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
188     }
189     if (serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities()
190         == null) {
191       serviceTemplate.getTopology_template().getSubstitution_mappings()
192           .setCapabilities(new HashMap<>());
193     }
194
195     serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities()
196         .putIfAbsent(substitutionMappingCapabilityId, substitutionMappingCapabilityList);
197
198     mdcDataDebugMessage.debugExitMessage(null, null);
199   }
200
201   /**
202    * Add node template.
203    *
204    * @param serviceTemplate the service template
205    * @param nodeTemplateId  the node template id
206    * @param nodeTemplate    the node template
207    */
208   public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId,
209                                      NodeTemplate nodeTemplate) {
210
211
212     mdcDataDebugMessage.debugEntryMessage(null, null);
213
214     if (serviceTemplate == null) {
215       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
216           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
217           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
218       throw new CoreException(
219           new InvalidAddActionNullEntityErrorBuilder("Node Template", "Service Template").build());
220     }
221     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
222     if (Objects.isNull(topologyTemplate)) {
223       topologyTemplate = new TopologyTemplate();
224       serviceTemplate.setTopology_template(topologyTemplate);
225     }
226     if (topologyTemplate.getNode_templates() == null) {
227       topologyTemplate.setNode_templates(new HashMap<>());
228     }
229     topologyTemplate.getNode_templates().put(nodeTemplateId, nodeTemplate);
230
231     mdcDataDebugMessage.debugExitMessage(null, null);
232
233   }
234
235   /**
236    * Add capability def.
237    *
238    * @param nodeType             the node type
239    * @param capabilityId         the capability id
240    * @param capabilityDefinition the capability definition
241    */
242   public static void addCapabilityDef(NodeType nodeType, String capabilityId,
243                                       CapabilityDefinition capabilityDefinition) {
244
245
246     mdcDataDebugMessage.debugEntryMessage(null, null);
247
248     if (nodeType == null) {
249       throw new CoreException(
250           new InvalidAddActionNullEntityErrorBuilder("Capability Definition", "Node Type").build());
251     }
252     if (Objects.isNull(nodeType.getCapabilities())) {
253       nodeType.setCapabilities(new HashMap<>());
254     }
255     nodeType.getCapabilities().put(capabilityId, capabilityDefinition);
256
257     mdcDataDebugMessage.debugExitMessage(null, null);
258   }
259
260   /**
261    * Add capabilities def to node type.
262    *
263    * @param nodeType     the node type
264    * @param capabilities the capability definitions
265    */
266   public static void addNodeTypeCapabilitiesDef(NodeType nodeType,
267                                                 Map<String, CapabilityDefinition> capabilities) {
268     mdcDataDebugMessage.debugEntryMessage(null, null);
269
270     if (capabilities == null || capabilities.entrySet().size() == 0) {
271       return;
272     }
273
274     if (nodeType == null) {
275       throw new CoreException(
276           new InvalidAddActionNullEntityErrorBuilder("Capability Definition", "Node Type").build());
277     }
278
279     if (MapUtils.isEmpty(nodeType.getCapabilities())) {
280       nodeType.setCapabilities(new HashMap<>());
281     }
282     if (capabilities.size() > 0) {
283       nodeType.setCapabilities(new HashMap<>());
284     }
285     for (Map.Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
286       nodeType.getCapabilities().put(entry.getKey(), entry.getValue());
287     }
288
289     mdcDataDebugMessage.debugExitMessage(null, null);
290   }
291
292   /**
293    * Add policy definition.
294    *
295    * @param serviceTemplate  the service template
296    * @param policyId         the policy id
297    * @param policyDefinition the policy definition
298    */
299   public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId,
300                                          PolicyDefinition policyDefinition) {
301
302
303     mdcDataDebugMessage.debugEntryMessage(null, null);
304
305     if (serviceTemplate == null) {
306       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
307           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
308           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
309       throw new CoreException(
310           new InvalidAddActionNullEntityErrorBuilder("Policy Definition", "Service Template")
311               .build());
312     }
313     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
314     if (Objects.isNull(topologyTemplate)) {
315       topologyTemplate = new TopologyTemplate();
316       serviceTemplate.setTopology_template(topologyTemplate);
317     }
318     if (topologyTemplate.getPolicies() == null) {
319       topologyTemplate.setPolicies(new HashMap<>());
320     }
321     topologyTemplate.getPolicies().put(policyId, policyDefinition);
322
323     mdcDataDebugMessage.debugExitMessage(null, null);
324   }
325
326   /**
327    * Add node type.
328    *
329    * @param serviceTemplate the service template
330    * @param nodeTypeId      the node type id
331    * @param nodeType        the node type
332    */
333   public static void addNodeType(ServiceTemplate serviceTemplate, String nodeTypeId,
334                                  NodeType nodeType) {
335
336
337     mdcDataDebugMessage.debugEntryMessage(null, null);
338
339     if (serviceTemplate == null) {
340       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
341           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
342           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
343       throw new CoreException(
344           new InvalidAddActionNullEntityErrorBuilder("Node Type", "Service Template").build());
345     }
346     if (serviceTemplate.getNode_types() == null) {
347       serviceTemplate.setNode_types(new HashMap<>());
348     }
349     serviceTemplate.getNode_types().put(nodeTypeId, nodeType);
350
351     mdcDataDebugMessage.debugExitMessage(null, null);
352   }
353
354   /**
355    * Add relationship template.
356    *
357    * @param serviceTemplate        the service template
358    * @param relationshipTemplateId the relationship template id
359    * @param relationshipTemplate   the relationship template
360    */
361   public static void addRelationshipTemplate(ServiceTemplate serviceTemplate,
362                                              String relationshipTemplateId,
363                                              RelationshipTemplate relationshipTemplate) {
364
365
366     mdcDataDebugMessage.debugEntryMessage(null, null);
367
368     if (serviceTemplate == null) {
369       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
370           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
371           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
372       throw new CoreException(
373           new InvalidAddActionNullEntityErrorBuilder("Relationship Template", "Service Template")
374               .build());
375     }
376     if (serviceTemplate.getTopology_template() == null) {
377       serviceTemplate.setTopology_template(new TopologyTemplate());
378     }
379     if (serviceTemplate.getTopology_template().getRelationship_templates() == null) {
380       serviceTemplate.getTopology_template().setRelationship_templates(new HashMap<>());
381     }
382     serviceTemplate.getTopology_template().getRelationship_templates()
383         .put(relationshipTemplateId, relationshipTemplate);
384
385     mdcDataDebugMessage.debugExitMessage(null, null);
386   }
387
388   /**
389    * Add requirement assignment.
390    *
391    * @param nodeTemplate          the node template
392    * @param requirementId         the requirement id
393    * @param requirementAssignment the requirement assignment
394    */
395   public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId,
396                                               RequirementAssignment requirementAssignment) {
397
398
399     mdcDataDebugMessage.debugEntryMessage(null, null);
400
401     if (nodeTemplate == null) {
402       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
403           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
404           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
405       throw new CoreException(
406           new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", "Node Template")
407               .build());
408     }
409     if (requirementAssignment.getNode() == null) {
410       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
411           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
412           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
413       throw new CoreException(new InvalidRequirementAssignmentErrorBuilder(requirementId).build());
414     }
415
416     if (nodeTemplate.getRequirements() == null) {
417       nodeTemplate.setRequirements(new ArrayList<>());
418     }
419     Map<String, RequirementAssignment> requirement = new HashMap<>();
420     requirement.put(requirementId, requirementAssignment);
421     nodeTemplate.getRequirements().add(requirement);
422
423     mdcDataDebugMessage.debugExitMessage(null, null);
424   }
425
426   /**
427    * Gets node template.
428    *
429    * @param serviceTemplate the service template
430    * @param nodeTemplateId  the node template id
431    * @return the node template
432    */
433   public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate,
434                                              String nodeTemplateId) {
435
436     mdcDataDebugMessage.debugEntryMessage(null, null);
437
438     if (serviceTemplate == null
439         || serviceTemplate.getTopology_template() == null
440         || serviceTemplate.getTopology_template().getNode_templates() == null) {
441       return null;
442     }
443
444     mdcDataDebugMessage.debugExitMessage(null, null);
445     return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId);
446   }
447
448   /**
449    * Gets node type.
450    *
451    * @param serviceTemplate the service template
452    * @param nodeTypeId      the node type id
453    * @return the node type
454    */
455   public static NodeType getNodeType(ServiceTemplate serviceTemplate, String nodeTypeId) {
456
457
458     mdcDataDebugMessage.debugEntryMessage(null, null);
459     if (serviceTemplate == null || serviceTemplate.getNode_types() == null) {
460       return null;
461     }
462
463     mdcDataDebugMessage.debugExitMessage(null, null);
464     return serviceTemplate.getNode_types().get(nodeTypeId);
465   }
466
467   /**
468    * Gets requirement definition.
469    *
470    * @param nodeType                the node type
471    * @param requirementDefinitionId the requirement definition id
472    * @return the requirement definition
473    */
474   public static Optional<RequirementDefinition> getRequirementDefinition(
475       NodeType nodeType,
476       String requirementDefinitionId) {
477
478
479     mdcDataDebugMessage.debugEntryMessage(null, null);
480
481     if (nodeType == null || nodeType.getRequirements() == null || requirementDefinitionId == null) {
482       return Optional.empty();
483     }
484     for (Map<String, RequirementDefinition> reqMap : nodeType.getRequirements()) {
485       if (reqMap.containsKey(requirementDefinitionId)) {
486         return Optional.of(reqMap.get(requirementDefinitionId));
487       }
488     }
489
490     mdcDataDebugMessage.debugExitMessage(null, null);
491     return Optional.empty();
492   }
493
494   /**
495    * get requirement defenition from requirement defenition list by req key.
496    *
497    * @param requirementsDefinitionList requirement defenition list
498    * @param requirementKey             requirement key
499    */
500   public static Optional<RequirementDefinition> getRequirementDefinition(
501       List<Map<String, RequirementDefinition>> requirementsDefinitionList,
502       String requirementKey) {
503     mdcDataDebugMessage.debugEntryMessage(null, null);
504     if (CollectionUtils.isEmpty(requirementsDefinitionList)) {
505       return Optional.empty();
506     }
507
508     for (Map<String, RequirementDefinition> requirementMap : requirementsDefinitionList) {
509       if (requirementMap.containsKey(requirementKey)) {
510         mdcDataDebugMessage.debugExitMessage(null, null);
511         return Optional.of(requirementMap.get(requirementKey));
512       }
513     }
514
515     mdcDataDebugMessage.debugExitMessage(null, null);
516     return Optional.empty();
517   }
518
519   /**
520    * Gets capability definition.
521    *
522    * @param nodeType               the node type
523    * @param capabilityDefinitionId the capability definition id
524    * @return the capability definition
525    */
526   public static Optional<CapabilityDefinition> getCapabilityDefinition(
527       NodeType nodeType,
528       String capabilityDefinitionId) {
529
530
531     mdcDataDebugMessage.debugEntryMessage(null, null);
532
533     if (nodeType == null || nodeType.getCapabilities() == null || capabilityDefinitionId == null) {
534       return Optional.empty();
535     }
536
537     mdcDataDebugMessage.debugExitMessage(null, null);
538     return Optional.ofNullable(nodeType.getCapabilities().get(capabilityDefinitionId));
539   }
540
541   /**
542    * Add group definition to topology template.
543    *
544    * @param serviceTemplate the service template
545    * @param groupName       the group name
546    * @param group           the group
547    */
548   public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate,
549                                                           String groupName, GroupDefinition group) {
550
551
552     mdcDataDebugMessage.debugEntryMessage(null, null);
553
554     if (serviceTemplate == null) {
555       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
556           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
557           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
558       throw new CoreException(
559           new InvalidAddActionNullEntityErrorBuilder("Group Definition", "Service Template")
560               .build());
561     }
562
563     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
564     if (Objects.isNull(topologyTemplate)) {
565       topologyTemplate = new TopologyTemplate();
566       serviceTemplate.setTopology_template(topologyTemplate);
567     }
568     if (topologyTemplate.getGroups() == null) {
569       topologyTemplate.setGroups(new HashMap<>());
570     }
571     if (serviceTemplate.getTopology_template().getGroups() == null) {
572       Map<String, GroupDefinition> groups = new HashMap<>();
573       serviceTemplate.getTopology_template().setGroups(groups);
574     }
575
576     serviceTemplate.getTopology_template().getGroups().put(groupName, group);
577     mdcDataDebugMessage.debugExitMessage(null, null);
578   }
579
580   /**
581    * Create property definition property definition.
582    *
583    * @param type        the type
584    * @param description the description
585    * @param required    the required
586    * @param constraints the constraints
587    * @param status      the status
588    * @param entrySchema the entry schema
589    * @param defaultVal  the default val
590    * @return the property definition
591    */
592   public static PropertyDefinition createPropertyDefinition(String type, String description,
593                                                             boolean required,
594                                                             List<Constraint> constraints,
595                                                             Status status,
596                                                             EntrySchema entrySchema,
597                                                             Object defaultVal) {
598
599
600     mdcDataDebugMessage.debugEntryMessage(null, null);
601
602     PropertyDefinition propDef = new PropertyDefinition();
603     propDef.setType(type);
604     propDef.setDescription(description);
605     propDef.setRequired(required);
606     propDef.setConstraints(constraints);
607     if (status != null) {
608       propDef.setStatus(status);
609     }
610     propDef.setEntry_schema(entrySchema);
611     propDef.set_default(defaultVal);
612
613     mdcDataDebugMessage.debugExitMessage(null, null);
614     return propDef;
615   }
616
617   /**
618    * Create parameter definition property definition.
619    *
620    * @param type        the type
621    * @param description the description
622    * @param value       the value
623    * @param required    the required
624    * @param constraints the constraints
625    * @param status      the status
626    * @param entrySchema the entry schema
627    * @param defaultVal  the default val
628    * @return the property definition
629    */
630   public static ParameterDefinition createParameterDefinition(String type, String description,
631                                                               Object value, boolean required,
632                                                               List<Constraint> constraints,
633                                                               Status status,
634                                                               EntrySchema entrySchema,
635                                                               Object defaultVal) {
636
637
638     mdcDataDebugMessage.debugEntryMessage(null, null);
639
640     ParameterDefinition paramDef = new ParameterDefinition();
641     paramDef.setType(type);
642     paramDef.setDescription(description);
643     paramDef.setValue(value);
644     paramDef.setRequired(required);
645     paramDef.setConstraints(constraints);
646     if (status != null) {
647       paramDef.setStatus(status);
648     }
649     paramDef.setEntry_schema(entrySchema == null ? null : entrySchema.clone());
650     paramDef.set_default(defaultVal);
651
652     mdcDataDebugMessage.debugExitMessage(null, null);
653     return paramDef;
654   }
655
656   /**
657    * Create requirement requirement definition.
658    *
659    * @param capability   the capability
660    * @param node         the node
661    * @param relationship the relationship
662    * @param occurrences  the occurrences
663    * @return the requirement definition
664    */
665   public static RequirementDefinition createRequirement(String capability, String node,
666                                                         String relationship, Object[] occurrences) {
667
668
669     mdcDataDebugMessage.debugEntryMessage(null, null);
670
671     RequirementDefinition requirementDefinition = new RequirementDefinition();
672     requirementDefinition.setCapability(capability);
673     requirementDefinition.setNode(node);
674     requirementDefinition.setRelationship(relationship);
675     if (occurrences != null) {
676       requirementDefinition.setOccurrences(occurrences);
677     }
678
679     mdcDataDebugMessage.debugExitMessage(null, null);
680     return requirementDefinition;
681   }
682
683   /**
684    * Create attribute definition attribute definition.
685    *
686    * @param type        the type
687    * @param description the description
688    * @param status      the status
689    * @param entrySchema the entry schema
690    * @param defaultVal  the default val
691    * @return the attribute definition
692    */
693   public static AttributeDefinition createAttributeDefinition(String type, String description,
694                                                               Status status,
695                                                               EntrySchema entrySchema,
696                                                               Object defaultVal) {
697
698
699     mdcDataDebugMessage.debugEntryMessage(null, null);
700
701     AttributeDefinition attributeDef = new AttributeDefinition();
702     attributeDef.setType(type);
703
704     if (description != null) {
705       attributeDef.setDescription(description);
706     }
707     if (status != null) {
708       attributeDef.setStatus(status);
709     }
710     attributeDef.setEntry_schema(entrySchema);
711     attributeDef.set_default(defaultVal);
712
713     mdcDataDebugMessage.debugExitMessage(null, null);
714     return attributeDef;
715   }
716
717   /**
718    * Create valid values constraint constraint.
719    *
720    * @param values the values
721    * @return the constraint
722    */
723   public static Constraint createValidValuesConstraint(Object... values) {
724
725
726     mdcDataDebugMessage.debugEntryMessage(null, null);
727
728     Constraint validValues = new Constraint();
729     for (Object value : values) {
730       validValues.addValidValue(value);
731     }
732
733     mdcDataDebugMessage.debugExitMessage(null, null);
734     return validValues;
735   }
736
737   /**
738    * Create metadata metadata.
739    *
740    * @param templateName    the template name
741    * @param templateVersion the template version
742    * @param templateAuthor  the template author
743    * @return the metadata
744    */
745   public static Map<String, String> createMetadata(String templateName, String templateVersion,
746                                                    String templateAuthor) {
747
748
749     mdcDataDebugMessage.debugEntryMessage(null, null);
750     Map<String, String> metadata = new HashMap<>();
751     metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
752     metadata.put("template_version", templateVersion);
753     metadata.put("template_author", templateAuthor);
754
755     mdcDataDebugMessage.debugExitMessage(null, null);
756     return metadata;
757   }
758
759   /**
760    * Create entry schema entry schema.
761    *
762    * @param type        the type
763    * @param description the description
764    * @param constraints the constraints
765    * @return the entry schema
766    */
767   public static EntrySchema createEntrySchema(String type, String description,
768                                               List<Constraint> constraints) {
769
770
771     mdcDataDebugMessage.debugEntryMessage(null, null);
772
773     if(Objects.isNull(type) && Objects.isNull(description) && CollectionUtils.isEmpty(constraints)){
774       return null;
775     }
776
777     EntrySchema entrySchema = new EntrySchema();
778     entrySchema.setType(type);
779     entrySchema.setDescription(description);
780     entrySchema.setConstraints(constraints);
781
782     mdcDataDebugMessage.debugExitMessage(null, null);
783     return entrySchema;
784   }
785
786   /**
787    * Create valid values constraints list list.
788    *
789    * @param values the values
790    * @return the list
791    */
792   public static List<Constraint> createValidValuesConstraintsList(String... values) {
793
794
795     mdcDataDebugMessage.debugEntryMessage(null, null);
796
797     List<Constraint> constraints;
798     Constraint validValues;
799     constraints = new ArrayList<>();
800     validValues = DataModelUtil.createValidValuesConstraint(values);
801     constraints.add(validValues);
802
803     mdcDataDebugMessage.debugExitMessage(null, null);
804     return constraints;
805   }
806
807   /**
808    * Create greater or equal constrain constraint.
809    *
810    * @param value the value
811    * @return the constraint
812    */
813   public static Constraint createGreaterOrEqualConstrain(Object value) {
814     mdcDataDebugMessage.debugEntryMessage(null, null);
815
816     Constraint constraint = new Constraint();
817     constraint.setGreater_or_equal(value);
818
819     mdcDataDebugMessage.debugExitMessage(null, null);
820     return constraint;
821   }
822
823   /**
824    * Gets constrain list.
825    *
826    * @param constrains the constrains
827    * @return the constrain list
828    */
829   public static List<Constraint> getConstrainList(Constraint... constrains) {
830     return Arrays.asList(constrains);
831
832   }
833
834   /**
835    * Create get input property value from list parameter map.
836    *
837    * @param inputPropertyListName the input property list name
838    * @param indexInTheList        the index in the list
839    * @param nestedPropertyName    the nested property name
840    * @return the map
841    */
842   public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName,
843                                                                  int indexInTheList,
844                                                                  String... nestedPropertyName) {
845
846
847     mdcDataDebugMessage.debugEntryMessage(null, null);
848
849     List propertyList = new ArrayList<>();
850     propertyList.add(inputPropertyListName);
851     propertyList.add(indexInTheList);
852     if (nestedPropertyName != null) {
853       Collections.addAll(propertyList, nestedPropertyName);
854     }
855     Map getInputProperty = new HashMap<>();
856     getInputProperty.put(ToscaFunctions.GET_INPUT.getDisplayName(), propertyList);
857
858     mdcDataDebugMessage.debugExitMessage(null, null);
859     return getInputProperty;
860   }
861
862   /**
863    * Convert property def to parameter def parameter definition ext.
864    *
865    * @param propertyDefinition the property definition
866    * @return the parameter definition ext
867    */
868   public static ParameterDefinitionExt convertPropertyDefToParameterDef(
869       PropertyDefinition propertyDefinition) {
870
871
872     mdcDataDebugMessage.debugEntryMessage(null, null);
873
874     if (propertyDefinition == null) {
875       return null;
876     }
877
878     ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt();
879     parameterDefinition.setType(propertyDefinition.getType());
880     parameterDefinition.setDescription(propertyDefinition.getDescription());
881     parameterDefinition.setRequired(propertyDefinition.getRequired());
882     parameterDefinition.set_default(propertyDefinition.get_default());
883     parameterDefinition.setStatus(propertyDefinition.getStatus());
884     parameterDefinition.setConstraints(propertyDefinition.getConstraints());
885     parameterDefinition.setEntry_schema(Objects.isNull(propertyDefinition.getEntry_schema()) ? null
886         : propertyDefinition.getEntry_schema().clone());
887     parameterDefinition.setHidden(false);
888     parameterDefinition.setImmutable(false);
889
890     mdcDataDebugMessage.debugExitMessage(null, null);
891     return parameterDefinition;
892   }
893
894   /**
895    * Convert attribute def to parameter def parameter definition ext.
896    *
897    * @param attributeDefinition the attribute definition
898    * @param outputValue         the output value
899    * @return the parameter definition ext
900    */
901   public static ParameterDefinitionExt convertAttributeDefToParameterDef(
902       AttributeDefinition attributeDefinition, Map<String, List> outputValue) {
903
904
905     mdcDataDebugMessage.debugEntryMessage(null, null);
906
907     if (attributeDefinition == null) {
908       return null;
909     }
910     ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt();
911     parameterDefinition.setDescription(attributeDefinition.getDescription());
912     parameterDefinition.setValue(outputValue);
913
914     mdcDataDebugMessage.debugExitMessage(null, null);
915     return parameterDefinition;
916   }
917
918   /**
919    * Convert capability type to capability definition capability definition.
920    *
921    * @param capabilityTypeId the capability type id
922    * @param capabilityType   the capability type
923    * @param properties       the properties
924    * @return the capability definition
925    */
926   public static CapabilityDefinition convertCapabilityTypeToCapabilityDefinition(
927       String capabilityTypeId, CapabilityType capabilityType, Map<String, Object> properties) {
928
929
930     mdcDataDebugMessage.debugEntryMessage(null, null);
931
932     CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
933     capabilityDefinition.setAttributes(cloneAttributeDefinitionMap(capabilityType.getAttributes()));
934     capabilityDefinition.setProperties(clonePropertyDefinitionMap(capabilityType.getProperties()));
935     capabilityDefinition.setDescription(capabilityType.getDescription());
936     capabilityDefinition.setType(capabilityTypeId);
937
938     capabilityDefinition.getProperties()
939         .entrySet()
940         .stream()
941         .filter(entry -> properties.containsKey(entry.getKey()))
942         .forEach(entry -> entry.getValue()
943             .set_default(properties.get(entry.getKey())));
944
945     mdcDataDebugMessage.debugExitMessage(null, null);
946     return capabilityDefinition;
947   }
948
949   /**
950    * Clone property definition map map.
951    *
952    * @param propertyDefinitionMap the property definition map
953    * @return the map
954    */
955   public static Map clonePropertyDefinitionMap(
956       Map<String, PropertyDefinition> propertyDefinitionMap) {
957
958
959     mdcDataDebugMessage.debugEntryMessage(null, null);
960
961     Map outMap = new HashMap<>();
962     for (String propertyDefKey : propertyDefinitionMap.keySet()) {
963       PropertyDefinition propertyDefValue = propertyDefinitionMap.get(propertyDefKey);
964       outMap.put(new String(propertyDefKey), propertyDefValue.clone());
965     }
966
967     mdcDataDebugMessage.debugExitMessage(null, null);
968     return outMap;
969   }
970
971   /**
972    * Clone attribute definition map map.
973    *
974    * @param attributeDefinitionMap the attribute definition map
975    * @return the map
976    */
977   public static Map cloneAttributeDefinitionMap(
978       Map<String, AttributeDefinition> attributeDefinitionMap) {
979
980
981     mdcDataDebugMessage.debugEntryMessage(null, null);
982
983     Map outMap = new HashMap<>();
984     for (String attributeDefKey : attributeDefinitionMap.keySet()) {
985       AttributeDefinition attributeDefinition = attributeDefinitionMap.get(attributeDefKey);
986       outMap.put(new String(attributeDefKey), attributeDefinition.clone());
987     }
988
989     mdcDataDebugMessage.debugExitMessage(null, null);
990     return outMap;
991   }
992
993   public static boolean isNodeTemplate(String entryId, ServiceTemplate serviceTemplate) {
994     return serviceTemplate.getTopology_template().getNode_templates() != null
995         && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null;
996   }
997
998   /**
999    * Add Input parameter.
1000    *
1001    * @param serviceTemplate       the service template
1002    * @param parameterDefinitionId the parameter definition id
1003    * @param parameterDefinition   the parameter definition
1004    */
1005   public static void addInputParameterToTopologyTemplate(ServiceTemplate serviceTemplate,
1006                                                          String parameterDefinitionId,
1007                                                          ParameterDefinition parameterDefinition) {
1008
1009
1010     mdcDataDebugMessage.debugEntryMessage(null, null);
1011
1012     if (Objects.isNull(serviceTemplate)) {
1013       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
1014           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
1015           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
1016       throw new CoreException(
1017           new InvalidAddActionNullEntityErrorBuilder("Topology Template Input Parameter",
1018               "Service Template").build());
1019     }
1020     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
1021     if (Objects.isNull(topologyTemplate)) {
1022       topologyTemplate = new TopologyTemplate();
1023       serviceTemplate.setTopology_template(topologyTemplate);
1024     }
1025     if (topologyTemplate.getInputs() == null) {
1026       topologyTemplate.setInputs(new HashMap<>());
1027     }
1028     topologyTemplate.getInputs().put(parameterDefinitionId, parameterDefinition);
1029
1030     mdcDataDebugMessage.debugExitMessage(null, null);
1031
1032   }
1033
1034   /**
1035    * Add Output parameter.
1036    *
1037    * @param serviceTemplate       the service template
1038    * @param parameterDefinitionId the parameter definition id
1039    * @param parameterDefinition   the parameter definition
1040    */
1041   public static void addOutputParameterToTopologyTemplate(ServiceTemplate serviceTemplate,
1042                                                           String parameterDefinitionId,
1043                                                           ParameterDefinition parameterDefinition) {
1044
1045
1046     mdcDataDebugMessage.debugEntryMessage(null, null);
1047
1048     if (Objects.isNull(serviceTemplate)) {
1049       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
1050           LoggerTragetServiceName.ADD_ENTITIES_TO_TOSCA, ErrorLevel.ERROR.name(),
1051           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ADD_ACTION);
1052       throw new CoreException(
1053           new InvalidAddActionNullEntityErrorBuilder("Topology Template Ouput Parameter",
1054               "Service Template").build());
1055     }
1056     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
1057     if (Objects.isNull(topologyTemplate)) {
1058       topologyTemplate = new TopologyTemplate();
1059       serviceTemplate.setTopology_template(topologyTemplate);
1060     }
1061     if (topologyTemplate.getOutputs() == null) {
1062       topologyTemplate.setOutputs(new HashMap<>());
1063     }
1064     topologyTemplate.getOutputs().put(parameterDefinitionId, parameterDefinition);
1065
1066     mdcDataDebugMessage.debugExitMessage(null, null);
1067
1068   }
1069
1070   /**
1071    * Add requirement def to requirement def list.
1072    *
1073    * @param requirementList requirement list
1074    * @param requirementDef  added requirement def
1075    */
1076   public static void addRequirementToList(List<Map<String, RequirementDefinition>> requirementList,
1077                                           Map<String, RequirementDefinition> requirementDef) {
1078     if (requirementDef == null) {
1079       return;
1080     }
1081     if (requirementList == null) {
1082       requirementList = new ArrayList<Map<String, RequirementDefinition>>();
1083     }
1084
1085     for (Map.Entry<String, RequirementDefinition> entry : requirementDef.entrySet()) {
1086       CommonMethods.mergeEntryInList(entry.getKey(), entry.getValue(), requirementList);
1087     }
1088   }
1089
1090   /**
1091    * get node template requirement.
1092    *
1093    * @param nodeTemplate node template
1094    */
1095   public static Map<String, RequirementAssignment> getNodeTemplateRequirements(
1096       NodeTemplate nodeTemplate) {
1097     mdcDataDebugMessage.debugEntryMessage(null, null);
1098
1099     if (Objects.isNull(nodeTemplate)) {
1100       return null;
1101     }
1102     List<Map<String, RequirementAssignment>> templateRequirements = nodeTemplate.getRequirements();
1103
1104     Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
1105     if (CollectionUtils.isEmpty(templateRequirements)) {
1106       return nodeTemplateRequirementsAssignment;
1107     }
1108     YamlUtil yamlUtil = new YamlUtil();
1109     for (Map<String, RequirementAssignment> requirementAssignmentMap : templateRequirements) {
1110       for (Map.Entry<String, RequirementAssignment> requirementEntry : requirementAssignmentMap
1111           .entrySet()) {
1112         RequirementAssignment requirementAssignment = (yamlUtil
1113             .yamlToObject(yamlUtil.objectToYaml(requirementEntry.getValue()),
1114                 RequirementAssignment.class));
1115         nodeTemplateRequirementsAssignment
1116             .put(requirementEntry.getKey(), requirementAssignment);
1117       }
1118     }
1119
1120     mdcDataDebugMessage.debugExitMessage(null, null);
1121     return nodeTemplateRequirementsAssignment;
1122   }
1123
1124   /**
1125    * Gets the list of requirements for the node template.
1126    *
1127    * @param nodeTemplate the node template
1128    * @return the node template requirement list and null if the node has no requirements
1129    */
1130   public static List<Map<String, RequirementAssignment>> getNodeTemplateRequirementList(
1131       NodeTemplate nodeTemplate) {
1132     mdcDataDebugMessage.debugEntryMessage(null, null);
1133     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
1134     //Creating concrete objects
1135     List<Map<String, RequirementAssignment>> requirements = nodeTemplate.getRequirements();
1136     List<Map<String, RequirementAssignment>> concreteRequirementList = null;
1137     if (requirements != null) {
1138       concreteRequirementList = new ArrayList<>();
1139       ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements
1140           .listIterator();
1141       while (reqListIterator.hasNext()) {
1142         Map<String, RequirementAssignment> requirement = reqListIterator.next();
1143         Map<String, RequirementAssignment> concreteRequirement = new HashMap<>();
1144         for (Map.Entry<String, RequirementAssignment> reqEntry : requirement.entrySet()) {
1145           RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil
1146               .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()),
1147                   RequirementAssignment.class));
1148           concreteRequirement.put(reqEntry.getKey(), requirementAssignment);
1149           concreteRequirementList.add(concreteRequirement);
1150           reqListIterator.remove();
1151         }
1152       }
1153       requirements.clear();
1154       requirements.addAll(concreteRequirementList);
1155       nodeTemplate.setRequirements(requirements);
1156     }
1157     mdcDataDebugMessage.debugExitMessage(null, null);
1158     return concreteRequirementList;
1159   }
1160
1161   /**
1162    * get requirement assignment from requirement assignment list by req key.
1163    *
1164    * @param requirementsAssignmentList requirement defenition list
1165    * @param requirementKey             requirement key
1166    */
1167   public static Optional<List<RequirementAssignment>> getRequirementAssignment(
1168       List<Map<String, RequirementAssignment>> requirementsAssignmentList,
1169       String requirementKey) {
1170
1171     mdcDataDebugMessage.debugEntryMessage(null, null);
1172     if (CollectionUtils.isEmpty(requirementsAssignmentList)) {
1173       return Optional.empty();
1174     }
1175
1176     List<RequirementAssignment> matchRequirementAssignmentList = new ArrayList<>();
1177     for (Map<String, RequirementAssignment> requirementMap : requirementsAssignmentList) {
1178       if (requirementMap.containsKey(requirementKey)) {
1179         YamlUtil yamlUtil = new YamlUtil();
1180         RequirementAssignment requirementAssignment = (yamlUtil
1181             .yamlToObject(yamlUtil.objectToYaml(requirementMap.get(requirementKey)),
1182                 RequirementAssignment.class));
1183         matchRequirementAssignmentList.add(requirementAssignment);
1184       }
1185     }
1186
1187     mdcDataDebugMessage.debugExitMessage(null, null);
1188     return Optional.ofNullable(matchRequirementAssignmentList);
1189   }
1190
1191   /**
1192    * remove requirement defenition from requirement defenition list by req key.
1193    *
1194    * @param requirementsDefinitionList requirement defenition list
1195    * @param requirementKey             requirement key
1196    */
1197   public static void removeRequirementsDefinition(
1198       List<Map<String, RequirementDefinition>> requirementsDefinitionList,
1199       String requirementKey) {
1200     mdcDataDebugMessage.debugEntryMessage(null, null);
1201     if (requirementsDefinitionList == null) {
1202       return;
1203     }
1204
1205     List<Map<String, RequirementDefinition>> mapToBeRemoved = new ArrayList<>();
1206     for (Map<String, RequirementDefinition> reqMap : requirementsDefinitionList) {
1207       reqMap.remove(requirementKey);
1208       if (reqMap.isEmpty()) {
1209         mapToBeRemoved.add(reqMap);
1210       }
1211     }
1212     for (Map<String, RequirementDefinition> removeMap : mapToBeRemoved) {
1213       requirementsDefinitionList.remove(removeMap);
1214     }
1215
1216     mdcDataDebugMessage.debugExitMessage(null, null);
1217   }
1218
1219   /**
1220    * remove requirement assignment from requirement defenition list by req key.
1221    *
1222    * @param requirementsAssignmentList requirement Assignment list
1223    * @param requirementKey             requirement key
1224    */
1225   public static void removeRequirementsAssignment(
1226       List<Map<String, RequirementAssignment>> requirementsAssignmentList,
1227       String requirementKey) {
1228     mdcDataDebugMessage.debugEntryMessage(null, null);
1229     if (requirementsAssignmentList == null) {
1230       return;
1231     }
1232
1233     List<Map<String, RequirementAssignment>> mapToBeRemoved = new ArrayList<>();
1234     for (Map<String, RequirementAssignment> reqMap : requirementsAssignmentList) {
1235       reqMap.remove(requirementKey);
1236       if (reqMap.isEmpty()) {
1237         mapToBeRemoved.add(reqMap);
1238       }
1239     }
1240     for (Map<String, RequirementAssignment> removeMap : mapToBeRemoved) {
1241       requirementsAssignmentList.remove(removeMap);
1242     }
1243
1244     mdcDataDebugMessage.debugExitMessage(null, null);
1245   }
1246
1247
1248   /**
1249    * Remove requirement assignment.
1250    *
1251    * @param nodeTemplate                     the node template
1252    * @param requirementKey                   the requirement key
1253    * @param requirementAssignmentToBeDeleted the requirement assignment to be deleted
1254    */
1255   public static void removeRequirementAssignment(
1256       NodeTemplate nodeTemplate,
1257       String requirementKey,
1258       RequirementAssignment requirementAssignmentToBeDeleted) {
1259     mdcDataDebugMessage.debugEntryMessage(null, null);
1260     ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1261     List<Map<String, RequirementAssignment>> nodeTemplateRequirements = nodeTemplate
1262         .getRequirements();
1263     if (nodeTemplateRequirements == null) {
1264       return;
1265     }
1266
1267     Map<String, RequirementAssignment> mapToBeRemoved = new HashMap<>();
1268     ListIterator<Map<String, RequirementAssignment>> iter = nodeTemplateRequirements.listIterator();
1269     while (iter.hasNext()) {
1270       Map<String, RequirementAssignment> reqMap = iter.next();
1271       RequirementAssignment requirementAssignment = reqMap.get(requirementKey);
1272       if (requirementAssignment != null) {
1273         boolean isDesiredRequirementAssignment = toscaAnalyzerService
1274             .isDesiredRequirementAssignment(requirementAssignment,
1275                 requirementAssignmentToBeDeleted.getCapability(),
1276                 requirementAssignmentToBeDeleted.getNode(),
1277                 requirementAssignmentToBeDeleted.getRelationship());
1278         if (isDesiredRequirementAssignment) {
1279           iter.remove();
1280         }
1281       }
1282     }
1283
1284     mdcDataDebugMessage.debugExitMessage(null, null);
1285   }
1286
1287   /**
1288    * Return the suffix of the input namespace
1289    * For an exmpale - for abc.sdf.vsrx, retrun vsrx
1290    *
1291    * @param namespace namespace
1292    * @return String namespace suffix
1293    */
1294   public static String getNamespaceSuffix(String namespace) {
1295     if (namespace == null) {
1296       return null;
1297     }
1298     String delimiterChar = ".";
1299     if (namespace.contains(delimiterChar)) {
1300       return namespace.substring(namespace.lastIndexOf(delimiterChar) + 1);
1301     }
1302     return namespace;
1303   }
1304
1305   /**
1306    * Return true if the input import exist in the input imports list.
1307    *
1308    * @param imports  namespace
1309    * @param importId namespace
1310    * @return true if exist, flase if not exist
1311    */
1312   public static boolean isImportAddedToServiceTemplate(List<Map<String, Import>> imports,
1313                                                        String importId) {
1314     for (Map<String, Import> anImport : imports) {
1315       if (anImport.containsKey(importId)) {
1316         return true;
1317       }
1318     }
1319     return false;
1320   }
1321
1322   /**
1323    * Get output parameter according to the input outputParameterId.
1324    *
1325    * @param serviceTemplate   service template
1326    * @param outputParameterId output parameter id
1327    * @return ParameterDefinition - output parameter
1328    */
1329   public static ParameterDefinition getOuputParameter(ServiceTemplate serviceTemplate,
1330                                                       String outputParameterId) {
1331     mdcDataDebugMessage.debugEntryMessage(null, null);
1332
1333     if (serviceTemplate == null
1334         || serviceTemplate.getTopology_template() == null
1335         || serviceTemplate.getTopology_template().getOutputs() == null) {
1336       return null;
1337     }
1338
1339     mdcDataDebugMessage.debugExitMessage(null, null);
1340     return serviceTemplate.getTopology_template().getOutputs().get(outputParameterId);
1341   }
1342
1343   /**
1344    * Gets input parameters in a service template.
1345    *
1346    * @param serviceTemplate the service template
1347    * @return the input parameters
1348    */
1349   public static Map<String, ParameterDefinition> getInputParameters(ServiceTemplate
1350                                                                         serviceTemplate) {
1351     if (serviceTemplate == null
1352         || serviceTemplate.getTopology_template() == null
1353         || serviceTemplate.getTopology_template().getInputs() == null) {
1354       return null;
1355     }
1356     return serviceTemplate.getTopology_template().getInputs();
1357   }
1358
1359   /**
1360    * Gets relationship templates in a service template.
1361    *
1362    * @param serviceTemplate the service template
1363    * @return the relationship template
1364    */
1365   public static Map<String, RelationshipTemplate> getRelationshipTemplates(ServiceTemplate
1366                                                                                serviceTemplate) {
1367     if (serviceTemplate == null
1368         || serviceTemplate.getTopology_template() == null
1369         || serviceTemplate.getTopology_template().getRelationship_templates() == null) {
1370       return null;
1371     }
1372     return serviceTemplate.getTopology_template().getRelationship_templates();
1373   }
1374
1375   /**
1376    * Get property value according to the input propertyId.
1377    *
1378    * @param nodeTemplate node template
1379    * @param propertyId   property id
1380    * @return Object        property Value
1381    */
1382   public static Object getPropertyValue(NodeTemplate nodeTemplate,
1383                                         String propertyId) {
1384     mdcDataDebugMessage.debugEntryMessage(null, null);
1385
1386     if (nodeTemplate == null
1387         || nodeTemplate.getProperties() == null) {
1388       return null;
1389     }
1390
1391     mdcDataDebugMessage.debugExitMessage(null, null);
1392     return nodeTemplate.getProperties().get(propertyId);
1393   }
1394
1395   /**
1396    * Get node template properties according to the input node template id.
1397    *
1398    * @param serviceTemplate       service template
1399    * @param nodeTemplateId        node template id
1400    * @return node template properties
1401    */
1402   public static Map<String, Object> getNodeTemplateProperties(ServiceTemplate serviceTemplate,
1403                                                               String nodeTemplateId) {
1404     mdcDataDebugMessage.debugEntryMessage(null, null);
1405
1406     if (serviceTemplate == null
1407         || serviceTemplate.getTopology_template() == null
1408         || serviceTemplate.getTopology_template().getNode_templates() == null
1409         || serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) == null) {
1410       return null;
1411     }
1412
1413     mdcDataDebugMessage.debugExitMessage(null, null);
1414     return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId)
1415         .getProperties();
1416   }
1417
1418   /**
1419    * Gets substitution mappings in a service template.
1420    *
1421    * @param serviceTemplate the service template
1422    * @return the substitution mappings
1423    */
1424   public static SubstitutionMapping getSubstitutionMappings(ServiceTemplate serviceTemplate) {
1425     mdcDataDebugMessage.debugEntryMessage(null, null);
1426
1427     if (serviceTemplate == null
1428         || serviceTemplate.getTopology_template() == null
1429         || serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
1430       return null;
1431     }
1432
1433     mdcDataDebugMessage.debugExitMessage(null, null);
1434     return serviceTemplate.getTopology_template().getSubstitution_mappings();
1435   }
1436
1437
1438   /**
1439    * Compare two requirement assignment objects for equality.
1440    *
1441    * @param first  the first requirement assignement object
1442    * @param second the second  requirement assignement object
1443    * @return true if objects are equal and false otherwise
1444    */
1445   public static boolean compareRequirementAssignment(RequirementAssignment first,
1446                                                      RequirementAssignment second) {
1447     if (first.getCapability().equals(second.getCapability())
1448         && first.getNode().equals(second.getNode())
1449         && first.getRelationship().equals(second.getRelationship())) {
1450       return true;
1451     }
1452     return false;
1453   }
1454
1455   /**
1456    * Gets a deep copy clone of the input object.
1457    *
1458    * @param <T>         the type parameter
1459    * @param objectValue the object value
1460    * @param clazz       the clazz
1461    * @return the cloned object
1462    */
1463   public static <T> Object getClonedObject(Object objectValue, Class<T> clazz) {
1464     YamlUtil yamlUtil = new ToscaExtensionYamlUtil();
1465     Object clonedObjectValue;
1466     String objectToYaml = yamlUtil.objectToYaml(objectValue);
1467     clonedObjectValue = yamlUtil.yamlToObject(objectToYaml, clazz);
1468     return clonedObjectValue;
1469   }
1470
1471   /**
1472    * Gets a deep copy clone of the input object.
1473    *
1474    * @param obj the object to be cloned
1475    * @return the cloned object
1476    */
1477   public static Object getClonedObject(Object obj) {
1478     Object clonedObjectValue;
1479     try {
1480       //Serialize object
1481       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1482       ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
1483       objectOutputStream.writeObject(obj);
1484       //Deserialize object
1485       ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream
1486           .toByteArray());
1487       ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
1488       clonedObjectValue = objectInputStream.readObject();
1489     } catch (NotSerializableException ex) {
1490       logger.debug(ex.getMessage(), ex);
1491       return getClonedObject(obj, obj.getClass());
1492     } catch (IOException | ClassNotFoundException ex) {
1493       logger.debug(ex.getMessage(), ex);
1494       return null;
1495     }
1496     return clonedObjectValue;
1497   }
1498
1499   /**
1500    * Add substitution filtering property.
1501    *
1502    * @param templateName the substitution service template name
1503    * @param nodeTemplate the node template
1504    * @param count        the count
1505    */
1506   public static void addSubstitutionFilteringProperty(String templateName,
1507                                                       NodeTemplate nodeTemplate, int count) {
1508     Map<String, Object> serviceTemplateFilterPropertyValue = new HashMap<>();
1509     Map<String, Object> properties = nodeTemplate.getProperties();
1510     serviceTemplateFilterPropertyValue.put(ToscaConstants
1511         .SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, templateName);
1512     serviceTemplateFilterPropertyValue.put(ToscaConstants.COUNT_PROPERTY_NAME, count);
1513     properties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME,
1514         serviceTemplateFilterPropertyValue);
1515     nodeTemplate.setProperties(properties);
1516   }
1517
1518   /**
1519    * Adding binding requirement from port node template to compute node template.
1520    *
1521    * @param computeNodeTemplateId compute node template id
1522    * @param portNodeTemplate      port node template
1523    */
1524   public static void addBindingReqFromPortToCompute(String computeNodeTemplateId,
1525                                                     NodeTemplate portNodeTemplate) {
1526
1527
1528     mdcDataDebugMessage.debugEntryMessage(null, null);
1529     RequirementAssignment requirementAssignment = new RequirementAssignment();
1530     requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
1531     requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
1532     requirementAssignment.setNode(computeNodeTemplateId);
1533     addRequirementAssignment(portNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID,
1534         requirementAssignment);
1535     mdcDataDebugMessage.debugExitMessage(null, null);
1536   }
1537
1538   public static SubstitutionMapping createSubstitutionTemplateSubMapping(
1539       String nodeTypeKey,
1540       NodeType substitutionNodeType,
1541       Map<String, Map<String, List<String>>> mapping) {
1542     mdcDataDebugMessage.debugEntryMessage(null, null);
1543     SubstitutionMapping substitutionMapping = new SubstitutionMapping();
1544     substitutionMapping.setNode_type(nodeTypeKey);
1545     substitutionMapping.setCapabilities(
1546         manageCapabilityMapping(substitutionNodeType.getCapabilities(), mapping.get("capability")));
1547     substitutionMapping.setRequirements(
1548         manageRequirementMapping(substitutionNodeType.getRequirements(),
1549             mapping.get("requirement")));
1550
1551     mdcDataDebugMessage.debugExitMessage(null, null);
1552     return substitutionMapping;
1553   }
1554
1555   /**
1556    * Add node template capability.
1557    *
1558    * @param nodeTemplate         the node template
1559    * @param capabilityId         the capability id
1560    * @param capabilityProperties the capability properties
1561    * @param capabilityAttributes the capability attributes
1562    */
1563   public static void addNodeTemplateCapability(NodeTemplate nodeTemplate, String capabilityId,
1564                                                Map<String, Object> capabilityProperties,
1565                                                Map<String, Object> capabilityAttributes) {
1566     List<Map<String, CapabilityAssignment>> capabilities = nodeTemplate.getCapabilities();
1567     if (Objects.isNull(capabilities)) {
1568       capabilities = new ArrayList<>();
1569     }
1570     CapabilityAssignment capabilityAssignment = new CapabilityAssignment();
1571     capabilityAssignment.setProperties(capabilityProperties);
1572     capabilityAssignment.setAttributes(capabilityAttributes);
1573     Map<String, CapabilityAssignment> nodeTemplateCapability = new HashMap<>();
1574     nodeTemplateCapability.put(capabilityId, capabilityAssignment);
1575     capabilities.add(nodeTemplateCapability);
1576     nodeTemplate.setCapabilities(capabilities);
1577   }
1578
1579   private static Map<String, List<String>> manageRequirementMapping(
1580       List<Map<String, RequirementDefinition>> requirementList,
1581       Map<String, List<String>> requirementSubstitutionMapping) {
1582     mdcDataDebugMessage.debugEntryMessage(null, null);
1583
1584     if (requirementList == null) {
1585       return null;
1586     }
1587     Map<String, List<String>> requirementMapping = new HashMap<>();
1588     String requirementKey;
1589     List<String> requirementMap;
1590     for (Map<String, RequirementDefinition> requirementDefMap : requirementList) {
1591       for (Map.Entry<String, RequirementDefinition> entry : requirementDefMap.entrySet()) {
1592         requirementKey = entry.getKey();
1593         requirementMap = requirementSubstitutionMapping.get(requirementKey);
1594         requirementMapping.put(requirementKey, requirementMap);
1595       }
1596     }
1597
1598     mdcDataDebugMessage.debugExitMessage(null, null);
1599     return requirementMapping;
1600   }
1601
1602   private static Map<String, List<String>> manageCapabilityMapping(
1603       Map<String, CapabilityDefinition> capabilities,
1604       Map<String, List<String>> capabilitySubstitutionMapping) {
1605     mdcDataDebugMessage.debugEntryMessage(null, null);
1606
1607     if (capabilities == null) {
1608       mdcDataDebugMessage.debugExitMessage(null, null);
1609       return null;
1610     }
1611
1612     Map<String, List<String>> capabilityMapping = new HashMap<>();
1613     String capabilityKey;
1614     List<String> capabilityMap;
1615     for (Map.Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
1616       capabilityKey = entry.getKey();
1617       capabilityMap = capabilitySubstitutionMapping.get(capabilityKey);
1618       capabilityMapping.put(capabilityKey, capabilityMap);
1619     }
1620
1621     mdcDataDebugMessage.debugExitMessage(null, null);
1622     return capabilityMapping;
1623   }
1624
1625   public static void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType,
1626                                                          List<Map<String, RequirementDefinition>>
1627                                                              requirementsList,
1628                                                          String templateName) {
1629     mdcDataDebugMessage.debugEntryMessage(null, null);
1630
1631     if (requirementsList == null || requirementsList.size() == 0) {
1632       return;
1633     }
1634
1635     if (substitutionNodeType.getRequirements() == null) {
1636       substitutionNodeType.setRequirements(new ArrayList<>());
1637     }
1638
1639     for (Map<String, RequirementDefinition> requirementDef : requirementsList) {
1640       for (Map.Entry<String, RequirementDefinition> entry : requirementDef.entrySet()) {
1641         Map<String, RequirementDefinition> requirementMap = new HashMap<>();
1642         requirementMap.put(entry.getKey() + "_" + templateName, entry.getValue().clone());
1643         substitutionNodeType.getRequirements().add(requirementMap);
1644       }
1645     }
1646
1647     mdcDataDebugMessage.debugExitMessage(null, null);
1648   }
1649
1650   public static boolean isNodeTemplateSectionMissingFromServiceTemplate(ServiceTemplate serviceTemplate){
1651     return Objects.isNull(serviceTemplate.getTopology_template() )
1652         || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates());
1653   }
1654 }