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