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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.models.base;
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;
31 import java.util.Map.Entry;
32 import java.util.NavigableMap;
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;
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;
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.
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.
64 * @param C the concept being contained
68 @Table(name = "PfConceptContainer")
70 @EqualsAndHashCode(callSuper = false)
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;
76 private static final String VALUE_FIELD = "value";
77 private static final Pattern KEY_ID_PATTERN = Pattern.compile(PfKey.KEY_ID_REGEXP);
82 private PfConceptKey key;
84 @ManyToMany(cascade = CascadeType.ALL)
88 @JoinColumn(name = "conceptContainerMapName", referencedColumnName = "name"),
89 @JoinColumn(name = "concpetContainerMapVersion", referencedColumnName = "version")
91 inverseJoinColumns = {
92 @JoinColumn(name = "conceptContainerName", referencedColumnName = "name"),
93 @JoinColumn(name = "conceptContainerVersion", referencedColumnName = "version")
97 private Map<PfConceptKey, C> conceptMap;
100 * The Default Constructor creates a {@link PfConceptContainer} object with a null artifact key and creates an empty
103 public PfConceptContainer() {
104 this(new PfConceptKey());
108 * The Key Constructor creates a {@link PfConceptContainer} object with the given artifact key and creates an empty
111 * @param key the concept key
113 public PfConceptContainer(@NonNull final PfConceptKey key) {
114 this(key, new TreeMap<>());
118 * This Constructor creates an concept container with all of its fields defined.
120 * @param key the concept container key
121 * @param conceptMap the concepts to be stored in the concept container
123 public PfConceptContainer(@NonNull final PfConceptKey key, @NonNull final Map<PfConceptKey, C> conceptMap) {
127 this.conceptMap = new TreeMap<>(conceptMap);
133 * @param copyConcept the concept to copy from
135 public PfConceptContainer(@NonNull final PfConceptContainer<C, A> copyConcept) {
137 this.key = new PfConceptKey(copyConcept.key);
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);
148 public List<PfKey> getKeys() {
149 final List<PfKey> keyList = key.getKeys();
151 for (final C concept : conceptMap.values()) {
152 keyList.addAll(concept.getKeys());
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<>();
164 for (Entry<PfConceptKey, C> conceptEntry : getConceptMap().entrySet()) {
165 // Create a map to hold this entry
166 Map<String, A> toscaPolicyMap = new LinkedHashMap<>(1);
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());
173 // Add the map to the returned list
174 toscaConceptMapList.add(toscaPolicyMap);
177 return toscaConceptMapList;
181 public void fromAuthorative(List<Map<String, A>> authorativeList) {
182 // Clear any existing map entries
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()) {
190 var conceptKey = new PfConceptKey();
191 if (KEY_ID_PATTERN.matches(incomingConceptEntry.getKey())) {
192 conceptKey = new PfConceptKey(incomingConceptEntry.getKey());
194 conceptKey.setName(incomingConceptEntry.getKey());
195 if (incomingConceptEntry.getValue().getVersion() != null) {
196 conceptKey.setVersion(incomingConceptEntry.getValue().getVersion());
198 conceptKey.setVersion(PfKey.NULL_KEY_VERSION);
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));
207 var jpaConcept = getConceptNewInstance();
208 // This cast allows us to call the fromAuthorative method
209 @SuppressWarnings("unchecked")
210 PfAuthorative<A> authoritiveImpl = (PfAuthorative<A>) jpaConcept;
212 // Set the key name and the rest of the values on the concept
213 authoritiveImpl.fromAuthorative(incomingConceptEntry.getValue());
215 // After all that, save the map entry
216 conceptMap.put(conceptKey, jpaConcept);
220 if (conceptMap.isEmpty()) {
221 throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
222 "An incoming list of concepts must have at least one entry");
227 * Get an authorative list of the concepts in this container.
229 * @return the authorative list of concepts
231 public List<A> toAuthorativeList() {
232 List<A> toscaConceptList = new ArrayList<>();
234 for (Map<String, A> toscaConceptMap : toAuthorative()) {
235 toscaConceptList.addAll(toscaConceptMap.values());
238 return toscaConceptList;
242 public void clean() {
244 for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
245 conceptEntry.getKey().clean();
246 conceptEntry.getValue().clean();
251 public BeanValidationResult validate(@NonNull String fieldName) {
252 BeanValidationResult result = new PfValidator().validateTop(fieldName, this);
253 result.addResult(validateConceptMap());
259 * Validate the concept map of the container.
261 * @return the validation result
263 private ValidationResult validateConceptMap() {
264 var result = new BeanValidationResult("conceptMap", conceptMap);
266 for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
267 BeanValidationResult result2 = null;
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));
279 result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
280 result2.addResult(conceptEntry.getValue().validate(VALUE_FIELD));
283 result.addResult(result2);
285 return (result.isClean() ? null : result);
289 public int compareTo(final PfConcept otherConcept) {
290 if (otherConcept == null) {
293 if (this == otherConcept) {
296 if (getClass() != otherConcept.getClass()) {
297 return getClass().getName().compareTo(otherConcept.getClass().getName());
300 @SuppressWarnings("unchecked")
301 final PfConceptContainer<C, A> other = (PfConceptContainer<C, A>) otherConcept;
302 int retVal = key.compareTo(other.key);
307 return PfUtils.compareMaps(conceptMap, other.conceptMap);
311 * Get all the concepts that match the given name and version.
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
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);
321 final Set<C> returnSet = new TreeSet<>();
322 var foundConcept = get(conceptKeyName, conceptKeyVersion);
323 if (foundConcept != null) {
324 returnSet.add(foundConcept);
331 public C get(final PfConceptKey conceptKey) {
332 if (conceptKey.isNullVersion()) {
333 return get(conceptKey.getName());
335 return new PfConceptGetterImpl<>(getNavigableConceptMap()).get(conceptKey);
340 public C get(final String conceptKeyName) {
341 return new PfConceptGetterImpl<>(getNavigableConceptMap()).get(conceptKeyName);
345 public C get(final String conceptKeyName, final String conceptKeyVersion) {
346 return new PfConceptGetterImpl<>(getNavigableConceptMap()).get(conceptKeyName, conceptKeyVersion);
350 public Set<C> getAll(final String conceptKeyName) {
351 return new PfConceptGetterImpl<>(getNavigableConceptMap()).getAll(conceptKeyName);
355 public Set<C> getAll(final String conceptKeyName, final String conceptKeyVersion) {
356 return new PfConceptGetterImpl<>(getNavigableConceptMap()).getAll(conceptKeyName, conceptKeyVersion);
360 * Get the concept map as a NavigableMap object.
362 * @return NavigableMap conceptMap instance.
364 private NavigableMap<PfConceptKey, C> getNavigableConceptMap() {
365 return new TreeMap<>(conceptMap);
369 * Get a new empty instance of a concept for this concept map.
371 * @return the new instance
373 @SuppressWarnings("unchecked")
374 private C getConceptNewInstance() {
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);
385 private String findConceptField(final PfConceptKey conceptKey, final String keyFieldValue,
386 final PfNameVersion concept, final Function<PfNameVersion, String> fieldGetterFunction) {
388 String conceptField = fieldGetterFunction.apply(concept);
390 if (StringUtils.isBlank(conceptField) || keyFieldValue.equals(conceptField)) {
391 return keyFieldValue;
393 throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Key " + conceptKey.getId() + " field "
394 + keyFieldValue + " does not match the value " + conceptField + " in the concept field");