2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020, 2023 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 jakarta.persistence.CascadeType;
27 import jakarta.persistence.EmbeddedId;
28 import jakarta.persistence.JoinColumn;
29 import jakarta.persistence.JoinTable;
30 import jakarta.persistence.ManyToMany;
31 import jakarta.persistence.MappedSuperclass;
32 import jakarta.persistence.Table;
33 import jakarta.ws.rs.core.Response;
34 import java.io.Serial;
35 import java.lang.reflect.ParameterizedType;
36 import java.util.ArrayList;
37 import java.util.LinkedHashMap;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.NavigableMap;
43 import java.util.TreeMap;
44 import java.util.TreeSet;
45 import java.util.function.Function;
47 import lombok.EqualsAndHashCode;
48 import lombok.NonNull;
49 import org.apache.commons.lang3.StringUtils;
50 import org.onap.policy.common.parameters.BeanValidationResult;
51 import org.onap.policy.common.parameters.ValidationResult;
52 import org.onap.policy.common.parameters.annotations.NotNull;
53 import org.onap.policy.models.base.validation.annotations.VerifyKey;
57 * This class is a concept container and holds a map of concepts. The {@link PfConceptContainer} class implements the
58 * helper methods of the {@link PfConceptGetter} interface to allow {@link PfConceptContainer} instances to be retrieved
59 * by calling methods directly on this class without referencing the contained map.
61 * <p>Validation checks that a container key is not null. An error is issued if no concepts are defined in a container.
62 * Each concept entry is checked to ensure that its key and value are not null and that the key matches the key in the
63 * map value. Each concept entry is then validated individually.
65 * @param <C> the concept being contained
69 @Table(name = "PfConceptContainer")
71 @EqualsAndHashCode(callSuper = false)
73 public class PfConceptContainer<C extends PfConcept, A extends PfNameVersion> extends PfConcept
74 implements PfConceptGetter<C>, PfAuthorative<List<Map<String, A>>> {
76 private static final long serialVersionUID = -324211738823208318L;
78 private static final String VALUE_FIELD = "value";
79 private static final Pattern KEY_ID_PATTERN = Pattern.compile(PfKey.KEY_ID_REGEXP);
84 private PfConceptKey key;
86 @ManyToMany(cascade = CascadeType.ALL)
90 @JoinColumn(name = "conceptContainerMapName", referencedColumnName = "name"),
91 @JoinColumn(name = "concpetContainerMapVersion", referencedColumnName = "version")
93 inverseJoinColumns = {
94 @JoinColumn(name = "conceptContainerName", referencedColumnName = "name"),
95 @JoinColumn(name = "conceptContainerVersion", referencedColumnName = "version")
99 private Map<PfConceptKey, C> conceptMap;
102 * The Default Constructor creates a {@link PfConceptContainer} object with a null artifact key and creates an empty
105 public PfConceptContainer() {
106 this(new PfConceptKey());
110 * The Key Constructor creates a {@link PfConceptContainer} object with the given artifact key and creates an empty
113 * @param key the concept key
115 public PfConceptContainer(@NonNull final PfConceptKey key) {
116 this(key, new TreeMap<>());
120 * This Constructor creates a concept container with all of its fields defined.
122 * @param key the concept container key
123 * @param conceptMap the concepts to be stored in the concept container
125 public PfConceptContainer(@NonNull final PfConceptKey key, @NonNull final Map<PfConceptKey, C> conceptMap) {
129 this.conceptMap = new TreeMap<>(conceptMap);
135 * @param copyConcept the concept to copy from
137 public PfConceptContainer(@NonNull final PfConceptContainer<C, A> copyConcept) {
139 this.key = new PfConceptKey(copyConcept.key);
141 this.conceptMap = new TreeMap<>();
142 for (final Entry<PfConceptKey, C> conceptMapEntry : copyConcept.conceptMap.entrySet()) {
143 var newK = new PfConceptKey(conceptMapEntry.getKey());
144 var newC = PfUtils.makeCopy(conceptMapEntry.getValue());
145 this.conceptMap.put(newK, newC);
150 public List<PfKey> getKeys() {
151 final List<PfKey> keyList = key.getKeys();
153 for (final C concept : conceptMap.values()) {
154 keyList.addAll(concept.getKeys());
161 public List<Map<String, A>> toAuthorative() {
162 // The returned list is a list of map singletons with one map for each map
163 // entry in the concept container
164 List<Map<String, A>> toscaConceptMapList = new ArrayList<>();
166 for (Entry<PfConceptKey, C> conceptEntry : getConceptMap().entrySet()) {
167 // Create a map to hold this entry
168 Map<String, A> toscaPolicyMap = new LinkedHashMap<>(1);
170 // Add the concept container entry to the singleton map
171 @SuppressWarnings("unchecked")
172 PfAuthorative<A> authoritiveImpl = (PfAuthorative<A>) conceptEntry.getValue();
173 toscaPolicyMap.put(conceptEntry.getKey().getName(), authoritiveImpl.toAuthorative());
175 // Add the map to the returned list
176 toscaConceptMapList.add(toscaPolicyMap);
179 return toscaConceptMapList;
183 public void fromAuthorative(List<Map<String, A>> authorativeList) {
184 // Clear any existing map entries
187 // Concepts are in lists of maps
188 for (Map<String, A> incomingConceptMap : authorativeList) {
189 // Add the map entries one by one
190 for (Entry<String, A> incomingConceptEntry : incomingConceptMap.entrySet()) {
192 var conceptKey = new PfConceptKey();
193 if (KEY_ID_PATTERN.matches(incomingConceptEntry.getKey())) {
194 conceptKey = new PfConceptKey(incomingConceptEntry.getKey());
196 conceptKey.setName(incomingConceptEntry.getKey());
197 if (incomingConceptEntry.getValue().getVersion() != null) {
198 conceptKey.setVersion(incomingConceptEntry.getValue().getVersion());
200 conceptKey.setVersion(PfKey.NULL_KEY_VERSION);
204 incomingConceptEntry.getValue().setName(findConceptField(conceptKey, conceptKey.getName(),
205 incomingConceptEntry.getValue(), PfNameVersion::getDefinedName));
206 incomingConceptEntry.getValue().setVersion(findConceptField(conceptKey, conceptKey.getVersion(),
207 incomingConceptEntry.getValue(), PfNameVersion::getDefinedVersion));
209 var jpaConcept = getConceptNewInstance();
210 // This cast allows us to call the fromAuthorative method
211 @SuppressWarnings("unchecked")
212 PfAuthorative<A> authoritiveImpl = (PfAuthorative<A>) jpaConcept;
214 // Set the key name and the rest of the values on the concept
215 authoritiveImpl.fromAuthorative(incomingConceptEntry.getValue());
217 // After all that, save the map entry
218 conceptMap.put(conceptKey, jpaConcept);
222 if (conceptMap.isEmpty()) {
223 throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
224 "An incoming list of concepts must have at least one entry");
229 * Get an authorative list of the concepts in this container.
231 * @return the authorative list of concepts
233 public List<A> toAuthorativeList() {
234 List<A> toscaConceptList = new ArrayList<>();
236 for (Map<String, A> toscaConceptMap : toAuthorative()) {
237 toscaConceptList.addAll(toscaConceptMap.values());
240 return toscaConceptList;
244 public void clean() {
246 for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
247 conceptEntry.getKey().clean();
248 conceptEntry.getValue().clean();
253 public BeanValidationResult validate(@NonNull String fieldName) {
254 BeanValidationResult result = new PfValidator().validateTop(fieldName, this);
255 result.addResult(validateConceptMap());
261 * Validate the concept map of the container.
263 * @return the validation result
265 private ValidationResult validateConceptMap() {
266 var result = new BeanValidationResult("conceptMap", conceptMap);
268 for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
269 BeanValidationResult result2 = null;
271 if (conceptEntry.getKey().equals(PfConceptKey.getNullKey())) {
272 addResult(result, "key on concept entry", conceptEntry.getKey(), IS_A_NULL_KEY);
273 } else if (conceptEntry.getValue() == null) {
274 result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
275 addResult(result2, VALUE_FIELD, conceptEntry.getValue(), IS_NULL);
276 } else if (!conceptEntry.getKey().equals(conceptEntry.getValue().getKey())) {
277 result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
278 addResult(result2, VALUE_FIELD, conceptEntry.getValue(), "does not equal concept key");
279 result2.addResult(conceptEntry.getValue().validate(VALUE_FIELD));
281 result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
282 result2.addResult(conceptEntry.getValue().validate(VALUE_FIELD));
285 result.addResult(result2);
287 return (result.isClean() ? null : result);
291 public int compareTo(@NonNull final PfConcept otherConcept) {
292 if (this == otherConcept) {
295 if (getClass() != otherConcept.getClass()) {
296 return getClass().getName().compareTo(otherConcept.getClass().getName());
299 @SuppressWarnings("unchecked") final PfConceptContainer<C, A> other = (PfConceptContainer<C, A>) otherConcept;
300 int retVal = key.compareTo(other.key);
305 return PfUtils.compareMaps(conceptMap, other.conceptMap);
309 * Get all the concepts that match the given name and version.
311 * @param conceptKeyName the name of the concept, if null, return all names
312 * @param conceptKeyVersion the version of the concept, if null, return all versions
313 * @return conceptKeyVersion
315 public Set<C> getAllNamesAndVersions(final String conceptKeyName, final String conceptKeyVersion) {
316 if (conceptKeyName == null || conceptKeyVersion == null || PfKey.NULL_KEY_VERSION.equals(conceptKeyVersion)) {
317 return getAll(conceptKeyName, conceptKeyVersion);
319 final Set<C> returnSet = new TreeSet<>();
320 var foundConcept = get(conceptKeyName, conceptKeyVersion);
321 if (foundConcept != null) {
322 returnSet.add(foundConcept);
329 public C get(final PfConceptKey conceptKey) {
330 if (conceptKey.isNullVersion()) {
331 return get(conceptKey.getName());
333 return new PfConceptGetterImpl<>(getNavigableConceptMap()).get(conceptKey);
338 public C get(final String conceptKeyName) {
339 return new PfConceptGetterImpl<>(getNavigableConceptMap()).get(conceptKeyName);
343 public C get(final String conceptKeyName, final String conceptKeyVersion) {
344 return new PfConceptGetterImpl<>(getNavigableConceptMap()).get(conceptKeyName, conceptKeyVersion);
348 public Set<C> getAll(final String conceptKeyName) {
349 return new PfConceptGetterImpl<>(getNavigableConceptMap()).getAll(conceptKeyName);
353 public Set<C> getAll(final String conceptKeyName, final String conceptKeyVersion) {
354 return new PfConceptGetterImpl<>(getNavigableConceptMap()).getAll(conceptKeyName, conceptKeyVersion);
358 * Get the concept map as a NavigableMap object.
360 * @return NavigableMap conceptMap instance.
362 private NavigableMap<PfConceptKey, C> getNavigableConceptMap() {
363 return new TreeMap<>(conceptMap);
367 * Get a new empty instance of a concept for this concept map.
369 * @return the new instance
371 @SuppressWarnings("unchecked")
372 private C getConceptNewInstance() {
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);
383 private String findConceptField(final PfConceptKey conceptKey, final String keyFieldValue,
384 final PfNameVersion concept,
385 final Function<PfNameVersion, String> fieldGetterFunction) {
387 String conceptField = fieldGetterFunction.apply(concept);
389 if (StringUtils.isBlank(conceptField) || keyFieldValue.equals(conceptField)) {
390 return keyFieldValue;
392 throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Key " + conceptKey.getId() + " field "
393 + keyFieldValue + " does not match the value " + conceptField + " in the concept field");