Remove inactive committers from INFO.yaml
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / service / ToscaServiceTemplateService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Bell Canada. All rights reserved.
4  *  Modifications Copyright (C) 2022 Nordix Foundation.
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.pap.main.service;
23
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30 import javax.ws.rs.core.Response;
31 import lombok.RequiredArgsConstructor;
32 import org.onap.policy.models.base.PfConceptKey;
33 import org.onap.policy.models.base.PfModelException;
34 import org.onap.policy.models.base.PfModelRuntimeException;
35 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
40 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
41 import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
42 import org.onap.policy.models.tosca.utils.ToscaUtils;
43 import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.stereotype.Service;
47 import org.springframework.transaction.annotation.Transactional;
48
49 @Service
50 @Transactional(readOnly = true)
51 @RequiredArgsConstructor
52 public class ToscaServiceTemplateService {
53
54     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaServiceTemplateService.class);
55
56     private static final String METADATASET_NAME = "metadataSetName";
57     private static final String METADATASET_VERSION = "metadataSetVersion";
58     private static final String METADATASET = "metadataSet";
59
60     private final ToscaServiceTemplateRepository serviceTemplateRepository;
61
62     private final ToscaNodeTemplateService nodeTemplateService;
63
64     /**
65      * Get policies.
66      *
67      * @param name the name of the policy to get, null to get all policies
68      * @param version the version of the policy to get, null to get all versions of a policy
69      * @return the policies found
70      * @throws PfModelException on errors getting policies
71      */
72     public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
73
74         LOGGER.debug("->getPolicyList: name={}, version={}", name, version);
75
76         List<ToscaPolicy> policyList;
77
78         try {
79             List<Map<String, ToscaPolicy>> policies = getToscaServiceTemplate(name, version, "policy").toAuthorative()
80                 .getToscaTopologyTemplate().getPolicies();
81             policyList = policies.stream().flatMap(policy -> policy.values().stream()).collect(Collectors.toList());
82             populateMetadataSet(policyList);
83         } catch (PfModelRuntimeException pfme) {
84             return handlePfModelRuntimeException(pfme);
85         } catch (Exception exc) {
86             String errorMsg = "Failed to fetch policy with name " + name + " and version " + version + ".";
87             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMsg, exc);
88         }
89
90         LOGGER.debug("<-getPolicyList: name={}, version={}, policyList={}", name, version, policyList);
91         return policyList;
92     }
93
94     /**
95      * Get filtered policies.
96      *
97      * @param filter the filter for the policies to get
98      * @return the policies found
99      * @throws PfModelException on errors getting policies
100      */
101     public List<ToscaPolicy> getFilteredPolicyList(ToscaTypedEntityFilter<ToscaPolicy> filter) throws PfModelException {
102         String version = ToscaTypedEntityFilter.LATEST_VERSION.equals(filter.getVersion()) ? null : filter.getVersion();
103         return filter.filter(getPolicyList(filter.getName(), version));
104     }
105
106     /**
107      * Get policy types.
108      *
109      * @param name the name of the policy type to get, set to null to get all policy types
110      * @param version the version of the policy type to get, set to null to get all versions
111      * @return the policy types found
112      * @throws PfModelException on errors getting policy types
113      */
114     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
115
116         LOGGER.debug("->getPolicyTypeList: name={}, version={}", name, version);
117
118         List<ToscaPolicyType> policyTypeList;
119
120         try {
121             policyTypeList = new ArrayList<>(
122                 getToscaServiceTemplate(name, version, "policyType").toAuthorative().getPolicyTypes().values());
123         } catch (PfModelRuntimeException pfme) {
124             return handlePfModelRuntimeException(pfme);
125         } catch (Exception exc) {
126             String errorMsg = "Failed to fetch policy type with name " + name + " and version " + version + ".";
127             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMsg, exc);
128         }
129
130         LOGGER.debug("<-getPolicyTypeList: name={}, version={}, policyTypeList={}", name, version, policyTypeList);
131         return policyTypeList;
132     }
133
134     private JpaToscaServiceTemplate getToscaServiceTemplate(final String name, final String version, final String type)
135         throws PfModelException {
136
137         Optional<JpaToscaServiceTemplate> serviceTemplate = serviceTemplateRepository
138             .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION));
139         if (serviceTemplate.isEmpty()) {
140             throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "service template not found in database");
141         }
142
143         LOGGER.debug("<-getServiceTemplate: serviceTemplate={}", serviceTemplate.get());
144         JpaToscaServiceTemplate dbServiceTemplate = serviceTemplate.get();
145
146         JpaToscaServiceTemplate returnServiceTemplate;
147         if (type.equals("policy")) {
148             returnServiceTemplate = getToscaPolicies(name, version, dbServiceTemplate);
149         } else {
150             returnServiceTemplate = getToscaPolicyTypes(name, version, dbServiceTemplate);
151         }
152         return returnServiceTemplate;
153     }
154
155     private JpaToscaServiceTemplate getToscaPolicies(final String name, final String version,
156         JpaToscaServiceTemplate dbServiceTemplate) throws PfModelException {
157         if (!ToscaUtils.doPoliciesExist(dbServiceTemplate)) {
158             throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
159                 "policies for " + name + ":" + version + " do not exist");
160         }
161
162         JpaToscaServiceTemplate returnServiceTemplate =
163             new SimpleToscaProvider().getCascadedPolicies(dbServiceTemplate, name, version);
164
165         LOGGER.debug("<-getPolicies: name={}, version={}, serviceTemplate={}", name, version, returnServiceTemplate);
166         return returnServiceTemplate;
167     }
168
169     private JpaToscaServiceTemplate getToscaPolicyTypes(final String name, final String version,
170         JpaToscaServiceTemplate dbServiceTemplate) throws PfModelException {
171         if (!ToscaUtils.doPolicyTypesExist(dbServiceTemplate)) {
172             throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
173                 "policy types for " + name + ":" + version + " do not exist");
174         }
175
176         JpaToscaServiceTemplate returnServiceTemplate =
177             new SimpleToscaProvider().getCascadedPolicyTypes(dbServiceTemplate, name, version);
178
179         LOGGER.debug("<-getPolicyTypes: name={}, version={}, serviceTemplate={}", name, version, returnServiceTemplate);
180         return returnServiceTemplate;
181     }
182
183     /**
184      * Handle a PfModelRuntimeException on a list call.
185      *
186      * @param pfme the model exception
187      * @return an empty list on 404
188      */
189     private <T extends ToscaEntity> List<T> handlePfModelRuntimeException(final PfModelRuntimeException pfme) {
190         if (Response.Status.NOT_FOUND.equals(pfme.getErrorResponse().getResponseCode())) {
191             LOGGER.trace("request did not find any results", pfme);
192             return Collections.emptyList();
193         } else {
194             throw pfme;
195         }
196     }
197
198     /**
199      * Populates metadataSet in policy->metadata if metadataSet reference is provided.
200      *
201      * @param policies List of policies
202      */
203     private void populateMetadataSet(List<ToscaPolicy> policies) {
204         for (ToscaPolicy policy : policies) {
205             if (policy.getMetadata().keySet().containsAll(List.of(METADATASET_NAME, METADATASET_VERSION))) {
206                 var name = String.valueOf(policy.getMetadata().get(METADATASET_NAME));
207                 var version = String.valueOf(policy.getMetadata().get(METADATASET_VERSION));
208                 policy.getMetadata().putIfAbsent(METADATASET,
209                     nodeTemplateService.getToscaNodeTemplate(name, version).getMetadata());
210             }
211         }
212     }
213
214 }