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