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