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