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