Removing legacy guard from policy/api
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / startstop / ApiDatabaseInitializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy API
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.api.main.startstop;
25
26 import java.util.LinkedHashMap;
27 import java.util.LinkedList;
28 import java.util.List;
29 import org.onap.policy.api.main.exception.PolicyApiException;
30 import org.onap.policy.api.main.parameters.ApiParameterGroup;
31 import org.onap.policy.common.utils.coder.CoderException;
32 import org.onap.policy.common.utils.coder.StandardYamlCoder;
33 import org.onap.policy.common.utils.resources.ResourceUtils;
34 import org.onap.policy.models.base.PfModelException;
35 import org.onap.policy.models.provider.PolicyModelsProvider;
36 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
40 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * This class creates initial policy types in the database.
46  *
47  * @author Chenfei Gao (cgao@research.att.com)
48  */
49 public class ApiDatabaseInitializer {
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(ApiDatabaseInitializer.class);
52
53     private static final StandardYamlCoder coder = new StandardYamlCoder();
54     private PolicyModelsProviderFactory factory;
55
56     /**
57      * Constructs the object.
58      */
59     public ApiDatabaseInitializer() {
60         factory = new PolicyModelsProviderFactory();
61     }
62
63     /**
64      * Initializes database by preloading policy types and policies.
65      *
66      * @param apiParameterGroup the apiParameterGroup parameters
67      * @throws PolicyApiException in case of errors.
68      */
69     public void initializeApiDatabase(final ApiParameterGroup apiParameterGroup) throws PolicyApiException {
70
71         try (PolicyModelsProvider databaseProvider =
72                 factory.createPolicyModelsProvider(apiParameterGroup.getDatabaseProviderParameters())) {
73             ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
74             serviceTemplate.setDataTypes(new LinkedHashMap<String, ToscaDataType>());
75             serviceTemplate.setPolicyTypes(new LinkedHashMap<String, ToscaPolicyType>());
76             serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_1_0");
77
78             ToscaServiceTemplate createdPolicyTypes = preloadServiceTemplate(serviceTemplate,
79                     apiParameterGroup.getPreloadPolicyTypes(), databaseProvider::createPolicyTypes);
80             preloadServiceTemplate(createdPolicyTypes,
81                     apiParameterGroup.getPreloadPolicies(), databaseProvider::createPolicies);
82         } catch (final PolicyApiException | PfModelException | CoderException exp) {
83             throw new PolicyApiException(exp);
84         }
85     }
86
87     private ToscaServiceTemplate preloadServiceTemplate(ToscaServiceTemplate serviceTemplate,
88             List<String> entities, FunctionWithEx<ToscaServiceTemplate, ToscaServiceTemplate> getter)
89                     throws PolicyApiException, CoderException, PfModelException {
90
91         for (String entity : entities) {
92             String entityAsStringYaml = ResourceUtils.getResourceAsString(entity);
93             if (entityAsStringYaml == null) {
94                 throw new PolicyApiException("Preloading entity cannot be found: " + entity);
95             }
96
97             ToscaServiceTemplate singleEntity =
98                     coder.decode(entityAsStringYaml,  ToscaServiceTemplate.class);
99             if (singleEntity == null) {
100                 throw new PolicyApiException("Error deserializaing entity from file: " + entity);
101             }
102
103             // Consolidate data types and policy types
104             if (singleEntity.getDataTypes() != null) {
105                 serviceTemplate.getDataTypes().putAll(singleEntity.getDataTypes());
106             }
107             if (singleEntity.getPolicyTypes() != null) {
108                 serviceTemplate.getPolicyTypes().putAll(singleEntity.getPolicyTypes());
109             }
110
111             // Consolidate policies
112             ToscaTopologyTemplate topologyTemplate = singleEntity.getToscaTopologyTemplate();
113             if (topologyTemplate != null && topologyTemplate.getPolicies() != null) {
114                 serviceTemplate.setToscaTopologyTemplate(new ToscaTopologyTemplate());
115                 serviceTemplate.getToscaTopologyTemplate().setPolicies(new LinkedList<>());
116                 serviceTemplate.getToscaTopologyTemplate().getPolicies()
117                     .addAll(singleEntity.getToscaTopologyTemplate().getPolicies());
118             }
119         }
120         // Preload the specified entities
121         ToscaServiceTemplate createdServiceTemplate = getter.apply(serviceTemplate);
122         LOGGER.debug("Created initial tosca service template in DB - {}", createdServiceTemplate);
123         return createdServiceTemplate;
124     }
125
126     @FunctionalInterface
127     protected interface FunctionWithEx<T, R> {
128         public R apply(T value) throws PfModelException;
129     }
130 }