Merge "Add @NonNull to PolicyIdent"
[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.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.ToscaServiceTemplate;
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 ToscaServiceTemplate getPolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException {
142         assertInitilized();
143         return new SimpleToscaProvider().getPolicyTypes(pfDao, policyTypeKey);
144     }
145
146     @Override
147     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
148             throws PfModelException {
149         assertInitilized();
150         return new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
151     }
152
153     @Override
154     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
155             throws PfModelException {
156         assertInitilized();
157         return new SimpleToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
158     }
159
160     @Override
161     public ToscaServiceTemplate deletePolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException {
162         assertInitilized();
163         return new SimpleToscaProvider().deletePolicyTypes(pfDao, policyTypeKey);
164     }
165
166     @Override
167     public ToscaServiceTemplate getPolicies(@NonNull final PfConceptKey policyKey) throws PfModelException {
168         assertInitilized();
169         return new SimpleToscaProvider().getPolicies(pfDao, policyKey);
170     }
171
172     @Override
173     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
174             throws PfModelException {
175         assertInitilized();
176         return new SimpleToscaProvider().createPolicies(pfDao, serviceTemplate);
177     }
178
179     @Override
180     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
181             throws PfModelException {
182         assertInitilized();
183         return new SimpleToscaProvider().updatePolicies(pfDao, serviceTemplate);
184     }
185
186     @Override
187     public ToscaServiceTemplate deletePolicies(@NonNull final PfConceptKey policyKey) throws PfModelException {
188         assertInitilized();
189         return new SimpleToscaProvider().deletePolicies(pfDao, policyKey);
190     }
191
192     @Override
193     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException {
194         assertInitilized();
195         return new LegacyProvider().getOperationalPolicy(pfDao, policyId);
196     }
197
198     @Override
199     public LegacyOperationalPolicy createOperationalPolicy(
200             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
201         assertInitilized();
202         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
203     }
204
205     @Override
206     public LegacyOperationalPolicy updateOperationalPolicy(
207             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
208         assertInitilized();
209         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
210     }
211
212     @Override
213     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException {
214         assertInitilized();
215         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId);
216     }
217
218     @Override
219     public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(@NonNull final String policyId) throws PfModelException {
220         assertInitilized();
221         return new LegacyProvider().getGuardPolicy(pfDao, policyId);
222     }
223
224     @Override
225     public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(
226             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
227         assertInitilized();
228         return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
229     }
230
231     @Override
232     public Map<String, LegacyGuardPolicyOutput> updateGuardPolicy(
233             @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
234         assertInitilized();
235         return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
236     }
237
238     @Override
239     public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId)
240             throws PfModelException {
241         assertInitilized();
242         return new LegacyProvider().deleteGuardPolicy(pfDao, policyId);
243     }
244
245     @Override
246     public PdpGroups getPdpGroups(@NonNull String pdpGroupFilter) throws PfModelException {
247         assertInitilized();
248         return new PdpProvider().getPdpGroups(pfDao, pdpGroupFilter);
249     }
250
251     @Override
252     public PdpGroups createPdpGroups(@NonNull PdpGroups pdpGroups) throws PfModelException {
253         assertInitilized();
254         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
255     }
256
257     @Override
258     public PdpGroups updatePdpGroups(@NonNull PdpGroups pdpGroups) throws PfModelException {
259         assertInitilized();
260         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
261     }
262
263     @Override
264     public PdpGroups deletePdpGroups(@NonNull String pdpGroupFilter) throws PfModelException {
265         assertInitilized();
266         return new PdpProvider().deletePdpGroups(pfDao, pdpGroupFilter);
267     }
268
269     /**
270      * Check if the model provider is initialized.
271      */
272     private void assertInitilized() {
273         if (pfDao == null) {
274             String errorMessage = "policy models provider is not initilaized";
275             LOGGER.warn(errorMessage);
276             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
277         }
278     }
279
280     /**
281      * Hook for unit test mocking of database connection.
282      *
283      * @param client the mocked client
284      */
285     protected void setConnection(final Connection connection) {
286         this.connection = connection;
287     }
288 }