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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.main.service;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
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;
50 @Transactional(readOnly = true)
51 @RequiredArgsConstructor
52 public class ToscaServiceTemplateService {
54 private static final Logger LOGGER = LoggerFactory.getLogger(ToscaServiceTemplateService.class);
56 private static final String METADATASET_NAME = "metadataSetName";
57 private static final String METADATASET_VERSION = "metadataSetVersion";
58 private static final String METADATASET = "metadataSet";
60 private final ToscaServiceTemplateRepository serviceTemplateRepository;
62 private final ToscaNodeTemplateService nodeTemplateService;
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
72 public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
74 LOGGER.debug("->getPolicyList: name={}, version={}", name, version);
76 List<ToscaPolicy> policyList;
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);
90 LOGGER.debug("<-getPolicyList: name={}, version={}, policyList={}", name, version, policyList);
95 * Get filtered policies.
97 * @param filter the filter for the policies to get
98 * @return the policies found
99 * @throws PfModelException on errors getting policies
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));
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
114 public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
116 LOGGER.debug("->getPolicyTypeList: name={}, version={}", name, version);
118 List<ToscaPolicyType> policyTypeList;
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);
130 LOGGER.debug("<-getPolicyTypeList: name={}, version={}, policyTypeList={}", name, version, policyTypeList);
131 return policyTypeList;
134 private JpaToscaServiceTemplate getToscaServiceTemplate(final String name, final String version, final String type)
135 throws PfModelException {
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");
143 LOGGER.debug("<-getServiceTemplate: serviceTemplate={}", serviceTemplate.get());
144 JpaToscaServiceTemplate dbServiceTemplate = serviceTemplate.get();
146 JpaToscaServiceTemplate returnServiceTemplate;
147 if (type.equals("policy")) {
148 returnServiceTemplate = getToscaPolicies(name, version, dbServiceTemplate);
150 returnServiceTemplate = getToscaPolicyTypes(name, version, dbServiceTemplate);
152 return returnServiceTemplate;
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");
162 JpaToscaServiceTemplate returnServiceTemplate =
163 new SimpleToscaProvider().getCascadedPolicies(dbServiceTemplate, name, version);
165 LOGGER.debug("<-getPolicies: name={}, version={}, serviceTemplate={}", name, version, returnServiceTemplate);
166 return returnServiceTemplate;
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");
176 JpaToscaServiceTemplate returnServiceTemplate =
177 new SimpleToscaProvider().getCascadedPolicyTypes(dbServiceTemplate, name, version);
179 LOGGER.debug("<-getPolicyTypes: name={}, version={}, serviceTemplate={}", name, version, returnServiceTemplate);
180 return returnServiceTemplate;
184 * Handle a PfModelRuntimeException on a list call.
186 * @param pfme the model exception
187 * @return an empty list on 404
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();
199 * Populates metadataSet in policy->metadata if metadataSet reference is provided.
201 * @param policies List of policies
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());