Merge "move two modules from drools-application to models"
[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 import java.util.List;
27 import java.util.Map;
28
29 import javax.ws.rs.core.Response;
30
31 import lombok.NonNull;
32
33 import org.onap.policy.models.base.PfModelException;
34 import org.onap.policy.models.base.PfModelRuntimeException;
35 import org.onap.policy.models.dao.DaoParameters;
36 import org.onap.policy.models.dao.PfDao;
37 import org.onap.policy.models.dao.PfDaoFactory;
38 import org.onap.policy.models.dao.impl.DefaultPfDao;
39 import org.onap.policy.models.pdp.concepts.Pdp;
40 import org.onap.policy.models.pdp.concepts.PdpGroup;
41 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
42 import org.onap.policy.models.pdp.concepts.PdpStatistics;
43 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
44 import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
45 import org.onap.policy.models.provider.PolicyModelsProvider;
46 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
52 import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider;
53 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
54 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
55 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
56 import org.onap.policy.models.tosca.legacy.provider.LegacyProvider;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
62  * a relational database.
63  *
64  * @author Liam Fallon (liam.fallon@est.tech)
65  */
66 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
67     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPfDao.class);
68
69     private final PolicyModelsProviderParameters parameters;
70
71     // Database connection and the DAO for reading and writing Policy Framework concepts
72     private Connection connection;
73     private PfDao pfDao;
74
75     /**
76      * Constructor that takes the parameters.
77      *
78      * @param parameters the parameters for the provider
79      */
80     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
81         this.parameters = parameters;
82     }
83
84     @Override
85     public void init() throws PfModelException {
86         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
87                 parameters.getPersistenceUnit());
88
89         if (connection != null || pfDao != null) {
90             String errorMessage = "provider is already initialized";
91             LOGGER.warn(errorMessage);
92             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
93         }
94
95         // Decode the password using Base64
96         String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword()));
97
98         // Connect to the database, call does not implement AutoCloseable for try-with-resources
99         try {
100             connection = DriverManager.getConnection(parameters.getDatabaseUrl(), parameters.getDatabaseUser(),
101                     decodedPassword);
102         } catch (Exception exc) {
103             String errorMessage = "could not connect to database with URL \"" + parameters.getDatabaseUrl() + "\"";
104             LOGGER.warn(errorMessage, exc);
105             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
106         }
107
108         // Parameters for the DAO
109         final DaoParameters daoParameters = new DaoParameters();
110         daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName());
111         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
112
113         try {
114             pfDao = new PfDaoFactory().createPfDao(daoParameters);
115             pfDao.init(daoParameters);
116         } catch (Exception exc) {
117             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
118                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
119             LOGGER.warn(errorMessage, exc);
120
121             this.close();
122             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
123         }
124     }
125
126     @Override
127     public void close() throws PfModelException {
128         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
129                 parameters.getPersistenceUnit());
130
131         if (pfDao != null) {
132             pfDao.close();
133             pfDao = null;
134         }
135
136         if (connection != null) {
137             try {
138                 connection.close();
139             } catch (Exception exc) {
140
141                 String errorMessage =
142                         "could not close connection to database with URL \"" + parameters.getDatabaseUrl() + "\"";
143                 LOGGER.warn(errorMessage, exc);
144                 throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc);
145             } finally {
146                 connection = null;
147             }
148         }
149
150         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
151                 parameters.getPersistenceUnit());
152     }
153
154     @Override
155     public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
156         assertInitilized();
157         return new AuthorativeToscaProvider().getPolicyTypes(pfDao, name, version);
158     }
159
160     @Override
161     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
162         assertInitilized();
163         return new AuthorativeToscaProvider().getPolicyTypeList(pfDao, name, version);
164     }
165
166     @Override
167     public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaPolicyTypeFilter filter) throws PfModelException {
168         assertInitilized();
169         return new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, filter);
170     }
171
172     @Override
173     public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaPolicyTypeFilter filter)
174             throws PfModelException {
175         assertInitilized();
176         return new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, filter);
177     }
178
179     @Override
180     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
181             throws PfModelException {
182         assertInitilized();
183         return new AuthorativeToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
184     }
185
186     @Override
187     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
188             throws PfModelException {
189         assertInitilized();
190         return new AuthorativeToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
191     }
192
193     @Override
194     public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
195             throws PfModelException {
196         assertInitilized();
197         return new AuthorativeToscaProvider().deletePolicyType(pfDao, name, version);
198     }
199
200     @Override
201     public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
202         assertInitilized();
203         return new AuthorativeToscaProvider().getPolicies(pfDao, name, version);
204     }
205
206     @Override
207     public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
208         assertInitilized();
209         return new AuthorativeToscaProvider().getPolicyList(pfDao, name, version);
210     }
211
212     @Override
213     public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaPolicyFilter filter) throws PfModelException {
214         assertInitilized();
215         return new AuthorativeToscaProvider().getFilteredPolicies(pfDao, filter);
216     }
217
218     @Override
219     public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaPolicyFilter filter) throws PfModelException {
220         assertInitilized();
221         return new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, filter);
222     }
223
224
225     @Override
226     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
227             throws PfModelException {
228         assertInitilized();
229         return new AuthorativeToscaProvider().createPolicies(pfDao, serviceTemplate);
230     }
231
232     @Override
233     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
234             throws PfModelException {
235         assertInitilized();
236         return new AuthorativeToscaProvider().updatePolicies(pfDao, serviceTemplate);
237     }
238
239     @Override
240     public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
241             throws PfModelException {
242         assertInitilized();
243         return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version);
244     }
245
246     @Override
247     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException {
248         assertInitilized();
249         return new LegacyProvider().getOperationalPolicy(pfDao, policyId);
250     }
251
252     @Override
253     public LegacyOperationalPolicy createOperationalPolicy(
254             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
255         assertInitilized();
256         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
257     }
258
259     @Override
260     public LegacyOperationalPolicy updateOperationalPolicy(
261             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
262         assertInitilized();
263         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
264     }
265
266     @Override
267     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException {
268         assertInitilized();
269         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId);
270     }
271
272     @Override
273     public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(@NonNull final String policyId) throws PfModelException {
274         assertInitilized();
275         return new LegacyProvider().getGuardPolicy(pfDao, policyId);
276     }
277
278     @Override
279     public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(
280             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
281         assertInitilized();
282         return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
283     }
284
285     @Override
286     public Map<String, LegacyGuardPolicyOutput> updateGuardPolicy(
287             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
288         assertInitilized();
289         return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
290     }
291
292     @Override
293     public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId)
294             throws PfModelException {
295         assertInitilized();
296         return new LegacyProvider().deleteGuardPolicy(pfDao, policyId);
297     }
298
299     @Override
300     public List<PdpGroup> getPdpGroups(final String name, final String version) throws PfModelException {
301         assertInitilized();
302         return new PdpProvider().getPdpGroups(pfDao, name, version);
303     }
304
305     @Override
306     public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
307         assertInitilized();
308         return new PdpProvider().getFilteredPdpGroups(pfDao, filter);
309     }
310
311     @Override
312     public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
313         assertInitilized();
314         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
315     }
316
317     @Override
318     public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
319         assertInitilized();
320         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
321     }
322
323     @Override
324     public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion,
325             @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException {
326         assertInitilized();
327         new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpGroupVersion, pdpSubGroup);
328     }
329
330     @Override
331     public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion,
332             @NonNull String pdpSubGroup, @NonNull Pdp pdp) throws PfModelException {
333         new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpGroupVersion, pdpSubGroup, pdp);
334     }
335
336     @Override
337     public PdpGroup deletePdpGroup(@NonNull final String name, @NonNull final String version) throws PfModelException {
338         assertInitilized();
339         return new PdpProvider().deletePdpGroup(pfDao, name, version);
340     }
341
342     @Override
343     public List<PdpStatistics> getPdpStatistics(final String name, final String version) throws PfModelException {
344         assertInitilized();
345         return new PdpProvider().getPdpStatistics(pfDao, name, version);
346     }
347
348     @Override
349     public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion,
350             @NonNull final String pdpType, @NonNull final String pdpInstanceId,
351             @NonNull final PdpStatistics pdppStatistics) throws PfModelException {
352         assertInitilized();
353         new PdpProvider().updatePdpStatistics(pfDao, pdpGroupName, pdpGroupVersion, pdpType, pdpInstanceId,
354                 pdppStatistics);
355     }
356
357     /**
358      * Check if the model provider is initialized.
359      */
360     private void assertInitilized() {
361         if (pfDao == null) {
362             String errorMessage = "policy models provider is not initilaized";
363             LOGGER.warn(errorMessage);
364             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
365         }
366     }
367
368     /**
369      * Hook for unit test mocking of database connection.
370      *
371      * @param client the mocked client
372      */
373     protected void setConnection(final Connection connection) {
374         this.connection = connection;
375     }
376 }