Fix sonars in policy models
[policy/models.git] / models-base / src / main / java / org / onap / policy / models / base / PfModel.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019-2021 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.base;
23
24 import java.util.List;
25 import java.util.Set;
26 import java.util.TreeSet;
27 import javax.persistence.EmbeddedId;
28 import javax.persistence.Entity;
29 import javax.persistence.Inheritance;
30 import javax.persistence.InheritanceType;
31 import javax.persistence.Table;
32 import lombok.Data;
33 import lombok.EqualsAndHashCode;
34 import lombok.NonNull;
35 import org.onap.policy.common.parameters.BeanValidationResult;
36 import org.onap.policy.common.parameters.ValidationStatus;
37 import org.onap.policy.common.parameters.annotations.NotNull;
38 import org.onap.policy.common.utils.validation.Assertions;
39 import org.onap.policy.models.base.validation.annotations.VerifyKey;
40
41 /**
42  * This class is the base class for all models in the Policy Framework. All model classes inherit
43  * from this model so all models must have a key and have key information.
44  *
45  * <p>Validation checks that the model key is valid. It goes on to check for null keys and checks
46  * each key for uniqueness in the model. A check is carried out to ensure that an {@link PfKeyInfo}
47  * instance exists for every {@link PfConceptKey} key. For each {@link PfReferenceKey} instance, a
48  * check is made that its parent and local name are nut null and that a {@link PfKeyInfo} entry
49  * exists for its parent. Then a check is made that each used {@link PfConceptKey} and
50  * {@link PfReferenceKey} usage references a key that exists. Finally, a check is made to ensure
51  * that an {@link PfConceptKey} instance exists for every {@link PfKeyInfo} instance.
52  *
53  * @param <C> the type of concept on which the interface is applied.
54  */
55
56 @Entity
57 @Table(name = "PfModel")
58 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
59 @Data
60 @EqualsAndHashCode(callSuper = false)
61 public abstract class PfModel extends PfConcept {
62     private static final String KEYS_TOKEN = "keys";
63
64     private static final long serialVersionUID = -771659065637205430L;
65
66     @EmbeddedId
67     @VerifyKey
68     @NotNull
69     private PfConceptKey key;
70
71     /**
72      * The Default Constructor creates this concept with a NULL artifact key.
73      */
74     protected PfModel() {
75         this(new PfConceptKey());
76     }
77
78     /**
79      * Constructor to create this concept with the specified key.
80      *
81      * @param key the key of this concept
82      */
83     protected PfModel(@NonNull final PfConceptKey key) {
84         super();
85         Assertions.argumentNotNull(key, "key may not be null");
86
87         this.key = key;
88     }
89
90     /**
91      * Copy constructor.
92      *
93      * @param copyConcept the concept to copy from
94      */
95     protected PfModel(@NonNull final PfModel copyConcept) {
96         super(copyConcept);
97         this.key = new PfConceptKey(copyConcept.key);
98     }
99
100     /**
101      * Registers this model with the {@link PfModelService}. All models are registered with the
102      * model service so that models can be references from anywhere in the Policy Framework system
103      * without being passed as references through deep call chains.
104      */
105     public abstract void register();
106
107     @Override
108     public List<PfKey> getKeys() {
109         return key.getKeys();
110     }
111
112     @Override
113     public void clean() {
114         key.clean();
115     }
116
117     @Override
118     public BeanValidationResult validate(@NonNull String fieldName) {
119         BeanValidationResult result = new PfValidator().validateTop(fieldName, this);
120
121         // Key consistency check
122         final Set<PfConceptKey> artifactKeySet = new TreeSet<>();
123         final Set<PfReferenceKey> referenceKeySet = new TreeSet<>();
124         final Set<PfKeyUse> usedKeySet = new TreeSet<>();
125
126         for (final PfKey pfKey : this.getKeys()) {
127             // Check for the two type of keys we have
128             if (pfKey instanceof PfConceptKey) {
129                 validateArtifactKeyInModel((PfConceptKey) pfKey, artifactKeySet, result);
130             } else if (pfKey instanceof PfReferenceKey) {
131                 validateReferenceKeyInModel((PfReferenceKey) pfKey, referenceKeySet, result);
132             } else {
133                 // It must be a PfKeyUse, nothing else is legal
134                 usedKeySet.add((PfKeyUse) pfKey);
135             }
136         }
137
138         // Check all reference keys have correct parent keys
139         for (final PfReferenceKey referenceKey : referenceKeySet) {
140             if (!artifactKeySet.contains(referenceKey.getParentConceptKey())) {
141                 addResult(result, "reference key", referenceKey, "parent artifact key not found");
142             }
143         }
144
145         validateKeyUses(usedKeySet, artifactKeySet, referenceKeySet, result);
146
147         return result;
148     }
149
150     /**
151      * Check for consistent usage of an artifact key in the model.
152      *
153      * @param artifactKey The artifact key to check
154      * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to
155      *        the set
156      * @param result where to add the results
157      */
158     private void validateArtifactKeyInModel(final PfConceptKey artifactKey,
159             final Set<PfConceptKey> artifactKeySet, final BeanValidationResult result) {
160
161         validateKeyNotNull(result, KEYS_TOKEN, artifactKey);
162
163         var result2 = new BeanValidationResult(KEYS_TOKEN, artifactKey);
164
165         // Null key name start check
166         if (artifactKey.getName().toUpperCase().startsWith(PfKey.NULL_KEY_NAME)) {
167             addResult(result2, "name of " + artifactKey.getId(), artifactKey.getName(),
168                             "starts with keyword " + PfKey.NULL_KEY_NAME);
169         }
170
171         // Unique key check
172         if (artifactKeySet.contains(artifactKey)) {
173             addResult(result, KEYS_TOKEN, artifactKey, "duplicate key");
174         } else {
175             artifactKeySet.add(artifactKey);
176         }
177     }
178
179     /**
180      * Check for consistent usage of a reference key in the model.
181      *
182      * @param referenceKey The reference key to check
183      * @param referenceKeySet The set of reference keys encountered so far, this key is appended to
184      *        the set
185      * @param result where to add the results
186      */
187     private void validateReferenceKeyInModel(final PfReferenceKey referenceKey,
188             final Set<PfReferenceKey> referenceKeySet, final BeanValidationResult result) {
189         // Null key check
190         if (referenceKey.isNullKey()) {
191             addResult(result, KEYS_TOKEN, referenceKey, IS_A_NULL_KEY);
192         }
193
194         var result2 = new BeanValidationResult(KEYS_TOKEN, referenceKey);
195
196         // Null parent key check
197         if (referenceKey.getParentConceptKey().isNullKey()) {
198             addResult(result2, "parent key of " + referenceKey.getId(), referenceKey.getParentConceptKey().getId(),
199                             IS_A_NULL_KEY);
200         }
201
202         // Null local name check
203         if (referenceKey.getLocalName().equals(PfKey.NULL_KEY_NAME)) {
204             addResult(result2, "local name of " + referenceKey.getId(), referenceKey.getLocalName(), IS_NULL);
205         }
206
207         // Null key name start check
208         if (referenceKey.getParentConceptKey().getName().toUpperCase().startsWith(PfKey.NULL_KEY_NAME)) {
209             addResult(result2, "parent name of " + referenceKey.getId(), referenceKey.getParentConceptKey().getName(),
210                             "starts with keyword " + PfKey.NULL_KEY_NAME);
211         }
212
213         // Unique key check
214         if (referenceKeySet.contains(referenceKey)) {
215             addResult(result, KEYS_TOKEN, referenceKey, "duplicate key");
216         } else {
217             referenceKeySet.add(referenceKey);
218         }
219     }
220
221     /**
222      * Check for consistent usage of cross-key references in the model.
223      *
224      * @param usedKeySet The set of all keys used in the model
225      * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to
226      *        the set
227      * @param referenceKeySet The set of reference keys encountered so far, this key is appended to
228      *        the set
229      * @param result where to add the results
230      */
231     private void validateKeyUses(final Set<PfKeyUse> usedKeySet, final Set<PfConceptKey> artifactKeySet,
232             final Set<PfReferenceKey> referenceKeySet, final BeanValidationResult result) {
233         // Check all key uses
234         for (final PfKeyUse usedKey : usedKeySet) {
235             if (usedKey.getKey() instanceof PfConceptKey) {
236                 // PfConceptKey usage, check the key exists
237                 if (!artifactKeySet.contains(usedKey.getKey())) {
238                     result.addResult("artifact key", usedKey.getId(), ValidationStatus.INVALID, NOT_DEFINED);
239                 }
240             } else {
241                 // PfReferenceKey usage, check the key exists
242                 if (!referenceKeySet.contains(usedKey.getKey())) {
243                     result.addResult("reference key", usedKey.getId(), ValidationStatus.INVALID, NOT_DEFINED);
244                 }
245             }
246         }
247     }
248
249     @Override
250     public int compareTo(final PfConcept otherObj) {
251         if (otherObj == null) {
252             return -1;
253         }
254         if (this == otherObj) {
255             return 0;
256         }
257         if (getClass() != otherObj.getClass()) {
258             return getClass().getName().compareTo(otherObj.getClass().getName());
259         }
260
261         final PfModel other = (PfModel) otherObj;
262
263         return key.compareTo(other.key);
264     }
265 }