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