Add impl of more PDP persistence
[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.Pdp;
41 import org.onap.policy.models.pdp.concepts.PdpGroup;
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         if (connection != null || pfDao != null) {
88             String errorMessage = "provider is already initialized";
89             LOGGER.warn(errorMessage);
90             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
91         }
92
93         // Decode the password using Base64
94         String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword()));
95
96         // Connect to the database, call does not implement AutoCloseable for try-with-resources
97         try {
98             connection = DriverManager.getConnection(parameters.getDatabaseUrl(), parameters.getDatabaseUser(),
99                     decodedPassword);
100         } catch (Exception exc) {
101             String errorMessage = "could not connect to database with URL \"" + parameters.getDatabaseUrl() + "\"";
102             LOGGER.warn(errorMessage, exc);
103             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
104         }
105
106         // Parameters for the DAO
107         final DaoParameters daoParameters = new DaoParameters();
108         daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName());
109         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
110
111         try {
112             pfDao = new PfDaoFactory().createPfDao(daoParameters);
113             pfDao.init(daoParameters);
114         } catch (Exception exc) {
115             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
116                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
117             LOGGER.warn(errorMessage, exc);
118
119             this.close();
120             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
121         }
122     }
123
124     @Override
125     public void close() throws PfModelException {
126         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
127                 parameters.getPersistenceUnit());
128
129         if (pfDao != null) {
130             pfDao.close();
131             pfDao = null;
132         }
133
134         if (connection != null) {
135             try {
136                 connection.close();
137             } catch (Exception exc) {
138
139                 String errorMessage =
140                         "could not close connection to database with URL \"" + parameters.getDatabaseUrl() + "\"";
141                 LOGGER.warn(errorMessage, exc);
142                 throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc);
143             } finally {
144                 connection = null;
145             }
146         }
147
148         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
149                 parameters.getPersistenceUnit());
150     }
151
152     @Override
153     public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
154         assertInitilized();
155         return new AuthorativeToscaProvider().getPolicyTypes(pfDao, name, version);
156     }
157
158     @Override
159     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
160         assertInitilized();
161         return new AuthorativeToscaProvider().getPolicyTypeList(pfDao, name, version);
162     }
163
164     @Override
165     public ToscaServiceTemplate getLatestPolicyTypes(final String name) throws PfModelException {
166         assertInitilized();
167         return new AuthorativeToscaProvider().getLatestPolicyTypes(pfDao, name);
168     }
169
170     @Override
171     public List<ToscaPolicyType> getLatestPolicyTypeList(final String name) throws PfModelException {
172         assertInitilized();
173         return new AuthorativeToscaProvider().getLatestPolicyTypeList(pfDao, name);
174     }
175
176     @Override
177     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
178             throws PfModelException {
179         assertInitilized();
180         return new AuthorativeToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
181     }
182
183     @Override
184     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
185             throws PfModelException {
186         assertInitilized();
187         return new AuthorativeToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
188     }
189
190     @Override
191     public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
192             throws PfModelException {
193         assertInitilized();
194         return new AuthorativeToscaProvider().deletePolicyType(pfDao, name, version);
195     }
196
197     @Override
198     public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
199         assertInitilized();
200         return new AuthorativeToscaProvider().getPolicies(pfDao, name, version);
201     }
202
203     @Override
204     public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
205         assertInitilized();
206         return new AuthorativeToscaProvider().getPolicyList(pfDao, name, version);
207     }
208
209     @Override
210     public ToscaServiceTemplate getPolicies4PolicyType(@NonNull String policyTypeName, String policyTypeVersion)
211             throws PfModelException {
212         assertInitilized();
213         return new AuthorativeToscaProvider().getPolicies4PolicyType(pfDao, policyTypeName, policyTypeVersion);
214     }
215
216     @Override
217     public List<ToscaPolicy> getPolicyList4PolicyType(@NonNull final String policyTypeName,
218             final String policyTypeVersion) throws PfModelException {
219         assertInitilized();
220         return new AuthorativeToscaProvider().getPolicyList4PolicyType(pfDao, policyTypeName, policyTypeVersion);
221     }
222
223     @Override
224     public ToscaServiceTemplate getLatestPolicies(final String name) throws PfModelException {
225         assertInitilized();
226         return new AuthorativeToscaProvider().getLatestPolicies(pfDao, name);
227     }
228
229     @Override
230     public List<ToscaPolicy> getLatestPolicyList(final String name) throws PfModelException {
231         assertInitilized();
232         return new AuthorativeToscaProvider().getLatestPolicyList(pfDao, name);
233     }
234
235     @Override
236     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
237             throws PfModelException {
238         assertInitilized();
239         return new AuthorativeToscaProvider().createPolicies(pfDao, serviceTemplate);
240     }
241
242     @Override
243     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
244             throws PfModelException {
245         assertInitilized();
246         return new AuthorativeToscaProvider().updatePolicies(pfDao, serviceTemplate);
247     }
248
249     @Override
250     public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
251             throws PfModelException {
252         assertInitilized();
253         return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version);
254     }
255
256     @Override
257     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException {
258         assertInitilized();
259         return new LegacyProvider().getOperationalPolicy(pfDao, policyId);
260     }
261
262     @Override
263     public LegacyOperationalPolicy createOperationalPolicy(
264             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
265         assertInitilized();
266         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
267     }
268
269     @Override
270     public LegacyOperationalPolicy updateOperationalPolicy(
271             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
272         assertInitilized();
273         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
274     }
275
276     @Override
277     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException {
278         assertInitilized();
279         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId);
280     }
281
282     @Override
283     public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(@NonNull final String policyId) throws PfModelException {
284         assertInitilized();
285         return new LegacyProvider().getGuardPolicy(pfDao, policyId);
286     }
287
288     @Override
289     public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(
290             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
291         assertInitilized();
292         return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
293     }
294
295     @Override
296     public Map<String, LegacyGuardPolicyOutput> updateGuardPolicy(
297             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
298         assertInitilized();
299         return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
300     }
301
302     @Override
303     public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId)
304             throws PfModelException {
305         assertInitilized();
306         return new LegacyProvider().deleteGuardPolicy(pfDao, policyId);
307     }
308
309     @Override
310     public List<PdpGroup> getPdpGroups(final String name, final String version) throws PfModelException {
311         assertInitilized();
312         return new PdpProvider().getPdpGroups(pfDao, name, version);
313     }
314
315     @Override
316     public List<PdpGroup> getLatestPdpGroups(final String name) throws PfModelException {
317         assertInitilized();
318         return new PdpProvider().getLatestPdpGroups(pfDao, name);
319     }
320
321     @Override
322     public List<PdpGroup> getFilteredPdpGroups(final String pdpType,
323             @NonNull final List<Pair<String, String>> supportedPolicyTypes) {
324         assertInitilized();
325         return new PdpProvider().getFilteredPdpGroups(pfDao, pdpType, supportedPolicyTypes);
326     }
327
328     @Override
329     public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
330         assertInitilized();
331         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
332     }
333
334     @Override
335     public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
336         assertInitilized();
337         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
338     }
339
340     @Override
341     public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion,
342             @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException {
343         assertInitilized();
344         new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpGroupVersion, pdpSubGroup);
345     }
346
347     @Override
348     public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion,
349             @NonNull String pdpSubGroup, @NonNull Pdp pdp) throws PfModelException {
350         new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpGroupVersion, pdpSubGroup, pdp);
351     }
352
353     @Override
354     public PdpGroup deletePdpGroup(@NonNull final String name, @NonNull final String version) throws PfModelException {
355         assertInitilized();
356         return new PdpProvider().deletePdpGroup(pfDao, name, version);
357     }
358
359     @Override
360     public List<PdpStatistics> getPdpStatistics(final String name, final String version) throws PfModelException {
361         assertInitilized();
362         return new PdpProvider().getPdpStatistics(pfDao, name, version);
363     }
364
365     @Override
366     public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion,
367             @NonNull final String pdpType, @NonNull final String pdpInstanceId,
368             @NonNull final PdpStatistics pdppStatistics) throws PfModelException {
369         assertInitilized();
370         new PdpProvider().updatePdpStatistics(pfDao, pdpGroupName, pdpGroupVersion, pdpType, pdpInstanceId,
371                 pdppStatistics);
372     }
373
374     @Override
375     public Map<Pair<String, String>, List<ToscaPolicy>> getDeployedPolicyList(final String name)
376             throws PfModelException {
377         assertInitilized();
378         return new PdpProvider().getDeployedPolicyList(pfDao, name);
379     }
380
381     /**
382      * Check if the model provider is initialized.
383      */
384     private void assertInitilized() {
385         if (pfDao == null) {
386             String errorMessage = "policy models provider is not initilaized";
387             LOGGER.warn(errorMessage);
388             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
389         }
390     }
391
392     /**
393      * Hook for unit test mocking of database connection.
394      *
395      * @param client the mocked client
396      */
397     protected void setConnection(final Connection connection) {
398         this.connection = connection;
399     }
400 }