Migrate pap startup & controllers to spring boot
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / startstop / PapDatabaseInitializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property.
5  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.startstop;
24
25 import java.util.List;
26 import javax.annotation.PostConstruct;
27 import org.onap.policy.common.parameters.ValidationResult;
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.pdp.concepts.PdpGroup;
33 import org.onap.policy.models.pdp.concepts.PdpGroups;
34 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
35 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
36 import org.onap.policy.pap.main.PolicyPapException;
37 import org.onap.policy.pap.main.parameters.PapParameterGroup;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.beans.factory.annotation.Value;
42 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
43 import org.springframework.stereotype.Component;
44
45 /**
46  * This class creates initial PdpGroup/SubGroup in the database.
47  *
48  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
49  */
50 @Component
51 @ConditionalOnProperty(value = "db.initialize", havingValue = "true", matchIfMissing = true)
52 public class PapDatabaseInitializer {
53
54     private static final Logger LOGGER = LoggerFactory.getLogger(PapDatabaseInitializer.class);
55
56     private final StandardCoder standardCoder;
57     private final PolicyModelsProviderFactory factory;
58
59     @Autowired
60     private PapParameterGroup papParameterGroup;
61
62     @Value("${group-config-file:PapDb.json}")
63     private String groupConfigFile;
64
65     /**
66      * Constructs the object.
67      */
68     public PapDatabaseInitializer() {
69         factory = new PolicyModelsProviderFactory();
70         standardCoder = new StandardCoder();
71     }
72
73     /**
74      * Initializes database with group information.
75      *
76      * @param policyModelsProviderParameters the database parameters
77      * @param groupsJson the group file path
78      * @throws PolicyPapException in case of errors.
79      */
80     private void initializePapDatabase(
81             final PolicyModelsProviderParameters policyModelsProviderParameters,
82             String groupsJson) throws PolicyPapException {
83
84         try (var databaseProvider =
85                      factory.createPolicyModelsProvider(policyModelsProviderParameters)) {
86             final var originalJson = ResourceUtils.getResourceAsString(groupsJson);
87             final var pdpGroupsToCreate = standardCoder.decode(originalJson, PdpGroups.class);
88             final List<PdpGroup> pdpGroupsFromDb = databaseProvider.getPdpGroups(
89                     pdpGroupsToCreate.getGroups().get(0).getName());
90             if (pdpGroupsFromDb.isEmpty()) {
91                 ValidationResult result = pdpGroupsToCreate.validatePapRest();
92                 if (!result.isValid()) {
93                     throw new PolicyPapException(result.getResult());
94                 }
95                 databaseProvider.createPdpGroups(pdpGroupsToCreate.getGroups());
96                 LOGGER.info("Created initial pdpGroup in DB - {} from {}", pdpGroupsToCreate, groupsJson);
97             } else {
98                 LOGGER.info("Initial pdpGroup already exists in DB, skipping create - {} from {}",
99                         pdpGroupsFromDb, groupsJson);
100             }
101         } catch (final PfModelException | CoderException | RuntimeException exp) {
102             throw new PolicyPapException(exp);
103         }
104     }
105
106     /**
107      * Initializes database with group information.
108      */
109     @PostConstruct
110     public void loadData() throws PolicyPapException {
111         initializePapDatabase(papParameterGroup.getDatabaseProviderParameters(), groupConfigFile);
112     }
113 }