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