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