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