6e4321e3a866592c687c7e83820589477e99f570
[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 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 org.onap.policy.api.main.exception.PolicyApiException;
28 import org.onap.policy.common.utils.coder.CoderException;
29 import org.onap.policy.common.utils.coder.StandardCoder;
30 import org.onap.policy.common.utils.resources.ResourceUtils;
31 import org.onap.policy.models.base.PfModelException;
32 import org.onap.policy.models.provider.PolicyModelsProvider;
33 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
34 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
35 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.yaml.snakeyaml.Yaml;
40
41 /**
42  * This class creates initial policy types in the database.
43  *
44  * @author Chenfei Gao (cgao@research.att.com)
45  */
46 public class ApiDatabaseInitializer {
47
48     private static final Logger LOGGER = LoggerFactory.getLogger(ApiDatabaseInitializer.class);
49
50     private StandardCoder standardCoder;
51     private PolicyModelsProviderFactory factory;
52
53     // @formatter:off
54     private static final String[] PRELOAD_POLICYTYPES = {
55         "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml",
56         "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
57         "policytypes/onap.policies.optimization.AffinityPolicy.yaml",
58         "policytypes/onap.policies.optimization.DistancePolicy.yaml",
59         "policytypes/onap.policies.optimization.HpaPolicy.yaml",
60         "policytypes/onap.policies.optimization.OptimizationPolicy.yaml",
61         "policytypes/onap.policies.optimization.PciPolicy.yaml",
62         "policytypes/onap.policies.optimization.QueryPolicy.yaml",
63         "policytypes/onap.policies.optimization.SubscriberPolicy.yaml",
64         "policytypes/onap.policies.optimization.Vim_fit.yaml",
65         "policytypes/onap.policies.optimization.VnfPolicy.yaml",
66         "policytypes/onap.policies.controlloop.guard.Blacklist.yaml",
67         "policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml",
68         "policytypes/onap.policies.controlloop.guard.MinMax.yaml",
69         "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
70         "policytypes/onap.policies.controlloop.Operational.yaml"
71     };
72     // @formatter:on
73
74     /**
75      * Constructs the object.
76      */
77     public ApiDatabaseInitializer() {
78         factory = new PolicyModelsProviderFactory();
79         standardCoder = new StandardCoder();
80     }
81
82     /**
83      * Initializes database by preloading policy types.
84      *
85      * @param policyModelsProviderParameters the database parameters
86      * @throws PolicyApiException in case of errors.
87      */
88     public void initializeApiDatabase(final PolicyModelsProviderParameters policyModelsProviderParameters)
89             throws PolicyApiException {
90
91         try (PolicyModelsProvider databaseProvider =
92                 factory.createPolicyModelsProvider(policyModelsProviderParameters)) {
93             ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
94             serviceTemplate.setPolicyTypes(new LinkedHashMap<String, ToscaPolicyType>());
95             serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_0_0");
96             for (String pt : PRELOAD_POLICYTYPES) {
97                 String policyTypeAsStringYaml = ResourceUtils.getResourceAsString(pt);
98                 if (policyTypeAsStringYaml == null) {
99                     throw new PolicyApiException("Preloading policy type cannot be found: " + pt);
100                 }
101
102                 Object yamlObject = new Yaml().load(policyTypeAsStringYaml);
103                 String policyTypeAsString = new StandardCoder().encode(yamlObject);
104
105                 ToscaServiceTemplate singlePolicyType =
106                         standardCoder.decode(policyTypeAsString, ToscaServiceTemplate.class);
107                 if (singlePolicyType == null) {
108                     throw new PolicyApiException("Error deserializing policy type from file: " + pt);
109                 }
110                 // Consolidate policy types
111                 serviceTemplate.getPolicyTypes().putAll(singlePolicyType.getPolicyTypes());
112             }
113             ToscaServiceTemplate createdPolicyTypes = databaseProvider.createPolicyTypes(serviceTemplate);
114             if (createdPolicyTypes == null) {
115                 throw new PolicyApiException("Error preloading policy types: " + serviceTemplate);
116             } else {
117                 LOGGER.debug("Created initial policy types in DB - {}", createdPolicyTypes);
118             }
119         } catch (final PfModelException | CoderException exp) {
120             throw new PolicyApiException(exp);
121         }
122     }
123 }