Address more sonar issues in policy-models
[policy/models.git] / models-base / src / main / java / org / onap / policy / models / base / PfConceptContainer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2019-2020 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 com.google.re2j.Pattern;
25 import java.lang.reflect.ParameterizedType;
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 import java.util.NavigableMap;
32 import java.util.Set;
33 import java.util.TreeMap;
34 import java.util.TreeSet;
35 import java.util.function.Function;
36 import javax.persistence.CascadeType;
37 import javax.persistence.EmbeddedId;
38 import javax.persistence.Entity;
39 import javax.persistence.JoinColumn;
40 import javax.persistence.JoinTable;
41 import javax.persistence.ManyToMany;
42 import javax.persistence.MappedSuperclass;
43 import javax.persistence.Table;
44 import javax.ws.rs.core.Response;
45 import lombok.Data;
46 import lombok.EqualsAndHashCode;
47 import lombok.NonNull;
48 import org.apache.commons.lang3.StringUtils;
49 import org.onap.policy.models.base.PfValidationResult.ValidationResult;
50
51 // @formatter:off
52 /**
53  * This class is a concept container and holds a map of concepts. The {@link PfConceptContainer} class implements the
54  * helper methods of the {@link PfConceptGetter} interface to allow {@link PfConceptContainer} instances to be retrieved
55  * by calling methods directly on this class without referencing the contained map.
56  *
57  * <p>Validation checks that a container key is not null. An error is issued if no concepts are defined in a container.
58  * Each concept entry is checked to ensure that its key and value are not null and that the key matches the key in the
59  * map value. Each concept entry is then validated individually.
60  *
61  * @param C the concept being contained
62  */
63 //@formatter:on
64 @MappedSuperclass
65 @Entity
66 @Table(name = "PfConceptContainer")
67 @Data
68 @EqualsAndHashCode(callSuper = false)
69
70 public class PfConceptContainer<C extends PfConcept, A extends PfNameVersion> extends PfConcept
71     implements PfConceptGetter<C>, PfAuthorative<List<Map<String, A>>> {
72     private static final long serialVersionUID = -324211738823208318L;
73
74     private static final Pattern KEY_ID_PATTERN = Pattern.compile(PfKey.KEY_ID_REGEXP);
75
76     @EmbeddedId
77     private PfConceptKey key;
78
79     @ManyToMany(cascade = CascadeType.ALL)
80     // @formatter:off
81     @JoinTable(
82             joinColumns = {
83                 @JoinColumn(name = "conceptContainerMapName",    referencedColumnName = "name"),
84                 @JoinColumn(name = "concpetContainerMapVersion", referencedColumnName = "version")
85             },
86             inverseJoinColumns = {
87                 @JoinColumn(name = "conceptContainerName",    referencedColumnName = "name"),
88                 @JoinColumn(name = "conceptContainerVersion", referencedColumnName = "version")
89             }
90         )
91     // @formatter:on
92     private Map<PfConceptKey, C> conceptMap;
93
94     /**
95      * The Default Constructor creates a {@link PfConceptContainer} object with a null artifact key and creates an empty
96      * concept map.
97      */
98     public PfConceptContainer() {
99         this(new PfConceptKey());
100     }
101
102     /**
103      * The Key Constructor creates a {@link PfConceptContainer} object with the given artifact key and creates an empty
104      * concept map.
105      *
106      * @param key the concept key
107      */
108     public PfConceptContainer(@NonNull final PfConceptKey key) {
109         this(key, new TreeMap<>());
110     }
111
112     /**
113      * This Constructor creates an concept container with all of its fields defined.
114      *
115      * @param key the concept container key
116      * @param conceptMap the concepts to be stored in the concept container
117      */
118     public PfConceptContainer(@NonNull final PfConceptKey key, @NonNull final Map<PfConceptKey, C> conceptMap) {
119         super();
120
121         this.key = key;
122         this.conceptMap = new TreeMap<>(conceptMap);
123     }
124
125     /**
126      * Copy constructor.
127      *
128      * @param copyConcept the concept to copy from
129      */
130     public PfConceptContainer(@NonNull final PfConceptContainer<C, A> copyConcept) {
131         super(copyConcept);
132         this.key = new PfConceptKey(copyConcept.key);
133
134         this.conceptMap = new TreeMap<>();
135         for (final Entry<PfConceptKey, C> conceptMapEntry : copyConcept.conceptMap.entrySet()) {
136             PfConceptKey newK = new PfConceptKey(conceptMapEntry.getKey());
137             C newC = PfUtils.makeCopy(conceptMapEntry.getValue());
138             this.conceptMap.put(newK, newC);
139         }
140     }
141
142     @Override
143     public List<PfKey> getKeys() {
144         final List<PfKey> keyList = key.getKeys();
145
146         for (final C concept : conceptMap.values()) {
147             keyList.addAll(concept.getKeys());
148         }
149
150         return keyList;
151     }
152
153     @Override
154     public List<Map<String, A>> toAuthorative() {
155         // The returned list is a list of map singletons with one map for each map
156         // entry in the concept container
157         List<Map<String, A>> toscaConceptMapList = new ArrayList<>();
158
159         for (Entry<PfConceptKey, C> conceptEntry : getConceptMap().entrySet()) {
160             // Create a map to hold this entry
161             Map<String, A> toscaPolicyMap = new LinkedHashMap<>(1);
162
163             // Add the concept container entry to the singleton map
164             @SuppressWarnings("unchecked")
165             PfAuthorative<A> authoritiveImpl = (PfAuthorative<A>) conceptEntry.getValue();
166             toscaPolicyMap.put(conceptEntry.getKey().getName(), authoritiveImpl.toAuthorative());
167
168             // Add the map to the returned list
169             toscaConceptMapList.add(toscaPolicyMap);
170         }
171
172         return toscaConceptMapList;
173     }
174
175     @Override
176     public void fromAuthorative(List<Map<String, A>> authorativeList) {
177         // Clear any existing map entries
178         conceptMap.clear();
179
180         // Concepts are in lists of maps
181         for (Map<String, A> incomingConceptMap : authorativeList) {
182             // Add the map entries one by one
183             for (Entry<String, A> incomingConceptEntry : incomingConceptMap.entrySet()) {
184
185                 PfConceptKey conceptKey = new PfConceptKey();
186                 if (KEY_ID_PATTERN.matches(incomingConceptEntry.getKey())) {
187                     conceptKey = new PfConceptKey(incomingConceptEntry.getKey());
188                 } else {
189                     conceptKey.setName(incomingConceptEntry.getKey());
190                     if (incomingConceptEntry.getValue().getVersion() != null) {
191                         conceptKey.setVersion(incomingConceptEntry.getValue().getVersion());
192                     } else {
193                         conceptKey.setVersion(PfKey.NULL_KEY_VERSION);
194                     }
195                 }
196
197                 incomingConceptEntry.getValue().setName(findConceptField(conceptKey, conceptKey.getName(),
198                     incomingConceptEntry.getValue(), PfNameVersion::getName));
199                 incomingConceptEntry.getValue().setVersion(findConceptField(conceptKey, conceptKey.getVersion(),
200                     incomingConceptEntry.getValue(), PfNameVersion::getVersion));
201
202                 C jpaConcept = getConceptNewInstance();
203                 // This cast allows us to call the fromAuthorative method
204                 @SuppressWarnings("unchecked")
205                 PfAuthorative<A> authoritiveImpl = (PfAuthorative<A>) jpaConcept;
206
207                 // Set the key name and the rest of the values on the concept
208                 authoritiveImpl.fromAuthorative(incomingConceptEntry.getValue());
209
210                 // After all that, save the map entry
211                 conceptMap.put(conceptKey, jpaConcept);
212             }
213         }
214
215         if (conceptMap.isEmpty()) {
216             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
217                 "An incoming list of concepts must have at least one entry");
218         }
219     }
220
221     /**
222      * Get an authorative list of the concepts in this container.
223      *
224      * @return the authorative list of concepts
225      */
226     public List<A> toAuthorativeList() {
227         List<A> toscaConceptList = new ArrayList<>();
228
229         for (Map<String, A> toscaConceptMap : toAuthorative()) {
230             toscaConceptList.addAll(toscaConceptMap.values());
231         }
232
233         return toscaConceptList;
234     }
235
236     @Override
237     public void clean() {
238         key.clean();
239         for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
240             conceptEntry.getKey().clean();
241             conceptEntry.getValue().clean();
242         }
243     }
244
245     @Override
246     public PfValidationResult validate(@NonNull final PfValidationResult resultIn) {
247         PfValidationResult result = resultIn;
248
249         if (key.equals(PfConceptKey.getNullKey())) {
250             result.addValidationMessage(
251                 new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key"));
252         }
253
254         result = key.validate(result);
255
256         if (!conceptMap.isEmpty()) {
257             result = validateConceptMap(result);
258         }
259
260         return result;
261     }
262
263     /**
264      * Validate the concept map of the container.
265      *
266      * @param resultIn the incoming validation results so far
267      * @return the validation results with the results of this validation added
268      */
269     private PfValidationResult validateConceptMap(final PfValidationResult resultIn) {
270         PfValidationResult result = resultIn;
271
272         for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
273             if (conceptEntry.getKey().equals(PfConceptKey.getNullKey())) {
274                 result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
275                     "key on concept entry " + conceptEntry.getKey() + " may not be the null key"));
276             } else if (conceptEntry.getValue() == null) {
277                 result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
278                     "value on concept entry " + conceptEntry.getKey() + " may not be null"));
279             } else if (!conceptEntry.getKey().equals(conceptEntry.getValue().getKey())) {
280                 result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
281                     "key on concept entry key " + conceptEntry.getKey() + " does not equal concept value key "
282                         + conceptEntry.getValue().getKey()));
283                 result = conceptEntry.getValue().validate(result);
284             } else {
285                 result = conceptEntry.getValue().validate(result);
286             }
287         }
288         return result;
289     }
290
291     @Override
292     public int compareTo(final PfConcept otherConcept) {
293         if (otherConcept == null) {
294             return -1;
295         }
296         if (this == otherConcept) {
297             return 0;
298         }
299         if (getClass() != otherConcept.getClass()) {
300             return getClass().getName().compareTo(otherConcept.getClass().getName());
301         }
302
303         @SuppressWarnings("unchecked")
304         final PfConceptContainer<C, A> other = (PfConceptContainer<C, A>) otherConcept;
305         int retVal = key.compareTo(other.key);
306         if (retVal != 0) {
307             return retVal;
308         }
309
310         if (!conceptMap.equals(other.conceptMap)) {
311             return (conceptMap.hashCode() - other.conceptMap.hashCode());
312         }
313
314         return 0;
315     }
316
317     /**
318      * Get all the concepts that match the given name and version.
319      *
320      * @param conceptKeyName the name of the concept, if null, return all names
321      * @param conceptKeyVersion the version of the concept, if null, return all versions
322      * @return conceptKeyVersion
323      */
324     public Set<C> getAllNamesAndVersions(final String conceptKeyName, final String conceptKeyVersion) {
325         if (conceptKeyName == null || conceptKeyVersion == null || PfKey.NULL_KEY_VERSION.equals(conceptKeyVersion)) {
326             return getAll(conceptKeyName, conceptKeyVersion);
327         } else {
328             final Set<C> returnSet = new TreeSet<>();
329             C foundConcept = get(conceptKeyName, conceptKeyVersion);
330             if (foundConcept != null) {
331                 returnSet.add(foundConcept);
332             }
333             return returnSet;
334         }
335     }
336
337     @Override
338     public C get(final PfConceptKey conceptKey) {
339         if (conceptKey.isNullVersion()) {
340             return get(conceptKey.getName());
341         } else {
342             return new PfConceptGetterImpl<>((NavigableMap<PfConceptKey, C>) conceptMap).get(conceptKey);
343         }
344     }
345
346     @Override
347     public C get(final String conceptKeyName) {
348         return new PfConceptGetterImpl<>((NavigableMap<PfConceptKey, C>) conceptMap).get(conceptKeyName);
349     }
350
351     @Override
352     public C get(final String conceptKeyName, final String conceptKeyVersion) {
353         return new PfConceptGetterImpl<>((NavigableMap<PfConceptKey, C>) conceptMap).get(conceptKeyName,
354             conceptKeyVersion);
355     }
356
357     @Override
358     public Set<C> getAll(final String conceptKeyName) {
359         return new PfConceptGetterImpl<>((NavigableMap<PfConceptKey, C>) conceptMap).getAll(conceptKeyName);
360     }
361
362     @Override
363     public Set<C> getAll(final String conceptKeyName, final String conceptKeyVersion) {
364         return new PfConceptGetterImpl<>((NavigableMap<PfConceptKey, C>) conceptMap).getAll(conceptKeyName,
365             conceptKeyVersion);
366     }
367
368     /**
369      * Get a new empty instance of a concept for this concept map.
370      *
371      * @return the new instance
372      */
373     @SuppressWarnings("unchecked")
374     private C getConceptNewInstance() {
375         try {
376             String conceptClassName =
377                 ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
378             return (C) Class.forName(conceptClassName).getDeclaredConstructor().newInstance();
379         } catch (Exception ex) {
380             throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR,
381                 "failed to instantiate instance of container concept class", ex);
382         }
383     }
384
385     private String findConceptField(final PfConceptKey conceptKey, final String keyFieldValue,
386         final PfNameVersion concept, final Function<PfNameVersion, String> fieldGetterFunction) {
387
388         String conceptField = fieldGetterFunction.apply(concept);
389
390         if (StringUtils.isBlank(conceptField) || keyFieldValue.equals(conceptField)) {
391             return keyFieldValue;
392         } else {
393             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Key " + conceptKey.getId() + " field "
394                 + keyFieldValue + " does not match the value " + conceptField + " in the concept field");
395         }
396     }
397 }