2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.clamp.controlloop.runtime.commissioning;
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.fasterxml.jackson.databind.PropertyNamingStrategies;
26 import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.stream.Collectors;
33 import javax.ws.rs.core.Response.Status;
34 import org.apache.commons.collections4.CollectionUtils;
35 import org.apache.commons.collections4.MapUtils;
36 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider;
37 import org.onap.policy.clamp.controlloop.models.messages.rest.commissioning.CommissioningResponse;
38 import org.onap.policy.models.base.PfModelException;
39 import org.onap.policy.models.provider.PolicyModelsProvider;
40 import org.onap.policy.models.tosca.authorative.concepts.ToscaCapabilityType;
41 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaRelationshipType;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplates;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
52 import org.springframework.stereotype.Component;
55 * This class provides the create, read and delete actions on Commissioning of Control Loop concepts in the database to
59 public class CommissioningProvider {
60 public static final String CONTROL_LOOP_NODE_TYPE = "org.onap.policy.clamp.controlloop.ControlLoop";
62 private final PolicyModelsProvider modelsProvider;
63 private final ControlLoopProvider clProvider;
64 private final ObjectMapper mapper = new ObjectMapper();
66 private static final Object lockit = new Object();
69 * Create a commissioning provider.
71 * @param modelsProvider the PolicyModelsProvider
72 * @param clProvider the ControlLoopProvider
74 public CommissioningProvider(PolicyModelsProvider modelsProvider, ControlLoopProvider clProvider) {
75 this.modelsProvider = modelsProvider;
76 this.clProvider = clProvider;
77 mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
81 * Create control loops from a service template.
83 * @param serviceTemplate the service template
84 * @return the result of the commissioning operation
85 * @throws PfModelException on creation errors
87 public CommissioningResponse createControlLoopDefinitions(ToscaServiceTemplate serviceTemplate)
88 throws PfModelException {
89 synchronized (lockit) {
90 modelsProvider.createServiceTemplate(serviceTemplate);
93 var response = new CommissioningResponse();
95 response.setAffectedControlLoopDefinitions(serviceTemplate.getToscaTopologyTemplate().getNodeTemplates()
98 .map(template -> template.getKey().asIdentifier())
99 .collect(Collectors.toList()));
106 * Delete the control loop definition with the given name and version.
108 * @param name the name of the control loop definition to delete
109 * @param version the version of the control loop to delete
110 * @return the result of the deletion
111 * @throws PfModelException on deletion errors
113 public CommissioningResponse deleteControlLoopDefinition(String name, String version) throws PfModelException {
114 synchronized (lockit) {
115 modelsProvider.deleteServiceTemplate(name, version);
118 var response = new CommissioningResponse();
119 response.setAffectedControlLoopDefinitions(
120 Collections.singletonList(new ToscaConceptIdentifier(name, version)));
126 * Get control loop node templates.
128 * @param clName the name of the control loop, null for all
129 * @param clVersion the version of the control loop, null for all
130 * @return list of control loop node templates
131 * @throws PfModelException on errors getting control loop definitions
133 public List<ToscaNodeTemplate> getControlLoopDefinitions(String clName, String clVersion) throws PfModelException {
136 ToscaTypedEntityFilter<ToscaNodeTemplate> nodeTemplateFilter = ToscaTypedEntityFilter
137 .<ToscaNodeTemplate>builder()
140 .type(CONTROL_LOOP_NODE_TYPE)
144 return clProvider.getFilteredNodeTemplates(nodeTemplateFilter);
148 * Get the control loop elements from a control loop node template.
150 * @param controlLoopNodeTemplate the control loop node template
151 * @return a list of the control loop element node templates in a control loop node template
152 * @throws PfModelException on errors get control loop element node templates
154 public List<ToscaNodeTemplate> getControlLoopElementDefinitions(ToscaNodeTemplate controlLoopNodeTemplate)
155 throws PfModelException {
156 if (!CONTROL_LOOP_NODE_TYPE.equals(controlLoopNodeTemplate.getType())) {
157 return Collections.emptyList();
160 if (MapUtils.isEmpty(controlLoopNodeTemplate.getProperties())) {
161 return Collections.emptyList();
164 @SuppressWarnings("unchecked")
165 List<Map<String, String>> controlLoopElements =
166 (List<Map<String, String>>) controlLoopNodeTemplate.getProperties().get("elements");
168 if (CollectionUtils.isEmpty(controlLoopElements)) {
169 return Collections.emptyList();
172 List<ToscaNodeTemplate> controlLoopElementList = new ArrayList<>();
174 controlLoopElementList.addAll(
177 .map(elementMap -> clProvider.getNodeTemplates(elementMap.get("name"),
178 elementMap.get("version")))
179 .flatMap(List::stream)
180 .collect(Collectors.toList())
184 return controlLoopElementList;
188 * Get the initial node types with common or instance properties.
190 * @param fullNodeTypes map of all the node types in the specified template
191 * @param common boolean to indicate whether common or instance properties are required
192 * @return node types map that only has common properties
193 * @throws PfModelException on errors getting node type with common properties
195 private Map<String, ToscaNodeType> getInitialNodeTypesMap(Map<String, ToscaNodeType> fullNodeTypes,
198 var tempNodeTypesMap = new HashMap<String, ToscaNodeType>();
200 fullNodeTypes.forEach((key, nodeType) -> {
201 var tempToscaNodeType = new ToscaNodeType();
202 tempToscaNodeType.setName(key);
204 var resultantPropertyMap = findCommonOrInstancePropsInNodeTypes(nodeType, common);
206 if (!resultantPropertyMap.isEmpty()) {
207 tempToscaNodeType.setProperties(resultantPropertyMap);
208 tempNodeTypesMap.put(key, tempToscaNodeType);
211 return tempNodeTypesMap;
214 private Map<String, ToscaProperty> findCommonOrInstancePropsInNodeTypes(ToscaNodeType nodeType, boolean common) {
216 var tempCommonPropertyMap = new HashMap<String, ToscaProperty>();
217 var tempInstancePropertyMap = new HashMap<String, ToscaProperty>();
219 nodeType.getProperties().forEach((propKey, prop) -> {
221 if (prop.getMetadata() != null) {
222 prop.getMetadata().forEach((k, v) -> {
223 if (k.equals("common") && v.equals("true") && common) {
224 tempCommonPropertyMap.put(propKey, prop);
225 } else if (k.equals("common") && v.equals("false") && !common) {
226 tempInstancePropertyMap.put(propKey, prop);
231 tempInstancePropertyMap.put(propKey, prop);
235 if (tempCommonPropertyMap.isEmpty() && !common) {
236 return tempInstancePropertyMap;
238 return tempCommonPropertyMap;
243 * Get the node types derived from those that have common properties.
245 * @param initialNodeTypes map of all the node types in the specified template
246 * @param filteredNodeTypes map of all the node types that have common or instance properties
247 * @return all node types that have common properties including their children
248 * @throws PfModelException on errors getting node type with common properties
250 private Map<String, ToscaNodeType> getFinalNodeTypesMap(Map<String, ToscaNodeType> initialNodeTypes,
251 Map<String, ToscaNodeType> filteredNodeTypes) {
252 for (var i = 0; i < initialNodeTypes.size(); i++) {
253 initialNodeTypes.forEach((key, nodeType) -> {
254 var tempToscaNodeType = new ToscaNodeType();
255 tempToscaNodeType.setName(key);
257 if (filteredNodeTypes.get(nodeType.getDerivedFrom()) != null) {
258 tempToscaNodeType.setName(key);
260 var finalProps = new HashMap<String, ToscaProperty>(
261 filteredNodeTypes.get(nodeType.getDerivedFrom()).getProperties());
263 tempToscaNodeType.setProperties(finalProps);
267 filteredNodeTypes.putIfAbsent(key, tempToscaNodeType);
271 return filteredNodeTypes;
275 * Get the requested node types with common or instance properties.
277 * @param common boolean indicating common or instance properties
278 * @param name the name of the definition to get, null for all definitions
279 * @param version the version of the definition to get, null for all definitions
280 * @return the node types with common or instance properties
281 * @throws PfModelException on errors getting node type properties
283 private Map<String, ToscaNodeType> getCommonOrInstancePropertiesFromNodeTypes(boolean common, String name,
284 String version) throws PfModelException {
285 var serviceTemplates = new ToscaServiceTemplates();
286 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
287 var tempNodeTypesMap =
288 this.getInitialNodeTypesMap(serviceTemplates.getServiceTemplates().get(0).getNodeTypes(), common);
290 return this.getFinalNodeTypesMap(serviceTemplates.getServiceTemplates().get(0).getNodeTypes(),
296 * Get node templates with appropriate common or instance properties added.
298 * @param initialNodeTemplates map of all the node templates in the specified template
299 * @param nodeTypeProps map of all the node types that have common or instance properties including children
300 * @return all node templates with appropriate common or instance properties added
301 * @throws PfModelException on errors getting map of node templates with common or instance properties added
303 private Map<String, ToscaNodeTemplate> getDerivedCommonOrInstanceNodeTemplates(
304 Map<String, ToscaNodeTemplate> initialNodeTemplates, Map<String, ToscaNodeType> nodeTypeProps) {
306 var finalNodeTemplatesMap = new HashMap<String, ToscaNodeTemplate>();
308 initialNodeTemplates.forEach((templateKey, template) -> {
309 if (nodeTypeProps.containsKey(template.getType())) {
310 var finalMergedProps = new HashMap<String, Object>();
312 nodeTypeProps.get(template.getType()).getProperties().forEach(finalMergedProps::putIfAbsent);
314 template.setProperties(finalMergedProps);
316 finalNodeTemplatesMap.put(templateKey, template);
321 return finalNodeTemplatesMap;
325 * Get node templates with common properties added.
327 * @param common boolean indicating common or instance properties to be used
328 * @param name the name of the definition to use, null for all definitions
329 * @param version the version of the definition to use, null for all definitions
330 * @return the nodes templates with common or instance properties
331 * @throws PfModelException on errors getting common or instance properties from node_templates
333 public Map<String, ToscaNodeTemplate> getNodeTemplatesWithCommonOrInstanceProperties(boolean common, String name,
334 String version) throws PfModelException {
336 var commonOrInstanceNodeTypeProps = this.getCommonOrInstancePropertiesFromNodeTypes(common, name, version);
338 var serviceTemplates = new ToscaServiceTemplates();
339 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
341 return this.getDerivedCommonOrInstanceNodeTemplates(
342 serviceTemplates.getServiceTemplates().get(0).getToscaTopologyTemplate().getNodeTemplates(),
343 commonOrInstanceNodeTypeProps);
347 * Get the requested control loop definitions.
349 * @param name the name of the definition to get, null for all definitions
350 * @param version the version of the definition to get, null for all definitions
351 * @return the control loop definitions
352 * @throws PfModelException on errors getting control loop definitions
354 public ToscaServiceTemplate getToscaServiceTemplate(String name, String version) throws PfModelException {
355 var serviceTemplates = new ToscaServiceTemplates();
356 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
357 return serviceTemplates.getServiceTemplates().get(0);
361 * Get the tosca service template with only required sections.
363 * @param name the name of the template to get, null for all definitions
364 * @param version the version of the template to get, null for all definitions
365 * @return the tosca service template
366 * @throws PfModelException on errors getting tosca service template
368 public String getToscaServiceTemplateReduced(String name, String version) throws PfModelException {
369 var serviceTemplates = new ToscaServiceTemplates();
370 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
372 ToscaServiceTemplate fullTemplate = serviceTemplates.getServiceTemplates().get(0);
374 var template = new HashMap<String, Object>();
375 template.put("tosca_definitions_version", fullTemplate.getToscaDefinitionsVersion());
376 template.put("data_types", fullTemplate.getDataTypes());
377 template.put("policy_types", fullTemplate.getPolicyTypes());
378 template.put("node_types", fullTemplate.getNodeTypes());
379 template.put("topology_template", fullTemplate.getToscaTopologyTemplate());
382 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(template);
384 } catch (JsonProcessingException e) {
385 throw new PfModelException(Status.BAD_REQUEST, "Converion to Json Schema failed", e);
390 * Get the requested json schema.
392 * @param section section of the tosca service template to get schema for
393 * @return the specified tosca service template or section Json Schema
394 * @throws PfModelException on errors with retrieving the classes
396 public String getToscaServiceTemplateSchema(String section) throws PfModelException {
397 var visitor = new SchemaFactoryWrapper();
402 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaDataType.class), visitor);
404 case "capability_types":
405 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaCapabilityType.class), visitor);
408 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaNodeType.class), visitor);
410 case "relationship_types":
411 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaRelationshipType.class), visitor);
414 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaPolicyType.class), visitor);
416 case "topology_template":
417 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaTopologyTemplate.class), visitor);
419 case "node_templates":
420 mapper.acceptJsonFormatVisitor(
421 mapper.getTypeFactory().constructCollectionType(List.class, ToscaNodeTemplate.class),
425 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaServiceTemplate.class), visitor);
428 var jsonSchema = visitor.finalSchema();
429 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
430 } catch (JsonProcessingException e) {
431 throw new PfModelException(Status.BAD_REQUEST, "Converion to Json Schema failed", e);