Allow storing database password in environment variables
[policy/models.git] / models-provider / src / main / java / org / onap / policy / models / provider / impl / DatabasePolicyModelsProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.provider.impl;
23
24 import java.util.Base64;
25 import java.util.Date;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Properties;
29
30 import javax.ws.rs.core.Response;
31
32 import lombok.NonNull;
33
34 import org.eclipse.persistence.config.PersistenceUnitProperties;
35 import org.onap.policy.models.base.PfModelException;
36 import org.onap.policy.models.base.PfModelRuntimeException;
37 import org.onap.policy.models.dao.DaoParameters;
38 import org.onap.policy.models.dao.PfDao;
39 import org.onap.policy.models.dao.PfDaoFactory;
40 import org.onap.policy.models.dao.impl.DefaultPfDao;
41 import org.onap.policy.models.pdp.concepts.Pdp;
42 import org.onap.policy.models.pdp.concepts.PdpGroup;
43 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
44 import org.onap.policy.models.pdp.concepts.PdpStatistics;
45 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
46 import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
47 import org.onap.policy.models.pdp.persistence.provider.PdpStatisticsProvider;
48 import org.onap.policy.models.provider.PolicyModelsProvider;
49 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
55 import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider;
56 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
57 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
58 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
59 import org.onap.policy.models.tosca.legacy.provider.LegacyProvider;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 /**
64  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
65  * a relational database.
66  *
67  * @author Liam Fallon (liam.fallon@est.tech)
68  */
69 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
70
71     private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderImpl.class);
72
73     private final PolicyModelsProviderParameters parameters;
74
75     // Database connection and the DAO for reading and writing Policy Framework concepts
76     private PfDao pfDao;
77
78     /**
79      * Constructor that takes the parameters.
80      *
81      * @param parameters the parameters for the provider
82      */
83     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
84         this.parameters = parameters;
85     }
86
87     @Override
88     public void init() throws PfModelException {
89         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
90                 parameters.getPersistenceUnit());
91
92         if (pfDao != null) {
93             String errorMessage = "provider is already initialized";
94             LOGGER.warn(errorMessage);
95             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
96         }
97
98         // Parameters for the DAO
99         final DaoParameters daoParameters = new DaoParameters();
100         daoParameters.setPluginClass(DefaultPfDao.class.getName());
101         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
102
103         // Decode the password using Base64
104         String decodedPassword = new String(Base64.getDecoder().decode(getValue(parameters.getDatabasePassword())));
105
106         // @formatter:off
107         Properties jdbcProperties = new Properties();
108         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
109         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
110         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
111         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, decodedPassword);
112         // @formatter:on
113
114         daoParameters.setJdbcProperties(jdbcProperties);
115
116         try {
117             pfDao = new PfDaoFactory().createPfDao(daoParameters);
118             pfDao.init(daoParameters);
119         } catch (Exception exc) {
120             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
121                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
122
123             this.close();
124             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
125         }
126     }
127
128     private String getValue(final String value) {
129         if (value != null && value.matches("[$][{].*[}]$")) {
130             return System.getenv(value.substring(2, value.length() - 1));
131         }
132         return value;
133     }
134
135     @Override
136     public void close() throws PfModelException {
137         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
138                 parameters.getPersistenceUnit());
139
140         if (pfDao != null) {
141             pfDao.close();
142             pfDao = null;
143         }
144
145         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
146                 parameters.getPersistenceUnit());
147     }
148
149     @Override
150     public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
151         assertInitialized();
152         return new AuthorativeToscaProvider().getPolicyTypes(pfDao, name, version);
153     }
154
155     @Override
156     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
157         assertInitialized();
158         return new AuthorativeToscaProvider().getPolicyTypeList(pfDao, name, version);
159     }
160
161     @Override
162     public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaPolicyTypeFilter filter) throws PfModelException {
163         assertInitialized();
164         return new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, filter);
165     }
166
167     @Override
168     public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaPolicyTypeFilter filter)
169             throws PfModelException {
170         assertInitialized();
171         return new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, filter);
172     }
173
174     @Override
175     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
176             throws PfModelException {
177         assertInitialized();
178         return new AuthorativeToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
179     }
180
181     @Override
182     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
183             throws PfModelException {
184         assertInitialized();
185         return new AuthorativeToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
186     }
187
188     @Override
189     public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
190             throws PfModelException {
191         assertInitialized();
192         return new AuthorativeToscaProvider().deletePolicyType(pfDao, name, version);
193     }
194
195     @Override
196     public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
197         assertInitialized();
198         return new AuthorativeToscaProvider().getPolicies(pfDao, name, version);
199     }
200
201     @Override
202     public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
203         assertInitialized();
204         return new AuthorativeToscaProvider().getPolicyList(pfDao, name, version);
205     }
206
207     @Override
208     public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaPolicyFilter filter) throws PfModelException {
209         assertInitialized();
210         return new AuthorativeToscaProvider().getFilteredPolicies(pfDao, filter);
211     }
212
213     @Override
214     public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaPolicyFilter filter) throws PfModelException {
215         assertInitialized();
216         return new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, filter);
217     }
218
219     @Override
220     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
221             throws PfModelException {
222         assertInitialized();
223         return new AuthorativeToscaProvider().createPolicies(pfDao, serviceTemplate);
224     }
225
226     @Override
227     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
228             throws PfModelException {
229         assertInitialized();
230         return new AuthorativeToscaProvider().updatePolicies(pfDao, serviceTemplate);
231     }
232
233     @Override
234     public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
235             throws PfModelException {
236         assertInitialized();
237         return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version);
238     }
239
240     @Override
241     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId, final String policyVersion)
242             throws PfModelException {
243         assertInitialized();
244         return new LegacyProvider().getOperationalPolicy(pfDao, policyId, policyVersion);
245     }
246
247     @Override
248     public LegacyOperationalPolicy createOperationalPolicy(
249             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
250         assertInitialized();
251         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
252     }
253
254     @Override
255     public LegacyOperationalPolicy updateOperationalPolicy(
256             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
257         assertInitialized();
258         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
259     }
260
261     @Override
262     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId,
263             @NonNull final String policyVersion) throws PfModelException {
264         assertInitialized();
265         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId, policyVersion);
266     }
267
268     @Override
269     public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(@NonNull final String policyId,
270             final String policyVersion) throws PfModelException {
271         assertInitialized();
272         return new LegacyProvider().getGuardPolicy(pfDao, policyId, policyVersion);
273     }
274
275     @Override
276     public Map<String, LegacyGuardPolicyOutput>
277             createGuardPolicy(@NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
278         assertInitialized();
279         return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy);
280     }
281
282     @Override
283     public Map<String, LegacyGuardPolicyOutput>
284             updateGuardPolicy(@NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException {
285         assertInitialized();
286         return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy);
287     }
288
289     @Override
290     public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId,
291             @NonNull final String policyVersion) throws PfModelException {
292         assertInitialized();
293         return new LegacyProvider().deleteGuardPolicy(pfDao, policyId, policyVersion);
294     }
295
296     @Override
297     public List<PdpGroup> getPdpGroups(final String name) throws PfModelException {
298         assertInitialized();
299         return new PdpProvider().getPdpGroups(pfDao, name);
300     }
301
302     @Override
303     public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
304         assertInitialized();
305         return new PdpProvider().getFilteredPdpGroups(pfDao, filter);
306     }
307
308     @Override
309     public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
310         assertInitialized();
311         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
312     }
313
314     @Override
315     public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
316         assertInitialized();
317         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
318     }
319
320     @Override
321     public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup)
322             throws PfModelException {
323         assertInitialized();
324         new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpSubGroup);
325     }
326
327     @Override
328     public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp)
329             throws PfModelException {
330         new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpSubGroup, pdp);
331     }
332
333     @Override
334     public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException {
335         assertInitialized();
336         return new PdpProvider().deletePdpGroup(pfDao, name);
337     }
338
339     @Override
340     public List<PdpStatistics> getPdpStatistics(final String name, final Date timestamp) throws PfModelException {
341         assertInitialized();
342         return new PdpStatisticsProvider().getPdpStatistics(pfDao, name, timestamp);
343     }
344
345     @Override
346     public List<PdpStatistics> getFilteredPdpStatistics(final String name, @NonNull final String pdpGroupName,
347             final String pdpSubGroup, final Date startTimeStamp, final Date endTimeStamp, final String sortOrder,
348             final int getRecordNum) throws PfModelException {
349         assertInitialized();
350         return new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, name, pdpGroupName, pdpSubGroup,
351                 startTimeStamp, endTimeStamp, sortOrder, getRecordNum);
352     }
353
354     @Override
355     public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
356             throws PfModelException {
357         assertInitialized();
358         return new PdpStatisticsProvider().createPdpStatistics(pfDao, pdpStatisticsList);
359     }
360
361     @Override
362     public List<PdpStatistics> updatePdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
363             throws PfModelException {
364         assertInitialized();
365         return new PdpStatisticsProvider().updatePdpStatistics(pfDao, pdpStatisticsList);
366     }
367
368     @Override
369     public List<PdpStatistics> deletePdpStatistics(@NonNull final String name, final Date timestamp)
370             throws PfModelException {
371         assertInitialized();
372         return new PdpStatisticsProvider().deletePdpStatistics(pfDao, name, timestamp);
373     }
374
375     /**
376      * Check if the model provider is initialized.
377      */
378     private void assertInitialized() {
379         if (pfDao == null) {
380             String errorMessage = "policy models provider is not initilaized";
381             LOGGER.warn(errorMessage);
382             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
383         }
384     }
385 }