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