Merge "migrate model-impl from drools-applications"
[policy/models.git] / models-provider / src / main / java / org / onap / policy / models / provider / impl / DatabasePolicyModelsProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.models.provider.impl;
22
23 import java.sql.Connection;
24 import java.sql.DriverManager;
25 import java.util.Base64;
26
27 import javax.ws.rs.core.Response;
28
29 import lombok.NonNull;
30
31 import org.onap.policy.models.base.PfConceptKey;
32 import org.onap.policy.models.base.PfModelException;
33 import org.onap.policy.models.base.PfModelRuntimeException;
34 import org.onap.policy.models.dao.DaoParameters;
35 import org.onap.policy.models.dao.PfDao;
36 import org.onap.policy.models.dao.PfDaoFactory;
37 import org.onap.policy.models.dao.impl.DefaultPfDao;
38 import org.onap.policy.models.pap.concepts.PdpGroups;
39 import org.onap.policy.models.pap.provider.PapProvider;
40 import org.onap.policy.models.provider.PolicyModelsProvider;
41 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
42 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy;
43 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
44 import org.onap.policy.models.tosca.legacy.provider.LegacyProvider;
45 import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
46 import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
52  * a relational database.
53  *
54  * @author Liam Fallon (liam.fallon@est.tech)
55  */
56 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
57     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPfDao.class);
58
59     private final PolicyModelsProviderParameters parameters;
60
61     // Database connection and the DAO for reading and writing Policy Framework concepts
62     private Connection connection;
63     private PfDao pfDao;
64
65     /**
66      * Constructor that takes the parameters.
67      *
68      * @param parameters the parameters for the provider
69      */
70     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
71         this.parameters = parameters;
72     }
73
74     @Override
75     public void init() throws PfModelException {
76         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
77                 parameters.getPersistenceUnit());
78
79         // Decode the password using Base64
80         String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword()));
81
82         // Connect to the database, call does not implement AutoCloseable for try-with-resources
83         try {
84             connection = DriverManager.getConnection(parameters.getDatabaseUrl(), parameters.getDatabaseUser(),
85                     decodedPassword);
86         } catch (Exception exc) {
87             String errorMessage = "could not connect to database with URL \"" + parameters.getDatabaseUrl() + "\"";
88             LOGGER.warn(errorMessage, exc);
89             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
90         }
91
92         // Parameters for the DAO
93         final DaoParameters daoParameters = new DaoParameters();
94         daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName());
95         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
96
97         try {
98             pfDao = new PfDaoFactory().createPfDao(daoParameters);
99             pfDao.init(daoParameters);
100         } catch (Exception exc) {
101             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
102                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
103             LOGGER.warn(errorMessage, exc);
104
105             this.close();
106             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
107         }
108     }
109
110     @Override
111     public void close() throws PfModelException {
112         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
113                 parameters.getPersistenceUnit());
114
115         if (pfDao != null) {
116             pfDao.close();
117             pfDao = null;
118         }
119
120         if (connection != null) {
121             try {
122                 connection.close();
123             } catch (Exception exc) {
124
125                 String errorMessage =
126                         "could not close connection to database with URL \"" + parameters.getDatabaseUrl() + "\"";
127                 LOGGER.warn(errorMessage, exc);
128                 throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc);
129             } finally {
130                 connection = null;
131             }
132         }
133
134         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
135                 parameters.getPersistenceUnit());
136     }
137
138     @Override
139     public ToscaServiceTemplate getPolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException {
140         assertInitilized();
141         return new SimpleToscaProvider().getPolicyTypes(pfDao, policyTypeKey);
142     }
143
144     @Override
145     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
146             throws PfModelException {
147         assertInitilized();
148         return new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
149     }
150
151     @Override
152     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
153             throws PfModelException {
154         assertInitilized();
155         return new SimpleToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
156     }
157
158     @Override
159     public ToscaServiceTemplate deletePolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException {
160         assertInitilized();
161         return new SimpleToscaProvider().deletePolicyTypes(pfDao, policyTypeKey);
162     }
163
164     @Override
165     public ToscaServiceTemplate getPolicies(@NonNull final PfConceptKey policyKey) throws PfModelException {
166         assertInitilized();
167         return new SimpleToscaProvider().getPolicies(pfDao, policyKey);
168     }
169
170     @Override
171     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
172             throws PfModelException {
173         assertInitilized();
174         return new SimpleToscaProvider().createPolicies(pfDao, serviceTemplate);
175     }
176
177     @Override
178     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
179             throws PfModelException {
180         assertInitilized();
181         return new SimpleToscaProvider().updatePolicies(pfDao, serviceTemplate);
182     }
183
184     @Override
185     public ToscaServiceTemplate deletePolicies(@NonNull final PfConceptKey policyKey) throws PfModelException {
186         assertInitilized();
187         return new SimpleToscaProvider().deletePolicies(pfDao, policyKey);
188     }
189
190     @Override
191     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException {
192         assertInitilized();
193         return new LegacyProvider().getOperationalPolicy(pfDao, policyId);
194     }
195
196     @Override
197     public LegacyOperationalPolicy createOperationalPolicy(
198             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
199         assertInitilized();
200         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
201     }
202
203     @Override
204     public LegacyOperationalPolicy updateOperationalPolicy(
205             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
206         assertInitilized();
207         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
208     }
209
210     @Override
211     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException {
212         assertInitilized();
213         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId);
214     }
215
216     @Override
217     public LegacyGuardPolicy getGuardPolicy(@NonNull final String policyId) throws PfModelException {
218         assertInitilized();
219         return new LegacyProvider().getGuardPolicy(pfDao, policyId);
220     }
221
222     @Override
223     public LegacyGuardPolicy createGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy)
224             throws PfModelException {
225         assertInitilized();
226         return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
227     }
228
229     @Override
230     public LegacyGuardPolicy updateGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy)
231             throws PfModelException {
232         assertInitilized();
233         return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
234     }
235
236     @Override
237     public LegacyGuardPolicy deleteGuardPolicy(@NonNull final String policyId) throws PfModelException {
238         assertInitilized();
239         return new LegacyProvider().deleteGuardPolicy(pfDao, policyId);
240     }
241
242     @Override
243     public PdpGroups getPdpGroups(@NonNull String pdpGroupFilter) throws PfModelException {
244         assertInitilized();
245         return new PapProvider().getPdpGroups(pfDao, pdpGroupFilter);
246     }
247
248     @Override
249     public PdpGroups createPdpGroups(@NonNull PdpGroups pdpGroups) throws PfModelException {
250         assertInitilized();
251         return new PapProvider().createPdpGroups(pfDao, pdpGroups);
252     }
253
254     @Override
255     public PdpGroups updatePdpGroups(@NonNull PdpGroups pdpGroups) throws PfModelException {
256         assertInitilized();
257         return new PapProvider().updatePdpGroups(pfDao, pdpGroups);
258     }
259
260     @Override
261     public PdpGroups deletePdpGroups(@NonNull String pdpGroupFilter) throws PfModelException {
262         assertInitilized();
263         return new PapProvider().deletePdpGroups(pfDao, pdpGroupFilter);
264     }
265
266     /**
267      * Check if the model provider is initialized.
268      */
269     private void assertInitilized() {
270         if (pfDao == null) {
271             String errorMessage = "policy models provider is not initilaized";
272             LOGGER.warn(errorMessage);
273             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
274         }
275     }
276
277     /**
278      * Hook for unit test mocking of database connection.
279      *
280      * @param client the mocked client
281      */
282     protected void setConnection(final Connection connection) {
283         this.connection = connection;
284     }
285 }