Changes for Checkstyle 8.32
[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 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.utils.validation.ParameterValidationUtils;
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.base.PfValidationMessage;
50 import org.onap.policy.models.base.PfValidationResult;
51 import org.onap.policy.models.base.PfValidationResult.ValidationResult;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
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 = "policyTypesName",    referencedColumnName = "name"),
95                 @JoinColumn(name = "policyTypesVersion", referencedColumnName = "version")
96             }
97         )
98     @SerializedName("policy_types")
99     private JpaToscaPolicyTypes policyTypes;
100
101     @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
102     @JoinColumns(
103             {
104                 @JoinColumn(name = "topologyTemplateParentKeyName",    referencedColumnName = "parentKeyName"),
105                 @JoinColumn(name = "topologyTemplateParentKeyVersion", referencedColumnName = "parentKeyVersion"),
106                 @JoinColumn(name = "topologyTemplateParentLocalName",  referencedColumnName = "parentLocalName"),
107                 @JoinColumn(name = "topologyTemplateLocalName",        referencedColumnName = "localName")
108             }
109         )
110     @SerializedName("topology_template")
111     private JpaToscaTopologyTemplate topologyTemplate;
112     // @formatter:on
113
114     /**
115      * The Default Constructor creates a {@link JpaToscaServiceTemplate} object with a null key.
116      */
117     public JpaToscaServiceTemplate() {
118         this(new PfConceptKey(DEFAULT_NAME, DEFAULT_VERSION));
119     }
120
121     /**
122      * The Key Constructor creates a {@link JpaToscaServiceTemplate} object with the given concept key.
123      *
124      * @param key the key
125      */
126     public JpaToscaServiceTemplate(@NonNull final PfConceptKey key) {
127         this(key, DEFAULT_TOSCA_DEFINTIONS_VERISON);
128     }
129
130     /**
131      * The full constructor creates a {@link JpaToscaServiceTemplate} object with all mandatory parameters.
132      *
133      * @param key the key
134      * @param toscaDefinitionsVersion the TOSCA version string
135      */
136     public JpaToscaServiceTemplate(@NonNull final PfConceptKey key, @NonNull final String toscaDefinitionsVersion) {
137         super(key);
138         this.toscaDefinitionsVersion = toscaDefinitionsVersion;
139     }
140
141     /**
142      * Copy constructor.
143      *
144      * @param copyConcept the concept to copy from
145      */
146     public JpaToscaServiceTemplate(final JpaToscaServiceTemplate copyConcept) {
147         super(copyConcept);
148         this.toscaDefinitionsVersion = copyConcept.toscaDefinitionsVersion;
149         this.dataTypes = (copyConcept.dataTypes != null ? new JpaToscaDataTypes(copyConcept.dataTypes) : null);
150         this.policyTypes = (copyConcept.policyTypes != null ? new JpaToscaPolicyTypes(copyConcept.policyTypes) : null);
151         this.topologyTemplate =
152                 (copyConcept.topologyTemplate != null ? new JpaToscaTopologyTemplate(copyConcept.topologyTemplate)
153                         : null);
154     }
155
156     /**
157      * Authorative constructor.
158      *
159      * @param authorativeConcept the authorative concept to copy from
160      */
161     public JpaToscaServiceTemplate(final ToscaServiceTemplate authorativeConcept) {
162         this.fromAuthorative(authorativeConcept);
163     }
164
165     @Override
166     public ToscaServiceTemplate toAuthorative() {
167         final ToscaServiceTemplate toscaServiceTemplate = new ToscaServiceTemplate();
168
169         super.setToscaEntity(toscaServiceTemplate);
170         super.toAuthorative();
171
172         toscaServiceTemplate.setToscaDefinitionsVersion(toscaDefinitionsVersion);
173
174         if (dataTypes != null) {
175             toscaServiceTemplate.setDataTypes(new LinkedHashMap<>());
176             List<Map<String, ToscaDataType>> dataTypeMapList = dataTypes.toAuthorative();
177             for (Map<String, ToscaDataType> dataTypeMap : dataTypeMapList) {
178                 toscaServiceTemplate.getDataTypes().putAll(dataTypeMap);
179             }
180         }
181
182         if (policyTypes != null) {
183             toscaServiceTemplate.setPolicyTypes(new LinkedHashMap<>());
184             List<Map<String, ToscaPolicyType>> policyTypeMapList = policyTypes.toAuthorative();
185             for (Map<String, ToscaPolicyType> policyTypeMap : policyTypeMapList) {
186                 toscaServiceTemplate.getPolicyTypes().putAll(policyTypeMap);
187             }
188         }
189
190         if (topologyTemplate != null) {
191             toscaServiceTemplate.setToscaTopologyTemplate(topologyTemplate.toAuthorative());
192         }
193
194         return toscaServiceTemplate;
195     }
196
197     @Override
198     public void fromAuthorative(ToscaServiceTemplate toscaServiceTemplate) {
199         super.fromAuthorative(toscaServiceTemplate);
200
201         if (PfKey.NULL_KEY_NAME.equals(getKey().getName())) {
202             getKey().setName(DEFAULT_NAME);
203         }
204
205         if (PfKey.NULL_KEY_VERSION.equals(getKey().getVersion())) {
206             getKey().setVersion(DEFAULT_VERSION);
207         }
208
209         toscaDefinitionsVersion = toscaServiceTemplate.getToscaDefinitionsVersion();
210
211         if (toscaServiceTemplate.getDataTypes() != null) {
212             dataTypes = new JpaToscaDataTypes();
213             dataTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getDataTypes()));
214         }
215
216         if (toscaServiceTemplate.getPolicyTypes() != null) {
217             policyTypes = new JpaToscaPolicyTypes();
218             policyTypes.fromAuthorative(Collections.singletonList(toscaServiceTemplate.getPolicyTypes()));
219         }
220
221         if (toscaServiceTemplate.getToscaTopologyTemplate() != null) {
222             topologyTemplate = new JpaToscaTopologyTemplate();
223             topologyTemplate.fromAuthorative(toscaServiceTemplate.getToscaTopologyTemplate());
224         }
225     }
226
227     @Override
228     public List<PfKey> getKeys() {
229         final List<PfKey> keyList = super.getKeys();
230
231         if (dataTypes != null) {
232             keyList.addAll(dataTypes.getKeys());
233         }
234
235         if (policyTypes != null) {
236             keyList.addAll(policyTypes.getKeys());
237         }
238
239         if (topologyTemplate != null) {
240             keyList.addAll(topologyTemplate.getKeys());
241         }
242
243         return keyList;
244     }
245
246     @Override
247     public void clean() {
248         toscaDefinitionsVersion = toscaDefinitionsVersion.trim();
249
250         if (dataTypes != null) {
251             dataTypes.clean();
252         }
253
254         if (policyTypes != null) {
255             policyTypes.clean();
256         }
257
258         if (topologyTemplate != null) {
259             topologyTemplate.clean();
260         }
261     }
262
263     @Override
264     public PfValidationResult validate(final PfValidationResult resultIn) {
265         PfValidationResult result = super.validate(resultIn);
266
267         if (!ParameterValidationUtils.validateStringParameter(toscaDefinitionsVersion)) {
268             result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID,
269                     "service template tosca definitions version may not be null"));
270         }
271
272         if (dataTypes != null) {
273             result = dataTypes.validate(result);
274         }
275
276         if (policyTypes != null) {
277             result = policyTypes.validate(result);
278         }
279
280         if (topologyTemplate != null) {
281             result = topologyTemplate.validate(result);
282         }
283
284         // No point in validating cross references if the structure of the individual parts are not valid
285         if (!result.isOk()) {
286             return result;
287         }
288
289         validateReferencedDataTypes(result);
290
291         return validatePolicyTypesInPolicies(result);
292     }
293
294     @Override
295     public int compareTo(final PfConcept otherConcept) {
296         int result = compareToWithoutEntities(otherConcept);
297         if (result != 0) {
298             return result;
299         }
300
301         final JpaToscaServiceTemplate other = (JpaToscaServiceTemplate) otherConcept;
302
303         result = ObjectUtils.compare(dataTypes, other.dataTypes);
304         if (result != 0) {
305             return result;
306         }
307
308         result = ObjectUtils.compare(policyTypes, other.policyTypes);
309         if (result != 0) {
310             return result;
311         }
312
313         return ObjectUtils.compare(topologyTemplate, other.topologyTemplate);
314     }
315
316     /**
317      * Compare this service template to another service template, ignoring contained entitites.
318      *
319      * @param otherConcept the other topology template
320      * @return the result of the comparison
321      */
322     public int compareToWithoutEntities(final PfConcept otherConcept) {
323         if (otherConcept == null) {
324             return -1;
325         }
326         if (this == otherConcept) {
327             return 0;
328         }
329         if (getClass() != otherConcept.getClass()) {
330             return getClass().getName().compareTo(otherConcept.getClass().getName());
331         }
332
333         final JpaToscaServiceTemplate other = (JpaToscaServiceTemplate) otherConcept;
334         if (!super.equals(other)) {
335             return super.compareTo(other);
336         }
337
338         return ObjectUtils.compare(toscaDefinitionsVersion, other.toscaDefinitionsVersion);
339     }
340
341     /**
342      * Validate that all data types referenced in policy types exist.
343      *
344      * @param result the validation result object to use for the validation result
345      * @return the validation result object
346      */
347     private PfValidationResult validateReferencedDataTypes(final PfValidationResult result) {
348         if (policyTypes == null) {
349             return result;
350         }
351
352         if (dataTypes != null) {
353             for (JpaToscaDataType dataType : dataTypes.getAll(null)) {
354                 validateReferencedDataTypesExists(dataType.getKey(), dataType.getReferencedDataTypes(), result);
355             }
356         }
357
358         for (JpaToscaPolicyType policyType : policyTypes.getAll(null)) {
359             validateReferencedDataTypesExists(policyType.getKey(), policyType.getReferencedDataTypes(), result);
360         }
361
362         return result;
363     }
364
365     /**
366      * Validate that the referenced data types exist for a collection of data type keys.
367      *
368      * @param referencingEntityKey the key of the referencing entity
369      * @param dataTypeKeyCollection the data type key collection
370      * @param result the result of the validation
371      */
372     private void validateReferencedDataTypesExists(final PfConceptKey referencingEntityKey,
373             final Collection<PfConceptKey> dataTypeKeyCollection, final PfValidationResult result) {
374         for (PfConceptKey dataTypeKey : dataTypeKeyCollection) {
375             if (dataTypes == null || dataTypes.get(dataTypeKey) == null) {
376                 result.addValidationMessage(new PfValidationMessage(referencingEntityKey, this.getClass(),
377                         ValidationResult.INVALID, "referenced data type " + dataTypeKey.getId() + " not found"));
378             }
379         }
380     }
381
382     /**
383      * Validate that all policy types referenced in policies exist.
384      *
385      * @param result the validation result object to use for the validation result
386      * @return the validation result object
387      */
388     private PfValidationResult validatePolicyTypesInPolicies(PfValidationResult result) {
389         if (topologyTemplate == null || topologyTemplate.getPolicies() == null
390                 || topologyTemplate.getPolicies().getConceptMap().isEmpty()) {
391             return result;
392         }
393
394         if (policyTypes == null || policyTypes.getConceptMap().isEmpty()) {
395             result.addValidationMessage(new PfValidationMessage(this.getKey(), this.getClass(),
396                     ValidationResult.INVALID,
397                     "no policy types are defined on the service template for the policies in the topology template"));
398             return result;
399         }
400
401         for (JpaToscaPolicy policy : topologyTemplate.getPolicies().getAll(null)) {
402             if (policyTypes.get(policy.getType()) == null) {
403                 result.addValidationMessage(
404                         new PfValidationMessage(policy.getKey(), this.getClass(), ValidationResult.INVALID,
405                                 "policy type " + policy.getType().getId() + " referenced in policy not found"));
406             }
407         }
408
409         return result;
410     }
411 }