Merge "Fix sonars in policy models"
[policy/models.git] / models-provider / src / main / java / org / onap / policy / models / provider / impl / AbstractModelsProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
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.models.provider.impl;
23
24 import java.io.Closeable;
25 import java.util.Properties;
26 import javax.ws.rs.core.Response;
27 import lombok.Getter;
28 import lombok.NonNull;
29 import org.eclipse.persistence.config.PersistenceUnitProperties;
30 import org.onap.policy.models.base.PfModelException;
31 import org.onap.policy.models.dao.DaoParameters;
32 import org.onap.policy.models.dao.PfDao;
33 import org.onap.policy.models.dao.PfDaoFactory;
34 import org.onap.policy.models.dao.impl.DefaultPfDao;
35 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * This class provides an abstract models provider that can be used to initialise the database for any specialisation of
41  * the class.
42  */
43 public abstract class AbstractModelsProvider implements Closeable {
44
45     private static final Logger LOGGER = LoggerFactory.getLogger(AbstractModelsProvider.class);
46
47     private final PolicyModelsProviderParameters parameters;
48
49     // Database connection and the DAO for reading and writing Policy Framework concepts
50     @Getter
51     private PfDao pfDao;
52
53     /**
54      * Constructor that takes the parameters.
55      *
56      * @param parameters the parameters for the provider
57      */
58     protected AbstractModelsProvider(@NonNull final PolicyModelsProviderParameters parameters) {
59         this.parameters = parameters;
60     }
61
62     /**
63      * Initialise the provider.
64      *
65      * @throws PfModelException in initialisation errors
66      */
67     public synchronized void init() throws PfModelException {
68         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
69                 parameters.getPersistenceUnit());
70
71         if (pfDao != null) {
72             var errorMessage = "provider is already initialized";
73             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
74         }
75
76         // Parameters for the DAO
77         final var daoParameters = new DaoParameters();
78         daoParameters.setPluginClass(DefaultPfDao.class.getName());
79         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
80
81         // @formatter:off
82         var jdbcProperties = new Properties();
83         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
84         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
85         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
86         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, parameters.getDatabasePassword());
87         jdbcProperties.setProperty(PersistenceUnitProperties.TARGET_DATABASE,
88                         (parameters.getDatabaseType() == null ? "MySQL" : parameters.getDatabaseType()));
89         // @formatter:on
90
91         daoParameters.setJdbcProperties(jdbcProperties);
92
93         try {
94             pfDao = new PfDaoFactory().createPfDao(daoParameters);
95             pfDao.init(daoParameters);
96         } catch (Exception exc) {
97             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
98                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
99
100             this.close();
101             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
102         }
103     }
104
105     @Override
106     public synchronized void close() {
107         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
108                 parameters.getPersistenceUnit());
109
110         if (pfDao != null) {
111             pfDao.close();
112             pfDao = null;
113         }
114
115         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
116                 parameters.getPersistenceUnit());
117     }
118 }