Merge "Fix sonars in policy models"
[policy/models.git] / models-tosca / src / main / java / org / onap / policy / models / tosca / utils / ToscaUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2021 Nordix Foundation.
4  *  Modifications Copyright (C) 2020-2021 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.tosca.utils;
23
24 import java.util.Collection;
25 import java.util.HashSet;
26 import java.util.Set;
27 import java.util.function.Function;
28 import javax.ws.rs.core.Response;
29 import lombok.NonNull;
30 import org.apache.commons.collections4.CollectionUtils;
31 import org.onap.policy.common.parameters.BeanValidationResult;
32 import org.onap.policy.common.parameters.ValidationStatus;
33 import org.onap.policy.models.base.PfConcept;
34 import org.onap.policy.models.base.PfConceptContainer;
35 import org.onap.policy.models.base.PfConceptKey;
36 import org.onap.policy.models.base.PfKey;
37 import org.onap.policy.models.base.PfModelRuntimeException;
38 import org.onap.policy.models.base.PfNameVersion;
39 import org.onap.policy.models.base.Validated;
40 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
41 import org.onap.policy.models.tosca.simple.concepts.JpaToscaEntityType;
42 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
43
44 /**
45  * Utility class for TOSCA concepts.
46  *
47  * @author Liam Fallon (liam.fallon@est.tech)
48  */
49 public final class ToscaUtils {
50     private static final String ROOT_KEY_NAME_SUFFIX = ".Root";
51
52     // @formatter:off
53     private static final Set<PfConceptKey> PREDEFINED_TOSCA_DATA_TYPES = Set.of(
54             new PfConceptKey("string",                       PfKey.NULL_KEY_VERSION),
55             new PfConceptKey("integer",                      PfKey.NULL_KEY_VERSION),
56             new PfConceptKey("float",                        PfKey.NULL_KEY_VERSION),
57             new PfConceptKey("boolean",                      PfKey.NULL_KEY_VERSION),
58             new PfConceptKey("timestamp",                    PfKey.NULL_KEY_VERSION),
59             new PfConceptKey("null",                         PfKey.NULL_KEY_VERSION),
60             new PfConceptKey("list",                         PfKey.NULL_KEY_VERSION),
61             new PfConceptKey("map",                          PfKey.NULL_KEY_VERSION),
62             new PfConceptKey("object",                       PfKey.NULL_KEY_VERSION),
63             new PfConceptKey("scalar-unit.size",             PfKey.NULL_KEY_VERSION),
64             new PfConceptKey("scalar-unit.time",             PfKey.NULL_KEY_VERSION),
65             new PfConceptKey("scalar-unit.frequency",        PfKey.NULL_KEY_VERSION),
66             new PfConceptKey("tosca.datatypes.TimeInterval", PfKey.NULL_KEY_VERSION)
67         );
68     // @formatter:on
69
70     /**
71      * Private constructor to prevent subclassing.
72      */
73     private ToscaUtils() {
74         // Private constructor to prevent subclassing
75     }
76
77     /**
78      * Get the predefined policy types.
79      *
80      * @return the predefined policy types
81      */
82     public static Collection<PfConceptKey> getPredefinedDataTypes() {
83         return PREDEFINED_TOSCA_DATA_TYPES;
84     }
85
86     /**
87      * Assert that data types have been specified correctly.
88      *
89      * @param serviceTemplate the service template containing data types to be checked
90      */
91     public static void assertDataTypesExist(final JpaToscaServiceTemplate serviceTemplate) {
92         assertExist(serviceTemplate, ToscaUtils::checkDataTypesExist);
93     }
94
95     /**
96      * Assert that policy types have been specified correctly.
97      *
98      * @param serviceTemplate the service template containing policy types to be checked
99      */
100     public static void assertPolicyTypesExist(final JpaToscaServiceTemplate serviceTemplate) {
101         assertExist(serviceTemplate, ToscaUtils::checkPolicyTypesExist);
102     }
103
104     /**
105      * Assert that policies have been specified correctly.
106      *
107      * @param serviceTemplate the service template containing policy types to be checked
108      */
109     public static void assertPoliciesExist(final JpaToscaServiceTemplate serviceTemplate) {
110         assertExist(serviceTemplate, ToscaUtils::checkPoliciesExist);
111     }
112
113     /**
114      * Check that data types have been specified correctly.
115      *
116      * @param serviceTemplate the service template containing data types to be checked
117      */
118     public static boolean doDataTypesExist(final JpaToscaServiceTemplate serviceTemplate) {
119         return doExist(serviceTemplate, ToscaUtils::checkDataTypesExist);
120     }
121
122     /**
123      * Check that policy types have been specified correctly.
124      *
125      * @param serviceTemplate the service template containing policy types to be checked
126      */
127     public static boolean doPolicyTypesExist(final JpaToscaServiceTemplate serviceTemplate) {
128         return doExist(serviceTemplate, ToscaUtils::checkPolicyTypesExist);
129     }
130
131     /**
132      * Check that policies have been specified correctly.
133      *
134      * @param serviceTemplate the service template containing policy types to be checked
135      */
136     public static boolean doPoliciesExist(final JpaToscaServiceTemplate serviceTemplate) {
137
138         return doExist(serviceTemplate, ToscaUtils::checkPoliciesExist);
139     }
140
141     /**
142      * Assert that something have been specified correctly.
143      *
144      * @param serviceTemplate the service template containing policy types to be checked
145      */
146     public static void assertExist(final JpaToscaServiceTemplate serviceTemplate,
147             final Function<JpaToscaServiceTemplate, String> checkerFunction) {
148         String message = checkerFunction.apply(serviceTemplate);
149         if (message != null) {
150             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, message);
151         }
152     }
153
154     /**
155      * Check that something have been specified correctly.
156      *
157      * @param serviceTemplate the service template containing policy types to be checked
158      */
159     public static boolean doExist(final JpaToscaServiceTemplate serviceTemplate,
160             final Function<JpaToscaServiceTemplate, String> checkerFunction) {
161         return checkerFunction.apply(serviceTemplate) == null;
162     }
163
164     /**
165      * Check if data types have been specified correctly.
166      */
167     public static String checkDataTypesExist(final JpaToscaServiceTemplate serviceTemplate) {
168         if (serviceTemplate.getDataTypes() == null) {
169             return "no data types specified on service template";
170         }
171
172         if (serviceTemplate.getDataTypes().getConceptMap().isEmpty()) {
173             return "list of data types specified on service template is empty";
174         }
175
176         return null;
177     }
178
179     /**
180      * Check if policy types have been specified correctly.
181      */
182     public static String checkPolicyTypesExist(final JpaToscaServiceTemplate serviceTemplate) {
183         if (serviceTemplate.getPolicyTypes() == null) {
184             return "no policy types specified on service template";
185         }
186
187         if (serviceTemplate.getPolicyTypes().getConceptMap().isEmpty()) {
188             return "list of policy types specified on service template is empty";
189         }
190
191         return null;
192     }
193
194     /**
195      * Check if policies have been specified correctly.
196      */
197     public static String checkPoliciesExist(final JpaToscaServiceTemplate serviceTemplate) {
198         if (serviceTemplate.getTopologyTemplate() == null) {
199             return "topology template not specified on service template";
200         }
201
202         if (serviceTemplate.getTopologyTemplate().getPolicies() == null) {
203             return "no policies specified on topology template of service template";
204         }
205
206         if (serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().isEmpty()) {
207             return "list of policies specified on topology template of service template is empty";
208         }
209
210         return null;
211     }
212
213     /**
214      * getLatestPolicyTypeVersion Find all the ancestors of an entity type.
215      *
216      * @param entityTypes the set of entity types that exist
217      * @param entityType the entity type for which to get the parents
218      * @param result the result of the ancestor search with any warnings or errors
219      * @return the entity set containing the ancestors of the incoming entity
220      */
221     public static Collection<JpaToscaEntityType<ToscaEntity>> getEntityTypeAncestors(
222             @NonNull PfConceptContainer<? extends PfConcept, ? extends PfNameVersion> entityTypes,
223             @NonNull JpaToscaEntityType<?> entityType, @NonNull final BeanValidationResult result) {
224
225         PfConceptKey parentEntityTypeKey = entityType.getDerivedFrom();
226         if (parentEntityTypeKey == null || parentEntityTypeKey.getName().endsWith(ROOT_KEY_NAME_SUFFIX)) {
227             return CollectionUtils.emptyCollection();
228         }
229
230         if (entityType.getKey().equals(parentEntityTypeKey)) {
231             result.addResult("entity type", entityType.getKey().getId(),
232                             ValidationStatus.INVALID, "ancestor of itself");
233             throw new PfModelRuntimeException(Response.Status.CONFLICT, result.getResult());
234         }
235
236         @SuppressWarnings("unchecked")
237         Set<JpaToscaEntityType<ToscaEntity>> ancestorEntitySet = (Set<JpaToscaEntityType<ToscaEntity>>) entityTypes
238                 .getAll(parentEntityTypeKey.getName(), parentEntityTypeKey.getVersion());
239         Set<JpaToscaEntityType<ToscaEntity>> ancestorEntitySetToReturn = new HashSet<>(ancestorEntitySet);
240         if (ancestorEntitySet.isEmpty()) {
241             result.addResult("parent", parentEntityTypeKey.getId(), ValidationStatus.INVALID, Validated.NOT_FOUND);
242         } else {
243             for (JpaToscaEntityType<?> filteredEntityType : ancestorEntitySet) {
244                 ancestorEntitySetToReturn.addAll(getEntityTypeAncestors(entityTypes, filteredEntityType, result));
245             }
246         }
247         return ancestorEntitySetToReturn;
248     }
249
250     /**
251      * Get the entity tree from a concept container for a given entity key.
252      *
253      * @param entityTypes the concept container containing entity types
254      * @param entityName the name of the entity
255      * @param entityVersion the version of the entity
256      */
257     public static void getEntityTree(
258             @NonNull final PfConceptContainer<? extends PfConcept, ? extends PfNameVersion> entityTypes,
259             final String entityName, final String entityVersion) {
260
261         var result = new BeanValidationResult("entity", entityName);
262
263         @SuppressWarnings("unchecked")
264         Set<JpaToscaEntityType<?>> filteredEntitySet =
265                 (Set<JpaToscaEntityType<?>>) entityTypes.getAllNamesAndVersions(entityName, entityVersion);
266         Set<JpaToscaEntityType<?>> filteredEntitySetToReturn = new HashSet<>(filteredEntitySet);
267         for (JpaToscaEntityType<?> filteredEntityType : filteredEntitySet) {
268             filteredEntitySetToReturn
269                     .addAll(ToscaUtils.getEntityTypeAncestors(entityTypes, filteredEntityType, result));
270         }
271
272         if (!result.isValid()) {
273             throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, result.getResult());
274         }
275
276         entityTypes.getConceptMap().entrySet()
277                 .removeIf(entityEntry -> !filteredEntitySetToReturn.contains(entityEntry.getValue()));
278     }
279 }