Restructure for authorative 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.Map;
27
28 import javax.ws.rs.core.Response;
29
30 import lombok.NonNull;
31
32 import org.onap.policy.models.base.PfConceptKey;
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.PdpGroups;
40 import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
41 import org.onap.policy.models.provider.PolicyModelsProvider;
42 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
43 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
44 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
45 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
46 import org.onap.policy.models.tosca.legacy.provider.LegacyProvider;
47 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
48 import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
54  * a relational database.
55  *
56  * @author Liam Fallon (liam.fallon@est.tech)
57  */
58 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
59     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPfDao.class);
60
61     private final PolicyModelsProviderParameters parameters;
62
63     // Database connection and the DAO for reading and writing Policy Framework concepts
64     private Connection connection;
65     private PfDao pfDao;
66
67     /**
68      * Constructor that takes the parameters.
69      *
70      * @param parameters the parameters for the provider
71      */
72     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
73         this.parameters = parameters;
74     }
75
76     @Override
77     public void init() throws PfModelException {
78         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
79                 parameters.getPersistenceUnit());
80
81         // Decode the password using Base64
82         String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword()));
83
84         // Connect to the database, call does not implement AutoCloseable for try-with-resources
85         try {
86             connection = DriverManager.getConnection(parameters.getDatabaseUrl(), parameters.getDatabaseUser(),
87                     decodedPassword);
88         } catch (Exception exc) {
89             String errorMessage = "could not connect to database with URL \"" + parameters.getDatabaseUrl() + "\"";
90             LOGGER.warn(errorMessage, exc);
91             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
92         }
93
94         // Parameters for the DAO
95         final DaoParameters daoParameters = new DaoParameters();
96         daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName());
97         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
98
99         try {
100             pfDao = new PfDaoFactory().createPfDao(daoParameters);
101             pfDao.init(daoParameters);
102         } catch (Exception exc) {
103             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
104                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
105             LOGGER.warn(errorMessage, exc);
106
107             this.close();
108             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
109         }
110     }
111
112     @Override
113     public void close() throws PfModelException {
114         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
115                 parameters.getPersistenceUnit());
116
117         if (pfDao != null) {
118             pfDao.close();
119             pfDao = null;
120         }
121
122         if (connection != null) {
123             try {
124                 connection.close();
125             } catch (Exception exc) {
126
127                 String errorMessage =
128                         "could not close connection to database with URL \"" + parameters.getDatabaseUrl() + "\"";
129                 LOGGER.warn(errorMessage, exc);
130                 throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc);
131             } finally {
132                 connection = null;
133             }
134         }
135
136         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
137                 parameters.getPersistenceUnit());
138     }
139
140     @Override
141     public JpaToscaServiceTemplate getPolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException {
142         assertInitilized();
143         return new SimpleToscaProvider().getPolicyTypes(pfDao, policyTypeKey);
144     }
145
146     @Override
147     public JpaToscaServiceTemplate createPolicyTypes(@NonNull final JpaToscaServiceTemplate serviceTemplate)
148             throws PfModelException {
149         assertInitilized();
150         return new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
151     }
152
153     @Override
154     public JpaToscaServiceTemplate updatePolicyTypes(@NonNull final JpaToscaServiceTemplate serviceTemplate)
155             throws PfModelException {
156         assertInitilized();
157         return new SimpleToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
158     }
159
160     @Override
161     public JpaToscaServiceTemplate deletePolicyTypes(@NonNull final PfConceptKey policyTypeKey)
162             throws PfModelException {
163         assertInitilized();
164         return new SimpleToscaProvider().deletePolicyTypes(pfDao, policyTypeKey);
165     }
166
167     @Override
168     public JpaToscaServiceTemplate getPolicies(@NonNull final PfConceptKey policyKey) throws PfModelException {
169         assertInitilized();
170         return new SimpleToscaProvider().getPolicies(pfDao, policyKey);
171     }
172
173     @Override
174     public JpaToscaServiceTemplate createPolicies(@NonNull final JpaToscaServiceTemplate serviceTemplate)
175             throws PfModelException {
176         assertInitilized();
177         return new SimpleToscaProvider().createPolicies(pfDao, serviceTemplate);
178     }
179
180     @Override
181     public JpaToscaServiceTemplate updatePolicies(@NonNull final JpaToscaServiceTemplate serviceTemplate)
182             throws PfModelException {
183         assertInitilized();
184         return new SimpleToscaProvider().updatePolicies(pfDao, serviceTemplate);
185     }
186
187     @Override
188     public JpaToscaServiceTemplate deletePolicies(@NonNull final PfConceptKey policyKey) throws PfModelException {
189         assertInitilized();
190         return new SimpleToscaProvider().deletePolicies(pfDao, policyKey);
191     }
192
193     @Override
194     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException {
195         assertInitilized();
196         return new LegacyProvider().getOperationalPolicy(pfDao, policyId);
197     }
198
199     @Override
200     public LegacyOperationalPolicy createOperationalPolicy(
201             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
202         assertInitilized();
203         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
204     }
205
206     @Override
207     public LegacyOperationalPolicy updateOperationalPolicy(
208             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
209         assertInitilized();
210         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
211     }
212
213     @Override
214     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException {
215         assertInitilized();
216         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId);
217     }
218
219     @Override
220     public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(@NonNull final String policyId) throws PfModelException {
221         assertInitilized();
222         return new LegacyProvider().getGuardPolicy(pfDao, policyId);
223     }
224
225     @Override
226     public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(
227             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
228         assertInitilized();
229         return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
230     }
231
232     @Override
233     public Map<String, LegacyGuardPolicyOutput> updateGuardPolicy(
234             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
235         assertInitilized();
236         return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
237     }
238
239     @Override
240     public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId)
241             throws PfModelException {
242         assertInitilized();
243         return new LegacyProvider().deleteGuardPolicy(pfDao, policyId);
244     }
245
246     @Override
247     public PdpGroups getPdpGroups(@NonNull String pdpGroupFilter) throws PfModelException {
248         assertInitilized();
249         return new PdpProvider().getPdpGroups(pfDao, pdpGroupFilter);
250     }
251
252     @Override
253     public PdpGroups createPdpGroups(@NonNull PdpGroups pdpGroups) throws PfModelException {
254         assertInitilized();
255         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
256     }
257
258     @Override
259     public PdpGroups updatePdpGroups(@NonNull PdpGroups pdpGroups) throws PfModelException {
260         assertInitilized();
261         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
262     }
263
264     @Override
265     public PdpGroups deletePdpGroups(@NonNull String pdpGroupFilter) throws PfModelException {
266         assertInitilized();
267         return new PdpProvider().deletePdpGroups(pfDao, pdpGroupFilter);
268     }
269
270     /**
271      * Check if the model provider is initialized.
272      */
273     private void assertInitilized() {
274         if (pfDao == null) {
275             String errorMessage = "policy models provider is not initilaized";
276             LOGGER.warn(errorMessage);
277             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
278         }
279     }
280
281     /**
282      * Hook for unit test mocking of database connection.
283      *
284      * @param client the mocked client
285      */
286     protected void setConnection(final Connection connection) {
287         this.connection = connection;
288     }
289 }