push addional code
[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.openecomp.sdc.common.errors.CoreException;
24 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
25 import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition;
26 import org.openecomp.sdc.tosca.datatypes.model.Constraint;
27 import org.openecomp.sdc.tosca.datatypes.model.EntrySchema;
28 import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition;
29 import org.openecomp.sdc.tosca.datatypes.model.Metadata;
30 import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate;
31 import org.openecomp.sdc.tosca.datatypes.model.NodeType;
32 import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition;
33 import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition;
34 import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate;
35 import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment;
36 import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition;
37 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
38 import org.openecomp.sdc.tosca.datatypes.model.Status;
39 import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping;
40 import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate;
41 import org.openecomp.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt;
42 import org.openecomp.sdc.tosca.errors.InvalidAddActionNullEntityErrorBuilder;
43 import org.openecomp.sdc.tosca.errors.InvalidRequirementAssignmentErrorBuilder;
44
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collections;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Objects;
52 import java.util.stream.Collectors;
53
54 /**
55  * The type Data model util.
56  */
57 public class DataModelUtil {
58
59   /**
60    * Add substitution mapping.
61    *
62    * @param serviceTemplate     the service template
63    * @param substitutionMapping the substitution mapping
64    */
65   public static void addSubstitutionMapping(ServiceTemplate serviceTemplate,
66                                             SubstitutionMapping substitutionMapping) {
67     if (serviceTemplate == null) {
68       throw new CoreException(
69           new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", "Service Template")
70               .build());
71     }
72
73     if (serviceTemplate.getTopology_template() == null) {
74       serviceTemplate.setTopology_template(new TopologyTemplate());
75     }
76     serviceTemplate.getTopology_template().setSubstitution_mappings(substitutionMapping);
77   }
78
79   /**
80    * Add substitution mapping req.
81    *
82    * @param serviceTemplate                    the service template
83    * @param substitutionMappingRequirementId   the substitution mapping requirement id
84    * @param substitutionMappingRequirementList the substitution mapping requirement list
85    */
86   public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate,
87                                                String substitutionMappingRequirementId,
88                                                List<String> substitutionMappingRequirementList) {
89     if (serviceTemplate == null) {
90       throw new CoreException(
91           new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements",
92               "Service Template").build());
93     }
94
95     if (serviceTemplate.getTopology_template() == null) {
96       serviceTemplate.setTopology_template(new TopologyTemplate());
97     }
98     if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) {
99       serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
100     }
101     if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
102         == null) {
103       serviceTemplate.getTopology_template().getSubstitution_mappings()
104           .setRequirements(new HashMap<>());
105     }
106
107     serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements()
108         .put(substitutionMappingRequirementId, substitutionMappingRequirementList);
109   }
110
111   /**
112    * Add node template.
113    *
114    * @param serviceTemplate the service template
115    * @param nodeTemplateId  the node template id
116    * @param nodeTemplate    the node template
117    */
118   public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId,
119                                      NodeTemplate nodeTemplate) {
120     if (serviceTemplate == null) {
121       throw new CoreException(
122           new InvalidAddActionNullEntityErrorBuilder("Node Template", "Service Template").build());
123     }
124     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
125     if (Objects.isNull(topologyTemplate)) {
126       topologyTemplate = new TopologyTemplate();
127       serviceTemplate.setTopology_template(topologyTemplate);
128     }
129     if (topologyTemplate.getNode_templates() == null) {
130       topologyTemplate.setNode_templates(new HashMap<>());
131     }
132     topologyTemplate.getNode_templates().put(nodeTemplateId, nodeTemplate);
133   }
134
135   /**
136    * Add policy definition.
137    *
138    * @param serviceTemplate  the service template
139    * @param policyId         the policy id
140    * @param policyDefinition the policy definition
141    */
142   public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId,
143                                          PolicyDefinition policyDefinition) {
144     if (serviceTemplate == null) {
145       throw new CoreException(
146           new InvalidAddActionNullEntityErrorBuilder("Policy Definition", "Service Template")
147               .build());
148     }
149     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
150     if (Objects.isNull(topologyTemplate)) {
151       topologyTemplate = new TopologyTemplate();
152       serviceTemplate.setTopology_template(topologyTemplate);
153     }
154     if (topologyTemplate.getPolicies() == null) {
155       topologyTemplate.setPolicies(new HashMap<>());
156     }
157     topologyTemplate.getPolicies().put(policyId, policyDefinition);
158   }
159
160   /**
161    * Add node type.
162    *
163    * @param serviceTemplate the service template
164    * @param nodeTypeId      the node type id
165    * @param nodeType        the node type
166    */
167   public static void addNodeType(ServiceTemplate serviceTemplate, String nodeTypeId,
168                                  NodeType nodeType) {
169     if (serviceTemplate == null) {
170       throw new CoreException(
171           new InvalidAddActionNullEntityErrorBuilder("Node Type", "Service Template").build());
172     }
173     if (serviceTemplate.getNode_types() == null) {
174       serviceTemplate.setNode_types(new HashMap<>());
175     }
176     serviceTemplate.getNode_types().put(nodeTypeId, nodeType);
177   }
178
179   /**
180    * Add relationship template.
181    *
182    * @param serviceTemplate        the service template
183    * @param relationshipTemplateId the relationship template id
184    * @param relationshipTemplate   the relationship template
185    */
186   public static void addRelationshipTemplate(ServiceTemplate serviceTemplate,
187                                              String relationshipTemplateId,
188                                              RelationshipTemplate relationshipTemplate) {
189     if (serviceTemplate == null) {
190       throw new CoreException(
191           new InvalidAddActionNullEntityErrorBuilder("Relationship Template", "Service Template")
192               .build());
193     }
194     if (serviceTemplate.getTopology_template() == null) {
195       serviceTemplate.setTopology_template(new TopologyTemplate());
196     }
197     if (serviceTemplate.getTopology_template().getRelationship_templates() == null) {
198       serviceTemplate.getTopology_template().setRelationship_templates(new HashMap<>());
199     }
200     serviceTemplate.getTopology_template().getRelationship_templates()
201         .put(relationshipTemplateId, relationshipTemplate);
202   }
203
204   /**
205    * Add requirement assignment.
206    *
207    * @param nodeTemplate          the node template
208    * @param requirementId         the requirement id
209    * @param requirementAssignment the requirement assignment
210    */
211   public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId,
212                                               RequirementAssignment requirementAssignment) {
213     if (nodeTemplate == null) {
214       throw new CoreException(
215           new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", "Node Template")
216               .build());
217     }
218     if (requirementAssignment.getNode() == null) {
219       throw new CoreException(new InvalidRequirementAssignmentErrorBuilder(requirementId).build());
220     }
221
222     if (nodeTemplate.getRequirements() == null) {
223       nodeTemplate.setRequirements(new ArrayList<>());
224     }
225     Map<String, RequirementAssignment> requirement = new HashMap<>();
226     requirement.put(requirementId, requirementAssignment);
227     nodeTemplate.getRequirements().add(requirement);
228   }
229
230   /**
231    * Gets node template.
232    *
233    * @param serviceTemplate the service template
234    * @param nodeTemplateId  the node template id
235    * @return the node template
236    */
237   public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate,
238                                              String nodeTemplateId) {
239     if (serviceTemplate == null
240         || serviceTemplate.getTopology_template() == null
241         || serviceTemplate.getTopology_template().getNode_templates() == null) {
242       return null;
243     }
244     return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId);
245   }
246
247   /**
248    * Gets node type.
249    *
250    * @param serviceTemplate the service template
251    * @param nodeTypeId      the node type id
252    * @return the node type
253    */
254   public static NodeType getNodeType(ServiceTemplate serviceTemplate, String nodeTypeId) {
255     if (serviceTemplate == null || serviceTemplate.getNode_types() == null) {
256       return null;
257     }
258     return serviceTemplate.getNode_types().get(nodeTypeId);
259   }
260
261   /**
262    * Add group definition to topology template.
263    *
264    * @param serviceTemplate the service template
265    * @param groupName       the group name
266    * @param group           the group
267    */
268   public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate,
269                                                           String groupName, GroupDefinition group) {
270     if (serviceTemplate == null) {
271       throw new CoreException(
272           new InvalidAddActionNullEntityErrorBuilder("Group Definition", "Service Template")
273               .build());
274     }
275
276     TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
277     if (Objects.isNull(topologyTemplate)) {
278       topologyTemplate = new TopologyTemplate();
279       serviceTemplate.setTopology_template(topologyTemplate);
280     }
281     if (topologyTemplate.getGroups() == null) {
282       topologyTemplate.setGroups(new HashMap<>());
283     }
284     if (serviceTemplate.getTopology_template().getGroups() == null) {
285       Map<String, GroupDefinition> groups = new HashMap<>();
286       serviceTemplate.getTopology_template().setGroups(groups);
287     }
288     serviceTemplate.getTopology_template().getGroups().put(groupName, group);
289   }
290
291   /**
292    * Create property definition property definition.
293    *
294    * @param type        the type
295    * @param description the description
296    * @param required    the required
297    * @param constraints the constraints
298    * @param status      the status
299    * @param entrySchema the entry schema
300    * @param defaultVal  the default val
301    * @return the property definition
302    */
303   public static PropertyDefinition createPropertyDefinition(String type, String description,
304                                                             boolean required,
305                                                             List<Constraint> constraints,
306                                                             Status status,
307                                                             EntrySchema entrySchema,
308                                                             Object defaultVal) {
309     PropertyDefinition propDef = new PropertyDefinition();
310     propDef.setType(type);
311     propDef.setDescription(description);
312     propDef.setRequired(required);
313     propDef.setConstraints(constraints);
314     if (status != null) {
315       propDef.setStatus(status);
316     }
317     propDef.setEntry_schema(entrySchema);
318     propDef.set_default(defaultVal);
319
320     return propDef;
321   }
322
323   /**
324    * Create requirement requirement definition.
325    *
326    * @param capability   the capability
327    * @param node         the node
328    * @param relationship the relationship
329    * @param occurrences  the occurrences
330    * @return the requirement definition
331    */
332   public static RequirementDefinition createRequirement(String capability, String node,
333                                                         String relationship, Object[] occurrences) {
334     RequirementDefinition requirementDefinition = new RequirementDefinition();
335     requirementDefinition.setCapability(capability);
336     requirementDefinition.setNode(node);
337     requirementDefinition.setRelationship(relationship);
338     if (occurrences != null) {
339       requirementDefinition.setOccurrences(occurrences);
340     }
341     return requirementDefinition;
342   }
343
344   /**
345    * Create attribute definition attribute definition.
346    *
347    * @param type        the type
348    * @param description the description
349    * @param status      the status
350    * @param entrySchema the entry schema
351    * @param defaultVal  the default val
352    * @return the attribute definition
353    */
354   public static AttributeDefinition createAttributeDefinition(String type, String description,
355                                                               Status status,
356                                                               EntrySchema entrySchema,
357                                                               Object defaultVal) {
358     AttributeDefinition attributeDef = new AttributeDefinition();
359     attributeDef.setType(type);
360
361     if (description != null) {
362       attributeDef.setDescription(description);
363     }
364     if (status != null) {
365       attributeDef.setStatus(status);
366     }
367     attributeDef.setEntry_schema(entrySchema);
368     attributeDef.set_default(defaultVal);
369
370     return attributeDef;
371   }
372
373   /**
374    * Create valid values constraint constraint.
375    *
376    * @param values the values
377    * @return the constraint
378    */
379   public static Constraint createValidValuesConstraint(Object... values) {
380     Constraint validValues = new Constraint();
381     for (Object value : values) {
382       validValues.addValidValue(value);
383     }
384     return validValues;
385   }
386
387   /**
388    * Create metadata metadata.
389    *
390    * @param templateName    the template name
391    * @param templateVersion the template version
392    * @param templateAuthor  the template author
393    * @return the metadata
394    */
395   public static Metadata createMetadata(String templateName, String templateVersion,
396                                         String templateAuthor) {
397     Metadata metadata = new Metadata();
398     metadata.setTemplate_name(templateName);
399     metadata.setTemplate_version(templateVersion);
400     metadata.setTemplate_author(templateAuthor);
401
402     return metadata;
403   }
404
405   /**
406    * Create entry schema entry schema.
407    *
408    * @param type        the type
409    * @param description the description
410    * @param constraints the constraints
411    * @return the entry schema
412    */
413   public static EntrySchema createEntrySchema(String type, String description,
414                                               List<Constraint> constraints) {
415     EntrySchema entrySchema = new EntrySchema();
416     entrySchema.setType(type);
417     entrySchema.setDescription(description);
418     entrySchema.setConstraints(constraints);
419     return entrySchema;
420   }
421
422   /**
423    * Create valid values constraints list list.
424    *
425    * @param values the values
426    * @return the list
427    */
428   public static List<Constraint> createValidValuesConstraintsList(String... values) {
429     List<Constraint> constraints;
430     Constraint validValues;
431     constraints = new ArrayList<>();
432     validValues = DataModelUtil.createValidValuesConstraint(values);
433     constraints.add(validValues);
434     return constraints;
435   }
436
437   /**
438    * Create greater or equal constrain constraint.
439    *
440    * @param value the value
441    * @return the constraint
442    */
443   public static Constraint createGreaterOrEqualConstrain(Object value) {
444
445     Constraint constraint = new Constraint();
446     constraint.setGreater_or_equal(value);
447     return constraint;
448   }
449
450   /**
451    * Gets constrain list.
452    *
453    * @param constrains the constrains
454    * @return the constrain list
455    */
456   public static List<Constraint> getConstrainList(Constraint... constrains) {
457     return Arrays.asList(constrains);
458
459   }
460
461   /**
462    * Create get input property value from list parameter map.
463    *
464    * @param inputPropertyListName the input property list name
465    * @param indexInTheList        the index in the list
466    * @param nestedPropertyName    the nested property name
467    * @return the map
468    */
469   public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName,
470                                                                  int indexInTheList,
471                                                                  String... nestedPropertyName) {
472     List propertyList = new ArrayList<>();
473     propertyList.add(inputPropertyListName);
474     propertyList.add(indexInTheList);
475     if (nestedPropertyName != null) {
476       Collections.addAll(propertyList, nestedPropertyName);
477     }
478     Map getInputProperty = new HashMap<>();
479     getInputProperty.put(ToscaFunctions.GET_INPUT.getDisplayName(), propertyList);
480     return getInputProperty;
481   }
482
483   /**
484    * Convert property def to parameter def parameter definition ext.
485    *
486    * @param propertyDefinition the property definition
487    * @return the parameter definition ext
488    */
489   public static ParameterDefinitionExt convertPropertyDefToParameterDef(
490       PropertyDefinition propertyDefinition) {
491     if (propertyDefinition == null) {
492       return null;
493     }
494
495     ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt();
496     parameterDefinition.setType(propertyDefinition.getType());
497     parameterDefinition.setDescription(propertyDefinition.getDescription());
498     parameterDefinition.setRequired(propertyDefinition.getRequired());
499     parameterDefinition.set_default(propertyDefinition.get_default());
500     parameterDefinition.setStatus(propertyDefinition.getStatus());
501     parameterDefinition.setConstraints(propertyDefinition.getConstraints());
502     parameterDefinition.setEntry_schema(propertyDefinition.getEntry_schema());
503     parameterDefinition.setHidden(false);
504     parameterDefinition.setImmutable(false);
505
506     return parameterDefinition;
507   }
508
509   /**
510    * Convert attribute def to parameter def parameter definition ext.
511    *
512    * @param attributeDefinition the attribute definition
513    * @param outputValue         the output value
514    * @return the parameter definition ext
515    */
516   public static ParameterDefinitionExt convertAttributeDefToParameterDef(
517       AttributeDefinition attributeDefinition, Map<String, List> outputValue) {
518     if (attributeDefinition == null) {
519       return null;
520     }
521     ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt();
522     parameterDefinition.setDescription(attributeDefinition.getDescription());
523     parameterDefinition.setValue(outputValue);
524     return parameterDefinition;
525   }
526
527   /**
528    * Clone constraints list.
529    *
530    * @param constraints the constraints
531    * @return the list
532    */
533   public static List<Constraint> cloneConstraints(List<Constraint> constraints) {
534     if (constraints == null) {
535       return null;
536     }
537     return constraints.stream().map(Constraint::clone).collect(Collectors.toList());
538   }
539
540   /**
541    * Clone valid source types list.
542    *
543    * @param validSourceTypes the valid source types
544    * @return the list
545    */
546   public static List<String> cloneValidSourceTypes(List<String> validSourceTypes) {
547     if (validSourceTypes == null) {
548       return null;
549     }
550     return validSourceTypes.stream().collect(Collectors.toList());
551   }
552
553   /**
554    * Clone property definitions map.
555    *
556    * @param propertyDefinitions the property definitions
557    * @return the map
558    */
559   public static Map<String, PropertyDefinition> clonePropertyDefinitions(
560       Map<String, PropertyDefinition> propertyDefinitions) {
561     if (propertyDefinitions == null) {
562       return null;
563     }
564     Map<String, PropertyDefinition> clonedProperties = new HashMap<>();
565     for (String propertyKey : propertyDefinitions.keySet()) {
566       clonedProperties.put(propertyKey, propertyDefinitions.get(propertyKey).clone());
567     }
568     return clonedProperties;
569   }
570
571   /**
572    * Clone attribute definitions map.
573    *
574    * @param attributeDefinitions the attribute definitions
575    * @return the map
576    */
577   public static Map<String, AttributeDefinition> cloneAttributeDefinitions(
578       Map<String, AttributeDefinition> attributeDefinitions) {
579     if (attributeDefinitions == null) {
580       return null;
581     }
582     Map<String, AttributeDefinition> clonedAttributeDefinitions = new HashMap<>();
583     for (String attributeKey : attributeDefinitions.keySet()) {
584       clonedAttributeDefinitions.put(attributeKey, attributeDefinitions.get(attributeKey).clone());
585     }
586     return clonedAttributeDefinitions;
587   }
588 }