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