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