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