769b623c71648452e2c31741e0316d039e7d93f0
[policy/models.git] / models-tosca / src / main / java / org / onap / policy / models / tosca / simple / concepts / JpaToscaServiceTemplate.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2021 Nordix Foundation.
4  *  Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.tosca.simple.concepts;
23
24 import com.google.gson.annotations.SerializedName;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import javax.persistence.CascadeType;
31 import javax.persistence.Column;
32 import javax.persistence.Entity;
33 import javax.persistence.FetchType;
34 import javax.persistence.Inheritance;
35 import javax.persistence.InheritanceType;
36 import javax.persistence.JoinColumn;
37 import javax.persistence.OneToOne;
38 import javax.persistence.Table;
39 import lombok.Data;
40 import lombok.EqualsAndHashCode;
41 import lombok.NonNull;
42 import org.apache.commons.lang3.ObjectUtils;
43 import org.onap.policy.common.parameters.BeanValidationResult;
44 import org.onap.policy.common.parameters.annotations.NotBlank;
45 import org.onap.policy.common.parameters.annotations.NotNull;
46 import org.onap.policy.common.parameters.annotations.Valid;
47 import org.onap.policy.models.base.PfAuthorative;
48 import org.onap.policy.models.base.PfConcept;
49 import org.onap.policy.models.base.PfConceptKey;
50 import org.onap.policy.models.base.PfKey;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
52
53 /**
54  * This class holds a full TOSCA service template. Note: Only the policy specific parts of the TOSCA service template
55  * are implemented.
56  *
57  * @author Liam Fallon (liam.fallon@est.tech)
58  */
59
60 @Entity
61 @Table(name = "ToscaServiceTemplate")
62 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
63 @Data
64 @EqualsAndHashCode(callSuper = true)
65 public class JpaToscaServiceTemplate extends JpaToscaEntityType<ToscaServiceTemplate>
66         implements PfAuthorative<ToscaServiceTemplate> {
67     private static final long serialVersionUID = 8084846046148349401L;
68
69     public static final String DEFAULT_TOSCA_DEFINTIONS_VERISON = "tosca_simple_yaml_1_1_0";
70     public static final String DEFAULT_NAME = "ToscaServiceTemplateSimple";
71     public static final String DEFAULT_VERSION = "1.0.0";
72
73     // @formatter:off
74     @Column
75     @SerializedName("tosca_definitions_version")
76     @NotNull
77     @NotBlank
78     private String toscaDefinitionsVersion;
79
80     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
81     @JoinColumn(name = "dataTypesName",    referencedColumnName = "name")
82     @JoinColumn(name = "dataTypesVersion", referencedColumnName = "version")
83     @SerializedName("data_types")
84     @Valid
85     private JpaToscaDataTypes dataTypes;
86
87     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
88     @JoinColumn(name = "capabilityTypesName",    referencedColumnName = "name")
89     @JoinColumn(name = "capabilityTypesVersion", referencedColumnName = "version")
90     @SerializedName("capability_types")
91     @Valid
92     private JpaToscaCapabilityTypes capabilityTypes;
93
94     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
95     @JoinColumn(name = "relationshipTypesName",    referencedColumnName = "name")
96     @JoinColumn(name = "relationshipTypesVersion", referencedColumnName = "version")
97     @SerializedName("relationship_types")
98     @Valid
99     private JpaToscaRelationshipTypes relationshipTypes;
100
101     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
102     @JoinColumn(name = "nodeTypesName",    referencedColumnName = "name")
103     @JoinColumn(name = "nodeTypesVersion", referencedColumnName = "version")
104     @SerializedName("node_types")
105     @Valid
106     private JpaToscaNodeTypes nodeTypes;
107
108     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
109     @JoinColumn(name = "policyTypesName",    referencedColumnName = "name")
110     @JoinColumn(name = "policyTypesVersion", referencedColumnName = "version")
111     @SerializedName("policy_types")
112     @Valid
113     private JpaToscaPolicyTypes policyTypes;
114
115     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
116     @JoinColumn(name = "topologyTemplateParentKeyName",    referencedColumnName = "parentKeyName")
117     @JoinColumn(name = "topologyTemplateParentKeyVersion", referencedColumnName = "parentKeyVersion")
118     @JoinColumn(name = "topologyTemplateParentLocalName",  referencedColumnName = "parentLocalName")
119     @JoinColumn(name = "topologyTemplateLocalName",        referencedColumnName = "localName")
120     @SerializedName("topology_template")
121     @Valid
122     private JpaToscaTopologyTemplate topologyTemplate;
123     // @formatter:on
124
125     /**
126      * The Default Constructor creates a {@link JpaToscaServiceTemplate} object with a null key.
127      */
128     public JpaToscaServiceTemplate() {
129         this(new PfConceptKey(DEFAULT_NAME, DEFAULT_VERSION));
130     }
131
132     /**
133      * The Key Constructor creates a {@link JpaToscaServiceTemplate} object with the given concept key.
134      *
135      * @param key the key
136      */
137     public JpaToscaServiceTemplate(@NonNull final PfConceptKey key) {
138         this(key, DEFAULT_TOSCA_DEFINTIONS_VERISON);
139     }
140
141     /**
142      * The full constructor creates a {@link JpaToscaServiceTemplate} object with all mandatory parameters.
143      *
144      * @param key the key
145      * @param toscaDefinitionsVersion the TOSCA version string
146      */
147     public JpaToscaServiceTemplate(@NonNull final PfConceptKey key, @NonNull final String toscaDefinitionsVersion) {
148         super(key);
149         this.toscaDefinitionsVersion = toscaDefinitionsVersion;
150     }
151
152     /**
153      * Copy constructor.
154      *
155      * @param copyConcept the concept to copy from
156      */
157     public JpaToscaServiceTemplate(final JpaToscaServiceTemplate copyConcept) {
158         super(copyConcept);
159         this.toscaDefinitionsVersion = copyConcept.toscaDefinitionsVersion;
160         this.dataTypes = (copyConcept.dataTypes != null ? new JpaToscaDataTypes(copyConcept.dataTypes) : null);
161         this.capabilityTypes =
162                 (copyConcept.capabilityTypes != null ? new JpaToscaCapabilityTypes(copyConcept.capabilityTypes) : null);
163         this.relationshipTypes =
164                 (copyConcept.relationshipTypes != null ? new JpaToscaRelationshipTypes(copyConcept.relationshipTypes)
165                         : null);
166         this.nodeTypes = (copyConcept.nodeTypes != null ? new JpaToscaNodeTypes(copyConcept.nodeTypes) : null);
167         this.policyTypes = (copyConcept.policyTypes != null ? new JpaToscaPolicyTypes(copyConcept.policyTypes) : null);
168         this.topologyTemplate =
169                 (copyConcept.topologyTemplate != null ? new JpaToscaTopologyTemplate(copyConcept.topologyTemplate)
170                         : null);
171     }
172
173     /**
174      * Authorative constructor.
175      *
176      * @param authorativeConcept the authorative concept to copy from
177      */
178     public JpaToscaServiceTemplate(final ToscaServiceTemplate authorativeConcept) {
179         this.fromAuthorative(authorativeConcept);
180     }
181
182     @Override
183     public ToscaServiceTemplate toAuthorative() {
184         final var toscaServiceTemplate = new ToscaServiceTemplate();
185
186         super.setToscaEntity(toscaServiceTemplate);
187         super.toAuthorative();
188
189         toscaServiceTemplate.setToscaDefinitionsVersion(toscaDefinitionsVersion);
190
191         if (dataTypes != null) {
192             toscaServiceTemplate.setDataTypes(flattenMap(dataTypes.toAuthorative()));
193         }
194
195         if (capabilityTypes != null) {
196             toscaServiceTemplate.setCapabilityTypes(flattenMap(capabilityTypes.toAuthorative()));
197         }
198
199         if (relationshipTypes != null) {
200             toscaServiceTemplate.setRelationshipTypes(flattenMap(relationshipTypes.toAuthorative()));
201         }
202
203         if (nodeTypes != null) {
204             toscaServiceTemplate.setNodeTypes(flattenMap(nodeTypes.toAuthorative()));
205         }
206
207         if (policyTypes != null) {
208             toscaServiceTemplate.setPolicyTypes(flattenMap(policyTypes.toAuthorative()));
209         }
210
211         if (topologyTemplate != null) {
212             toscaServiceTemplate.setToscaTopologyTemplate(topologyTemplate.toAuthorative());
213         }
214
215         return toscaServiceTemplate;
216     }
217
218     /**
219      * Takes a list of maps and flattens it into a single map.
220      *
221      * @param list list to be be flattened
222      * @return a map containing all of the elements from the list of maps
223      */
224     private <V> Map<String, V> flattenMap(List<Map<String, V>> list) {
225         Map<String, V> result = new LinkedHashMap<>();
226
227         for (Map<String, V> map : list) {
228             result.putAll(map);
229         }
230
231         return result;
232     }
233
234     @Override
235     public void fromAuthorative(ToscaServiceTemplate toscaServiceTemplate) {
236         super.fromAuthorative(toscaServiceTemplate);
237
238         if (toscaServiceTemplate.getDefinedName() == null) {
239             getKey().setName(DEFAULT_NAME);
240         }
241
242         if (toscaServiceTemplate.getDefinedVersion() == null) {
243             getKey().setVersion(DEFAULT_VERSION);
244         }
245
246         toscaDefinitionsVersion = toscaServiceTemplate.getToscaDefinitionsVersion();
247
248         if (toscaServiceTemplate.getDataTypes() != null) {
249             dataTypes = new JpaToscaDataTypes();
250             dataTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getDataTypes()));
251         }
252
253         if (toscaServiceTemplate.getCapabilityTypes() != null) {
254             capabilityTypes = new JpaToscaCapabilityTypes();
255             capabilityTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getCapabilityTypes()));
256         }
257
258         if (toscaServiceTemplate.getRelationshipTypes() != null) {
259             relationshipTypes = new JpaToscaRelationshipTypes();
260             relationshipTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getRelationshipTypes()));
261         }
262
263         if (toscaServiceTemplate.getNodeTypes() != null) {
264             nodeTypes = new JpaToscaNodeTypes();
265             nodeTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getNodeTypes()));
266         }
267
268         if (toscaServiceTemplate.getPolicyTypes() != null) {
269             policyTypes = new JpaToscaPolicyTypes();
270             policyTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getPolicyTypes()));
271         }
272
273         if (toscaServiceTemplate.getToscaTopologyTemplate() != null) {
274             topologyTemplate = new JpaToscaTopologyTemplate();
275             topologyTemplate.fromAuthorative(toscaServiceTemplate.getToscaTopologyTemplate());
276         }
277     }
278
279     @Override
280     public List<PfKey> getKeys() {
281         final List<PfKey> keyList = super.getKeys();
282
283         if (dataTypes != null) {
284             keyList.addAll(dataTypes.getKeys());
285         }
286
287         if (capabilityTypes != null) {
288             keyList.addAll(capabilityTypes.getKeys());
289         }
290
291         if (relationshipTypes != null) {
292             keyList.addAll(relationshipTypes.getKeys());
293         }
294
295         if (nodeTypes != null) {
296             keyList.addAll(nodeTypes.getKeys());
297         }
298
299         if (policyTypes != null) {
300             keyList.addAll(policyTypes.getKeys());
301         }
302
303         if (topologyTemplate != null) {
304             keyList.addAll(topologyTemplate.getKeys());
305         }
306
307         return keyList;
308     }
309
310     @Override
311     public void clean() {
312         toscaDefinitionsVersion = toscaDefinitionsVersion.trim();
313
314         if (dataTypes != null) {
315             dataTypes.clean();
316         }
317
318         if (capabilityTypes != null) {
319             capabilityTypes.clean();
320         }
321
322         if (relationshipTypes != null) {
323             relationshipTypes.clean();
324         }
325
326         if (nodeTypes != null) {
327             nodeTypes.clean();
328         }
329
330         if (policyTypes != null) {
331             policyTypes.clean();
332         }
333
334         if (topologyTemplate != null) {
335             topologyTemplate.clean();
336         }
337     }
338
339     @Override
340     public BeanValidationResult validate(String fieldName) {
341         BeanValidationResult result = super.validate(fieldName);
342
343         // No point in validating cross references if the structure of the individual parts are not valid
344         if (!result.isValid()) {
345             return result;
346         }
347
348         validateReferencedDataTypes(result);
349
350         validatePolicyTypesInPolicies(result);
351
352         return result;
353     }
354
355     @Override
356     public int compareTo(final PfConcept otherConcept) {
357         int result = compareToWithoutEntities(otherConcept);
358         if (result != 0) {
359             return result;
360         }
361
362         final JpaToscaServiceTemplate other = (JpaToscaServiceTemplate) otherConcept;
363
364         result = ObjectUtils.compare(dataTypes, other.dataTypes);
365         if (result != 0) {
366             return result;
367         }
368
369         result = ObjectUtils.compare(capabilityTypes, other.capabilityTypes);
370         if (result != 0) {
371             return result;
372         }
373
374         result = ObjectUtils.compare(relationshipTypes, other.relationshipTypes);
375         if (result != 0) {
376             return result;
377         }
378
379         result = ObjectUtils.compare(nodeTypes, other.nodeTypes);
380         if (result != 0) {
381             return result;
382         }
383
384         result = ObjectUtils.compare(policyTypes, other.policyTypes);
385         if (result != 0) {
386             return result;
387         }
388
389         return ObjectUtils.compare(topologyTemplate, other.topologyTemplate);
390     }
391
392     /**
393      * Compare this service template to another service template, ignoring contained entitites.
394      *
395      * @param otherConcept the other topology template
396      * @return the result of the comparison
397      */
398     public int compareToWithoutEntities(final PfConcept otherConcept) {
399         if (otherConcept == null) {
400             return -1;
401         }
402         if (this == otherConcept) {
403             return 0;
404         }
405         if (getClass() != otherConcept.getClass()) {
406             return getClass().getName().compareTo(otherConcept.getClass().getName());
407         }
408
409         final JpaToscaServiceTemplate other = (JpaToscaServiceTemplate) otherConcept;
410         if (!super.equals(other)) {
411             return super.compareTo(other);
412         }
413
414         return ObjectUtils.compare(toscaDefinitionsVersion, other.toscaDefinitionsVersion);
415     }
416
417     /**
418      * Validate that all data types referenced in policy types exist.
419      *
420      * @param result where the results are added
421      */
422     private void validateReferencedDataTypes(final BeanValidationResult result) {
423         if (policyTypes == null) {
424             return;
425         }
426
427         if (dataTypes != null) {
428             for (JpaToscaDataType dataType : dataTypes.getAll(null)) {
429                 validateReferencedDataTypesExists(dataType.getReferencedDataTypes(), result);
430             }
431         }
432
433         for (JpaToscaPolicyType policyType : policyTypes.getAll(null)) {
434             validateReferencedDataTypesExists(policyType.getReferencedDataTypes(), result);
435         }
436     }
437
438     /**
439      * Validate that the referenced data types exist for a collection of data type keys.
440      *
441      * @param dataTypeKeyCollection the data type key collection
442      * @param result where the results are added
443      */
444     private void validateReferencedDataTypesExists(final Collection<PfConceptKey> dataTypeKeyCollection,
445             final BeanValidationResult result) {
446         for (PfConceptKey dataTypeKey : dataTypeKeyCollection) {
447             if (dataTypes == null || dataTypes.get(dataTypeKey) == null) {
448                 addResult(result, "data type", dataTypeKey.getId(), NOT_FOUND);
449             }
450         }
451     }
452
453     /**
454      * Validate that all policy types referenced in policies exist.
455      *
456      * @param result where the results are added
457      */
458     private void validatePolicyTypesInPolicies(BeanValidationResult result) {
459         if (topologyTemplate == null || topologyTemplate.getPolicies() == null
460                 || topologyTemplate.getPolicies().getConceptMap().isEmpty()) {
461             return;
462         }
463
464         if (policyTypes == null || policyTypes.getConceptMap().isEmpty()) {
465             addResult(result, "policyTypes", policyTypes,
466                     "no policy types are defined on the service template for the policies in the topology template");
467             return;
468         }
469
470         for (JpaToscaPolicy policy : topologyTemplate.getPolicies().getAll(null)) {
471             if (policyTypes.get(policy.getType()) == null) {
472                 addResult(result, "policy type", policy.getType().getId(), NOT_FOUND);
473             }
474         }
475     }
476 }