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