Finish unit test on policy-models
[policy/models.git] / models-tosca / src / main / java / org / onap / policy / models / tosca / simple / concepts / JpaToscaPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Model
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.models.tosca.simple.concepts;
25
26 import java.util.ArrayList;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31
32 import javax.persistence.AttributeOverride;
33 import javax.persistence.AttributeOverrides;
34 import javax.persistence.Column;
35 import javax.persistence.ElementCollection;
36 import javax.persistence.Entity;
37 import javax.persistence.Inheritance;
38 import javax.persistence.InheritanceType;
39 import javax.persistence.Lob;
40 import javax.persistence.Table;
41
42 import lombok.Data;
43 import lombok.EqualsAndHashCode;
44 import lombok.NonNull;
45
46 import org.onap.policy.common.utils.validation.Assertions;
47 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
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.base.PfUtils;
53 import org.onap.policy.models.base.PfValidationMessage;
54 import org.onap.policy.models.base.PfValidationResult;
55 import org.onap.policy.models.base.PfValidationResult.ValidationResult;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
57
58 /**
59  * Class to represent the policy in TOSCA definition.
60  *
61  * @author Chenfei Gao (cgao@research.att.com)
62  * @author Liam Fallon (liam.fallon@est.tech)
63  */
64 @Entity
65 @Table(name = "ToscaPolicy")
66 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
67 @Data
68 @EqualsAndHashCode(callSuper = true)
69 public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements PfAuthorative<ToscaPolicy> {
70     private static final long serialVersionUID = 3265174757061982805L;
71
72     // @formatter:off
73     @Column
74     @AttributeOverrides({
75         @AttributeOverride(name = "name",
76                            column = @Column(name = "type_name")),
77         @AttributeOverride(name = "version",
78                            column = @Column(name = "type_version"))
79         })
80     private PfConceptKey type;
81
82     @ElementCollection
83     @Lob
84     private Map<String, String> properties;
85
86     @ElementCollection
87     private List<PfConceptKey> targets;
88     // @formatter:on
89
90     /**
91      * The Default Constructor creates a {@link JpaToscaPolicy} object with a null key.
92      */
93     public JpaToscaPolicy() {
94         this(new PfConceptKey());
95     }
96
97     /**
98      * The Key Constructor creates a {@link JpaToscaPolicy} object with the given concept key.
99      *
100      * @param key the key
101      */
102     public JpaToscaPolicy(@NonNull final PfConceptKey key) {
103         this(key, new PfConceptKey());
104     }
105
106     /**
107      * The full Constructor creates a {@link JpaToscaPolicy} object with all mandatory fields.
108      *
109      * @param key the key
110      * @param type the type of the policy
111      */
112     public JpaToscaPolicy(@NonNull final PfConceptKey key, @NonNull final PfConceptKey type) {
113         super(key);
114         this.type = type;
115     }
116
117     /**
118      * Copy constructor.
119      *
120      * @param copyConcept the concept to copy from
121      */
122     public JpaToscaPolicy(@NonNull final JpaToscaPolicy copyConcept) {
123         super(copyConcept);
124     }
125
126     /**
127      * Authorative constructor.
128      *
129      * @param authorativeConcept the authorative concept to copy from
130      */
131     public JpaToscaPolicy(final ToscaPolicy authorativeConcept) {
132         super(new PfConceptKey());
133         type = new PfConceptKey();
134         this.fromAuthorative(authorativeConcept);
135     }
136
137     @Override
138     public ToscaPolicy toAuthorative() {
139         ToscaPolicy toscaPolicy = new ToscaPolicy();
140         super.setToscaEntity(toscaPolicy);
141         super.toAuthorative();
142
143         toscaPolicy.setType(type.getName());
144
145         if (!PfKey.NULL_KEY_VERSION.equals(type.getVersion())) {
146             toscaPolicy.setTypeVersion(type.getVersion());
147         }
148         else {
149             toscaPolicy.setTypeVersion(null);
150         }
151
152         if (properties != null) {
153             Map<String, Object> propertyMap = new LinkedHashMap<>();
154
155             for (Entry<String, String> entry : properties.entrySet()) {
156                 propertyMap.put(entry.getKey(), entry.getValue());
157             }
158
159             toscaPolicy.setProperties(propertyMap);
160         }
161
162         return toscaPolicy;
163     }
164
165     @Override
166     public void fromAuthorative(@NonNull final ToscaPolicy toscaPolicy) {
167         super.fromAuthorative(toscaPolicy);
168
169         type.setName(toscaPolicy.getType());
170         type.setVersion(toscaPolicy.getTypeVersion());
171         if (type.getVersion() == null) {
172             type.setVersion(PfKey.NULL_KEY_VERSION);
173         }
174
175         if (toscaPolicy.getProperties() != null) {
176             properties = new LinkedHashMap<>();
177
178             for (Entry<String, Object> propertyEntry : toscaPolicy.getProperties().entrySet()) {
179                 // TODO: This is a HACK, we need to validate the properties against their
180                 // TODO: their data type in their policy type definition in TOSCA, which means reading
181                 // TODO: the policy type from the database and parsing the property value object correctly
182                 // TODO: Here we are simply serializing the property value into a string and storing it
183                 // TODO: unvalidated into the database
184                 properties.put(propertyEntry.getKey(), propertyEntry.getValue().toString());
185             }
186         }
187     }
188
189     @Override
190     public List<PfKey> getKeys() {
191         final List<PfKey> keyList = super.getKeys();
192
193         keyList.addAll(type.getKeys());
194
195         if (targets != null) {
196             keyList.addAll(targets);
197         }
198
199         return keyList;
200     }
201
202     @Override
203     public void clean() {
204         super.clean();
205
206         type.clean();
207
208         if (targets != null) {
209             for (PfConceptKey target : targets) {
210                 target.clean();
211             }
212         }
213     }
214
215     @Override
216     public PfValidationResult validate(@NonNull final PfValidationResult resultIn) {
217         PfValidationResult result = super.validate(resultIn);
218
219         if (type == null || type.isNullKey()) {
220             result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID,
221                     "type is null or a null key"));
222         } else {
223             result = type.validate(result);
224         }
225
226         if (properties != null) {
227             result = validateProperties(result);
228         }
229
230         if (targets != null) {
231             result = validateTargets(result);
232         }
233
234         return result;
235     }
236
237     /**
238      * Validate the policy properties.
239      *
240      * @param result The result of validations up to now
241      * @return the validation result
242      */
243     private PfValidationResult validateProperties(final PfValidationResult resultIn) {
244         PfValidationResult result = resultIn;
245
246         for (Entry<String, String> propertyEntry : properties.entrySet()) {
247             if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getKey())) {
248                 result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID,
249                         "policy property key may not be null "));
250             } else if (propertyEntry.getValue() == null) {
251                 result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID,
252                         "policy property value may not be null "));
253             }
254         }
255         return result;
256     }
257
258     /**
259      * Validate the policy targets.
260      *
261      * @param result The result of validations up to now
262      * @return the validation result
263      */
264     private PfValidationResult validateTargets(final PfValidationResult resultIn) {
265         PfValidationResult result = resultIn;
266
267         for (PfConceptKey target : targets) {
268             if (target == null) {
269                 result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID,
270                         "policy target may not be null "));
271             } else {
272                 result = target.validate(result);
273             }
274         }
275         return result;
276     }
277
278     @Override
279     public int compareTo(final PfConcept otherConcept) {
280         if (otherConcept == null) {
281             return -1;
282         }
283
284         if (this == otherConcept) {
285             return 0;
286         }
287
288         if (getClass() != otherConcept.getClass()) {
289             return this.hashCode() - otherConcept.hashCode();
290         }
291
292         final JpaToscaPolicy other = (JpaToscaPolicy) otherConcept;
293         if (!super.equals(other)) {
294             return super.compareTo(other);
295         }
296
297         if (!type.equals(other.type)) {
298             return type.compareTo(other.type);
299         }
300
301         int retVal = PfUtils.compareObjects(properties, other.properties);
302         if (retVal != 0) {
303             return retVal;
304         }
305
306         return PfUtils.compareObjects(targets, other.targets);
307     }
308
309     @Override
310     public PfConcept copyTo(@NonNull PfConcept target) {
311         final Object copyObject = target;
312         Assertions.instanceOf(copyObject, PfConcept.class);
313
314         final JpaToscaPolicy copy = ((JpaToscaPolicy) copyObject);
315         super.copyTo(target);
316
317         copy.setType(new PfConceptKey(type));
318
319         if (properties == null) {
320             copy.setProperties(null);
321         } else {
322             copy.setProperties(properties);
323         }
324
325         if (targets == null) {
326             copy.setTargets(null);
327         } else {
328             final List<PfConceptKey> newTargets = new ArrayList<>();
329             for (final PfConceptKey oldTarget : targets) {
330                 newTargets.add(new PfConceptKey(oldTarget));
331             }
332             copy.setTargets(newTargets);
333         }
334
335         return copy;
336     }
337 }