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