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