6b3749fc5a4c2c404a37f0ebeed545e79f2e8c5b
[policy/clamp.git] /
1 /*-
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
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.clamp.controlloop.models.controlloop.persistence.provider;
22
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.core.Response.Status;
28 import lombok.RequiredArgsConstructor;
29 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaServiceTemplateRepository;
30 import org.onap.policy.models.base.PfConceptKey;
31 import org.onap.policy.models.base.PfModelException;
32 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
33 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType;
34 import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
35 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
36 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
37 import org.springframework.stereotype.Component;
38 import org.springframework.transaction.annotation.Transactional;
39
40 @Component
41 @RequiredArgsConstructor
42 @Transactional
43 public class ServiceTemplateProvider {
44
45     private final ToscaServiceTemplateRepository serviceTemplateRepository;
46
47     /**
48      * Create service template.
49      *
50      * @param serviceTemplate the service template to be created
51      * @return the created service template
52      * @throws PfModelException on errors creating the service template
53      */
54     public ToscaServiceTemplate createServiceTemplate(final ToscaServiceTemplate serviceTemplate)
55             throws PfModelException {
56         try {
57             var result = serviceTemplateRepository.save(ProviderUtils.getJpaAndValidate(serviceTemplate,
58                     JpaToscaServiceTemplate::new, "toscaServiceTemplate"));
59             return result.toAuthorative();
60         } catch (IllegalArgumentException e) {
61             throw new PfModelException(Status.BAD_REQUEST, "Error in save serviceTemplate", e);
62         }
63     }
64
65     /**
66      * Delete service template.
67      *
68      * @param name the name of the service template to delete.
69      * @param version the version of the service template to delete.
70      * @return the TOSCA service template that was deleted
71      * @throws PfModelException on errors deleting policy types
72      */
73     public ToscaServiceTemplate deleteServiceTemplate(final String name, final String version) throws PfModelException {
74         var serviceTemplateKey = new PfConceptKey(name, version);
75         var jpaDelete = serviceTemplateRepository.findById(serviceTemplateKey);
76         if (jpaDelete.isEmpty()) {
77             String errorMessage = "delete of serviceTemplate \"" + serviceTemplateKey.getId()
78                     + "\" failed, serviceTemplate does not exist";
79             throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage);
80         }
81         serviceTemplateRepository.deleteById(serviceTemplateKey);
82         return jpaDelete.get().toAuthorative();
83     }
84
85     /**
86      * Get the requested control loop definitions.
87      *
88      * @param name the name of the definition to get, null for all definitions
89      * @param version the version of the definition to get, null for all definitions
90      * @return the control loop definitions
91      * @throws PfModelException on errors getting control loop definitions
92      */
93     @Transactional(readOnly = true)
94     public ToscaServiceTemplate getToscaServiceTemplate(String name, String version) throws PfModelException {
95         var serviceTemplateKey = new PfConceptKey(name, version);
96         var jpaServiceTemplates = serviceTemplateRepository.findById(serviceTemplateKey);
97         if (jpaServiceTemplates.isEmpty()) {
98             throw new PfModelException(Status.NOT_FOUND, "Control Loop definitions not found");
99         }
100         return jpaServiceTemplates.get().toAuthorative();
101     }
102
103     /**
104      * Get service templates.
105      *
106      * @return the topology templates found
107      * @throws PfModelException on errors getting service templates
108      */
109     @Transactional(readOnly = true)
110     public List<ToscaServiceTemplate> getAllServiceTemplates() throws PfModelException {
111         var jpaList = serviceTemplateRepository.findAll();
112         return ProviderUtils.asEntityList(jpaList);
113     }
114
115     /**
116      * Get service templates.
117      *
118      * @param name the name of the topology template to get, set to null to get all service templates
119      * @param version the version of the service template to get, set to null to get all service templates
120      * @return the topology templates found
121      * @throws PfModelException on errors getting service templates
122      */
123     @Transactional(readOnly = true)
124     public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version)
125             throws PfModelException {
126         var jpaList = serviceTemplateRepository.getFiltered(JpaToscaServiceTemplate.class, name, version);
127         return ProviderUtils.asEntityList(jpaList);
128     }
129
130     /**
131      * Get the initial node types with common or instance properties.
132      *
133      * @param fullNodeTypes map of all the node types in the specified template
134      * @param common boolean to indicate whether common or instance properties are required
135      * @return node types map that only has common properties
136      * @throws PfModelException on errors getting node type with common properties
137      */
138     private Map<String, ToscaNodeType> getInitialNodeTypesMap(Map<String, ToscaNodeType> fullNodeTypes,
139             boolean common) {
140
141         var tempNodeTypesMap = new HashMap<String, ToscaNodeType>();
142
143         fullNodeTypes.forEach((key, nodeType) -> {
144             var tempToscaNodeType = new ToscaNodeType();
145             tempToscaNodeType.setName(key);
146
147             var resultantPropertyMap = findCommonOrInstancePropsInNodeTypes(nodeType, common);
148
149             if (!resultantPropertyMap.isEmpty()) {
150                 tempToscaNodeType.setProperties(resultantPropertyMap);
151                 tempNodeTypesMap.put(key, tempToscaNodeType);
152             }
153         });
154         return tempNodeTypesMap;
155     }
156
157     private Map<String, ToscaProperty> findCommonOrInstancePropsInNodeTypes(ToscaNodeType nodeType, boolean common) {
158
159         var tempCommonPropertyMap = new HashMap<String, ToscaProperty>();
160         var tempInstancePropertyMap = new HashMap<String, ToscaProperty>();
161
162         nodeType.getProperties().forEach((propKey, prop) -> {
163
164             if (prop.getMetadata() != null) {
165                 prop.getMetadata().forEach((k, v) -> {
166                     if (k.equals("common") && v.equals("true") && common) {
167                         tempCommonPropertyMap.put(propKey, prop);
168                     } else if (k.equals("common") && v.equals("false") && !common) {
169                         tempInstancePropertyMap.put(propKey, prop);
170                     }
171
172                 });
173             } else {
174                 tempInstancePropertyMap.put(propKey, prop);
175             }
176         });
177
178         if (tempCommonPropertyMap.isEmpty() && !common) {
179             return tempInstancePropertyMap;
180         } else {
181             return tempCommonPropertyMap;
182         }
183     }
184
185     /**
186      * Get the node types derived from those that have common properties.
187      *
188      * @param initialNodeTypes map of all the node types in the specified template
189      * @param filteredNodeTypes map of all the node types that have common or instance properties
190      * @return all node types that have common properties including their children
191      * @throws PfModelException on errors getting node type with common properties
192      */
193     private Map<String, ToscaNodeType> getFinalNodeTypesMap(Map<String, ToscaNodeType> initialNodeTypes,
194             Map<String, ToscaNodeType> filteredNodeTypes) {
195         for (var i = 0; i < initialNodeTypes.size(); i++) {
196             initialNodeTypes.forEach((key, nodeType) -> {
197                 var tempToscaNodeType = new ToscaNodeType();
198                 tempToscaNodeType.setName(key);
199
200                 if (filteredNodeTypes.get(nodeType.getDerivedFrom()) != null) {
201                     tempToscaNodeType.setName(key);
202
203                     var finalProps = new HashMap<String, ToscaProperty>(
204                             filteredNodeTypes.get(nodeType.getDerivedFrom()).getProperties());
205
206                     tempToscaNodeType.setProperties(finalProps);
207                 } else {
208                     return;
209                 }
210                 filteredNodeTypes.putIfAbsent(key, tempToscaNodeType);
211
212             });
213         }
214         return filteredNodeTypes;
215     }
216
217     /**
218      * Get the requested node types with common or instance properties.
219      *
220      * @param common boolean indicating common or instance properties
221      * @param serviceTemplate the ToscaServiceTemplate
222      * @return the node types with common or instance properties
223      * @throws PfModelException on errors getting node type properties
224      */
225     public Map<String, ToscaNodeType> getCommonOrInstancePropertiesFromNodeTypes(boolean common,
226             ToscaServiceTemplate serviceTemplate) throws PfModelException {
227         var tempNodeTypesMap = this.getInitialNodeTypesMap(serviceTemplate.getNodeTypes(), common);
228
229         return this.getFinalNodeTypesMap(serviceTemplate.getNodeTypes(), tempNodeTypesMap);
230
231     }
232
233     /**
234      * Get node templates with appropriate common or instance properties added.
235      *
236      * @param initialNodeTemplates map of all the node templates in the specified template
237      * @param nodeTypeProps map of all the node types that have common or instance properties including children
238      * @return all node templates with appropriate common or instance properties added
239      * @throws PfModelException on errors getting map of node templates with common or instance properties added
240      */
241     public Map<String, ToscaNodeTemplate> getDerivedCommonOrInstanceNodeTemplates(
242             Map<String, ToscaNodeTemplate> initialNodeTemplates, Map<String, ToscaNodeType> nodeTypeProps) {
243
244         var finalNodeTemplatesMap = new HashMap<String, ToscaNodeTemplate>();
245
246         initialNodeTemplates.forEach((templateKey, template) -> {
247             if (nodeTypeProps.containsKey(template.getType())) {
248                 var finalMergedProps = new HashMap<String, Object>();
249
250                 nodeTypeProps.get(template.getType()).getProperties().forEach(finalMergedProps::putIfAbsent);
251
252                 template.setProperties(finalMergedProps);
253
254                 finalNodeTemplatesMap.put(templateKey, template);
255             } else {
256                 return;
257             }
258         });
259         return finalNodeTemplatesMap;
260     }
261 }