Merge "Add filter obejcts for concepts"
[policy/models.git] / models-pdp / src / main / java / org / onap / policy / models / pdp / persistence / concepts / JpaPdpSubGroup.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.pdp.persistence.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.CollectionTable;
33 import javax.persistence.Column;
34 import javax.persistence.ElementCollection;
35 import javax.persistence.EmbeddedId;
36 import javax.persistence.Entity;
37 import javax.persistence.Inheritance;
38 import javax.persistence.InheritanceType;
39 import javax.persistence.JoinColumn;
40 import javax.persistence.OneToMany;
41 import javax.persistence.Table;
42
43 import lombok.Data;
44 import lombok.EqualsAndHashCode;
45 import lombok.NonNull;
46
47 import org.onap.policy.common.utils.validation.Assertions;
48 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
49 import org.onap.policy.models.base.PfAuthorative;
50 import org.onap.policy.models.base.PfConcept;
51 import org.onap.policy.models.base.PfConceptKey;
52 import org.onap.policy.models.base.PfKey;
53 import org.onap.policy.models.base.PfKeyUse;
54 import org.onap.policy.models.base.PfReferenceKey;
55 import org.onap.policy.models.base.PfUtils;
56 import org.onap.policy.models.base.PfValidationMessage;
57 import org.onap.policy.models.base.PfValidationResult;
58 import org.onap.policy.models.base.PfValidationResult.ValidationResult;
59 import org.onap.policy.models.pdp.concepts.Pdp;
60 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
61 import org.onap.policy.models.pdp.concepts.ToscaPolicyIdentifier;
62 import org.onap.policy.models.pdp.concepts.ToscaPolicyTypeIdentifier;
63
64 /**
65  * Class to represent a PDP subgroup in the database.
66  *
67  * @author Liam Fallon (liam.fallon@est.tech)
68  */
69 @Entity
70 @Table(name = "PdpSubGroup")
71 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
72 @Data
73 @EqualsAndHashCode(callSuper = false)
74 public class JpaPdpSubGroup extends PfConcept implements PfAuthorative<PdpSubGroup> {
75     private static final long serialVersionUID = -357224425637789775L;
76
77     @EmbeddedId
78     private PfReferenceKey key;
79
80     @ElementCollection
81     private List<PfConceptKey> supportedPolicyTypes;
82
83     @ElementCollection
84     private List<PfConceptKey> policies;
85
86     @Column
87     private int currentInstanceCount;
88
89     @Column
90     private int desiredInstanceCount;
91
92     @ElementCollection
93     private Map<String, String> properties;
94
95     // @formatter:ofF
96     @OneToMany
97     @CollectionTable(joinColumns = {
98             @JoinColumn(name = "pdpSubGroupParentKeyName",    referencedColumnName = "parentKeyName"),
99             @JoinColumn(name = "pdpSubGroupParentKeyVersion", referencedColumnName = "parentKeyVersion"),
100             @JoinColumn(name = "pdpSubGroupParentLocalName",  referencedColumnName = "parentLocalName"),
101             @JoinColumn(name = "pdpSubGroupLocalName",        referencedColumnName = "localName")
102         })
103     // formatter:on
104     private List<JpaPdp> pdpInstances;
105
106     /**
107      * The Default Constructor creates a {@link JpaPdpSubGroup} object with a null key.
108      */
109     public JpaPdpSubGroup() {
110         this(new PfReferenceKey());
111     }
112
113     /**
114      * The Key Constructor creates a {@link JpaPdpSubGroup} object with the given concept key.
115      *
116      * @param key the key
117      */
118     public JpaPdpSubGroup(@NonNull final PfReferenceKey key) {
119         this(key, new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
120     }
121
122     /**
123      * The Key Constructor creates a {@link JpaPdpSubGroup} object with all mandatory fields.
124      *
125      * @param key the key
126      * @param supportedPolicyTypes Supported policy types
127      * @param policies policies deployed on this PDP subgroups
128      * @param pdpInstances the PDP instances on this PDP subgroups
129      */
130     public JpaPdpSubGroup(@NonNull final PfReferenceKey key, @NonNull final List<PfConceptKey> supportedPolicyTypes,
131             @NonNull List<PfConceptKey> policies, @NonNull final List<JpaPdp> pdpInstances) {
132         this.key = key;
133         this.supportedPolicyTypes = supportedPolicyTypes;
134         this.policies = policies;
135         this.pdpInstances = pdpInstances;
136     }
137
138     /**
139      * Copy constructor.
140      *
141      * @param copyConcept the concept to copy from
142      */
143     public JpaPdpSubGroup(final JpaPdpSubGroup copyConcept) {
144         super(copyConcept);
145     }
146
147     /**
148      * Authorative constructor.
149      *
150      * @param authorativeConcept the authorative concept to copy from
151      */
152     public JpaPdpSubGroup(final PdpSubGroup authorativeConcept) {
153         this.fromAuthorative(authorativeConcept);
154     }
155
156     @Override
157     public PdpSubGroup toAuthorative() {
158         PdpSubGroup pdpSubgroup = new PdpSubGroup();
159
160         pdpSubgroup.setPdpType(getKey().getLocalName());
161
162         pdpSubgroup.setSupportedPolicyTypes(new ArrayList<>());
163         for (PfConceptKey supportedPolicyTypeKey : supportedPolicyTypes) {
164             ToscaPolicyTypeIdentifier supportedPolicyTypeIdent = new ToscaPolicyTypeIdentifier(
165                     supportedPolicyTypeKey.getName(), supportedPolicyTypeKey.getVersion());
166             pdpSubgroup.getSupportedPolicyTypes().add(supportedPolicyTypeIdent);
167         }
168
169         pdpSubgroup.setPolicies(new ArrayList<>());
170         for (PfConceptKey policyKey : policies) {
171             ToscaPolicyIdentifier toscaPolicyIdentifier = new ToscaPolicyIdentifier();
172             toscaPolicyIdentifier.setName(policyKey.getName());
173             toscaPolicyIdentifier.setVersion(policyKey.getVersion());
174             pdpSubgroup.getPolicies().add(toscaPolicyIdentifier);
175         }
176
177         pdpSubgroup.setCurrentInstanceCount(currentInstanceCount);
178         pdpSubgroup.setDesiredInstanceCount(desiredInstanceCount);
179         pdpSubgroup.setProperties(properties == null ? null : new LinkedHashMap<>(properties));
180
181         pdpSubgroup.setPdpInstances(new ArrayList<>());
182         for (JpaPdp jpaPdp : pdpInstances) {
183             pdpSubgroup.getPdpInstances().add(jpaPdp.toAuthorative());
184         }
185
186         return pdpSubgroup;
187     }
188
189     @Override
190     public void fromAuthorative(final PdpSubGroup pdpSubgroup) {
191         if (this.getKey().isNullKey()) {
192             this.setKey(new PfReferenceKey());
193             getKey().setLocalName(pdpSubgroup.getPdpType());
194         }
195
196         this.supportedPolicyTypes = new ArrayList<>();
197         for (ToscaPolicyTypeIdentifier supportedPolicyType : pdpSubgroup.getSupportedPolicyTypes()) {
198             this.supportedPolicyTypes
199                     .add(new PfConceptKey(supportedPolicyType.getName(), supportedPolicyType.getVersion()));
200         }
201
202
203         this.policies = new ArrayList<>();
204         for (ToscaPolicyIdentifier toscaPolicyIdentifier : pdpSubgroup.getPolicies()) {
205             this.policies.add(new PfConceptKey(toscaPolicyIdentifier.getName(), toscaPolicyIdentifier.getVersion()));
206         }
207
208         this.currentInstanceCount = pdpSubgroup.getCurrentInstanceCount();
209         this.desiredInstanceCount = pdpSubgroup.getDesiredInstanceCount();
210         this.properties =
211                 (pdpSubgroup.getProperties() == null ? null : new LinkedHashMap<>(pdpSubgroup.getProperties()));
212
213         this.pdpInstances = new ArrayList<>();
214         for (Pdp pdp : pdpSubgroup.getPdpInstances()) {
215             JpaPdp jpaPdp = new JpaPdp();
216             jpaPdp.setKey(new PfReferenceKey(getKey(), pdp.getInstanceId()));
217             jpaPdp.fromAuthorative(pdp);
218             this.pdpInstances.add(jpaPdp);
219         }
220     }
221
222     @Override
223     public List<PfKey> getKeys() {
224         List<PfKey> keyList = getKey().getKeys();
225
226         for (PfConceptKey ptkey : supportedPolicyTypes) {
227             keyList.add(new PfKeyUse(ptkey));
228         }
229
230         for (PfConceptKey pkey : policies) {
231             keyList.add(new PfKeyUse(pkey));
232         }
233
234         for (JpaPdp jpaPdp : pdpInstances) {
235             keyList.addAll(jpaPdp.getKeys());
236         }
237
238
239         return keyList;
240     }
241
242     @Override
243     public void clean() {
244         key.clean();
245
246         for (PfConceptKey ptkey : supportedPolicyTypes) {
247             ptkey.clean();
248         }
249
250         for (PfConceptKey pkey : policies) {
251             pkey.clean();
252         }
253
254         if (properties != null) {
255             Map<String, String> cleanedPropertyMap = new LinkedHashMap<>();
256             for (Entry<String, String> propertyEntry : properties.entrySet()) {
257                 cleanedPropertyMap.put(propertyEntry.getKey().trim(), propertyEntry.getValue().trim());
258             }
259             properties = cleanedPropertyMap;
260         }
261
262         for (JpaPdp jpaPdp : pdpInstances) {
263             jpaPdp.clean();
264         }
265     }
266
267     @Override
268     public PfValidationResult validate(final PfValidationResult resultIn) {
269         PfValidationResult result = resultIn;
270
271         if (key.isNullKey()) {
272             result.addValidationMessage(
273                     new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key"));
274         }
275
276         result = key.validate(result);
277
278         if (key.getParentConceptKey().isNullKey()) {
279             result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
280                     "parent of key is a null key"));
281         }
282
283         if (currentInstanceCount < 0) {
284             result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
285                     "the current instance count of a PDP group may not be negative"));
286         }
287
288         if (desiredInstanceCount < 0) {
289             result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
290                     "the desired instance count of a PDP group may not be negative"));
291         }
292
293         if (properties != null) {
294             for (Entry<String, String> propertyEntry : properties.entrySet()) {
295                 if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getKey())) {
296                     result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
297                             "a property key may not be null or blank"));
298                 }
299                 if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getValue())) {
300                     result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
301                             "a property value may not be null or blank"));
302                 }
303             }
304         }
305
306
307         return validateSubConcepts(result);
308     }
309
310     /**
311      * Validate collections of sub concepts.
312      *
313      * @param result the result in which to store the validation result
314      * @return the validation result including the results of this method
315      */
316     private PfValidationResult validateSubConcepts(PfValidationResult result) {
317         if (supportedPolicyTypes == null || supportedPolicyTypes.isEmpty()) {
318             result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
319                     "a PDP subgroup must support at least one policy type"));
320         } else {
321             for (PfConceptKey supportedPolicyType : supportedPolicyTypes) {
322                 result = supportedPolicyType.validate(result);
323             }
324         }
325
326         if (policies == null) {
327             result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
328                     "a PDP subgroup must have a list of policies"));
329         } else {
330             for (PfConceptKey policyKey : policies) {
331                 result = policyKey.validate(result);
332             }
333         }
334
335         if (pdpInstances == null) {
336             result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
337                     "a PDP subgroup must have a list of PDPs"));
338         } else {
339             for (JpaPdp jpaPdp : pdpInstances) {
340                 result = jpaPdp.validate(result);
341             }
342         }
343
344         return result;
345     }
346
347     @Override
348     public int compareTo(final PfConcept otherConcept) {
349         if (otherConcept == null) {
350             return -1;
351         }
352         if (this == otherConcept) {
353             return 0;
354         }
355         if (getClass() != otherConcept.getClass()) {
356             return this.hashCode() - otherConcept.hashCode();
357         }
358
359         final JpaPdpSubGroup other = (JpaPdpSubGroup) otherConcept;
360         if (!key.equals(other.key)) {
361             return key.compareTo(other.key);
362         }
363
364         int result = PfUtils.compareObjects(supportedPolicyTypes, other.supportedPolicyTypes);
365         if (result != 0) {
366             return result;
367         }
368
369         result = PfUtils.compareObjects(policies, other.policies);
370         if (result != 0) {
371             return result;
372         }
373
374         if (currentInstanceCount != other.currentInstanceCount) {
375             return currentInstanceCount - other.currentInstanceCount;
376         }
377
378         if (desiredInstanceCount != other.desiredInstanceCount) {
379             return desiredInstanceCount - other.desiredInstanceCount;
380         }
381
382         result = PfUtils.compareObjects(properties, other.properties);
383         if (result != 0) {
384             return result;
385         }
386
387         return PfUtils.compareObjects(pdpInstances, other.pdpInstances);
388     }
389
390     @Override
391     public PfConcept copyTo(@NonNull final PfConcept target) {
392         Assertions.instanceOf(target, JpaPdpSubGroup.class);
393
394         final JpaPdpSubGroup copy = ((JpaPdpSubGroup) target);
395         copy.setKey(new PfReferenceKey(key));
396
397         copy.setSupportedPolicyTypes(PfUtils.mapList(supportedPolicyTypes, PfConceptKey::new));
398         copy.setPolicies(PfUtils.mapList(policies, PfConceptKey::new));
399         copy.setCurrentInstanceCount(currentInstanceCount);
400         copy.setDesiredInstanceCount(desiredInstanceCount);
401         copy.setProperties(properties == null ? null : new LinkedHashMap<>(properties));
402         copy.setPdpInstances(PfUtils.mapList(pdpInstances, JpaPdp::new));
403
404         return copy;
405     }
406 }