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