Changes for Checkstyle 8.32
[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-2020 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.Properties;
28 import javax.ws.rs.core.Response;
29 import lombok.NonNull;
30 import org.eclipse.persistence.config.PersistenceUnitProperties;
31 import org.onap.policy.models.base.PfModelException;
32 import org.onap.policy.models.base.PfModelRuntimeException;
33 import org.onap.policy.models.dao.DaoParameters;
34 import org.onap.policy.models.dao.PfDao;
35 import org.onap.policy.models.dao.PfDaoFactory;
36 import org.onap.policy.models.dao.impl.DefaultPfDao;
37 import org.onap.policy.models.pdp.concepts.Pdp;
38 import org.onap.policy.models.pdp.concepts.PdpGroup;
39 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
40 import org.onap.policy.models.pdp.concepts.PdpStatistics;
41 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
42 import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
43 import org.onap.policy.models.pdp.persistence.provider.PdpStatisticsProvider;
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.ToscaPolicyFilter;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
53 import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider;
54 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
55 import org.onap.policy.models.tosca.legacy.provider.LegacyProvider;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
61  * a relational database.
62  *
63  * @author Liam Fallon (liam.fallon@est.tech)
64  */
65 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
66
67     private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderImpl.class);
68
69     private final PolicyModelsProviderParameters parameters;
70
71     // Database connection and the DAO for reading and writing Policy Framework concepts
72     private PfDao pfDao;
73
74     /**
75      * Constructor that takes the parameters.
76      *
77      * @param parameters the parameters for the provider
78      */
79     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
80         this.parameters = parameters;
81     }
82
83     @Override
84     public void init() throws PfModelException {
85         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
86                 parameters.getPersistenceUnit());
87
88         if (pfDao != null) {
89             String errorMessage = "provider is already initialized";
90             LOGGER.warn(errorMessage);
91             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
92         }
93
94         // Parameters for the DAO
95         final DaoParameters daoParameters = new DaoParameters();
96         daoParameters.setPluginClass(DefaultPfDao.class.getName());
97         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
98
99         // Decode the password using Base64
100         String decodedPassword = new String(Base64.getDecoder().decode(getValue(parameters.getDatabasePassword())));
101
102         // @formatter:off
103         Properties jdbcProperties = new Properties();
104         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
105         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
106         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
107         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, decodedPassword);
108         // @formatter:on
109
110         daoParameters.setJdbcProperties(jdbcProperties);
111
112         try {
113             pfDao = new PfDaoFactory().createPfDao(daoParameters);
114             pfDao.init(daoParameters);
115         } catch (Exception exc) {
116             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
117                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
118
119             this.close();
120             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
121         }
122     }
123
124     private String getValue(final String value) {
125         if (value != null && value.startsWith("${") && value.endsWith("}")) {
126             return System.getenv(value.substring(2, value.length() - 1));
127         }
128         return value;
129     }
130
131     @Override
132     public void close() throws PfModelException {
133         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
134                 parameters.getPersistenceUnit());
135
136         if (pfDao != null) {
137             pfDao.close();
138             pfDao = null;
139         }
140
141         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
142                 parameters.getPersistenceUnit());
143     }
144
145     @Override
146     public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
147         assertInitialized();
148         return new AuthorativeToscaProvider().getPolicyTypes(pfDao, name, version);
149     }
150
151     @Override
152     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
153         assertInitialized();
154         return new AuthorativeToscaProvider().getPolicyTypeList(pfDao, name, version);
155     }
156
157     @Override
158     public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaPolicyTypeFilter filter) throws PfModelException {
159         assertInitialized();
160         return new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, filter);
161     }
162
163     @Override
164     public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaPolicyTypeFilter filter)
165             throws PfModelException {
166         assertInitialized();
167         return new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, filter);
168     }
169
170     @Override
171     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
172             throws PfModelException {
173         assertInitialized();
174         return new AuthorativeToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
175     }
176
177     @Override
178     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
179             throws PfModelException {
180         assertInitialized();
181         return new AuthorativeToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
182     }
183
184     @Override
185     public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
186             throws PfModelException {
187         assertInitialized();
188
189         ToscaPolicyTypeIdentifier policyTypeIdentifier = new ToscaPolicyTypeIdentifier(name, version);
190         assertPolicyTypeNotSupportedInPdpGroup(policyTypeIdentifier);
191
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
238         ToscaPolicyIdentifier policyIdentifier = new ToscaPolicyIdentifier(name, version);
239         assertPolicyNotDeployedInPdpGroup(policyIdentifier);
240
241         return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version);
242     }
243
244     @Override
245     public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId, final String policyVersion)
246             throws PfModelException {
247         assertInitialized();
248         return new LegacyProvider().getOperationalPolicy(pfDao, policyId, policyVersion);
249     }
250
251     @Override
252     public LegacyOperationalPolicy createOperationalPolicy(
253             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
254         assertInitialized();
255         return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy);
256     }
257
258     @Override
259     public LegacyOperationalPolicy updateOperationalPolicy(
260             @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException {
261         assertInitialized();
262         return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy);
263     }
264
265     @Override
266     public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId,
267             @NonNull final String policyVersion) throws PfModelException {
268         assertInitialized();
269
270         assertPolicyNotDeployedInPdpGroup(
271                 new ToscaPolicyIdentifier(policyId, policyVersion + LegacyProvider.LEGACY_MINOR_PATCH_SUFFIX));
272
273         return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId, policyVersion);
274     }
275
276     @Override
277     public List<PdpGroup> getPdpGroups(final String name) throws PfModelException {
278         assertInitialized();
279         return new PdpProvider().getPdpGroups(pfDao, name);
280     }
281
282     @Override
283     public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
284         assertInitialized();
285         return new PdpProvider().getFilteredPdpGroups(pfDao, filter);
286     }
287
288     @Override
289     public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
290         assertInitialized();
291         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
292     }
293
294     @Override
295     public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
296         assertInitialized();
297         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
298     }
299
300     @Override
301     public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup)
302             throws PfModelException {
303         assertInitialized();
304         new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpSubGroup);
305     }
306
307     @Override
308     public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp)
309             throws PfModelException {
310         new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpSubGroup, pdp);
311     }
312
313     @Override
314     public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException {
315         assertInitialized();
316         return new PdpProvider().deletePdpGroup(pfDao, name);
317     }
318
319     @Override
320     public List<PdpStatistics> getPdpStatistics(final String name, final Date timestamp) throws PfModelException {
321         assertInitialized();
322         return new PdpStatisticsProvider().getPdpStatistics(pfDao, name, timestamp);
323     }
324
325     @Override
326     public List<PdpStatistics> getFilteredPdpStatistics(final String name, @NonNull final String pdpGroupName,
327             final String pdpSubGroup, final Date startTimeStamp, final Date endTimeStamp, final String sortOrder,
328             final int getRecordNum) throws PfModelException {
329         assertInitialized();
330         return new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, name, pdpGroupName, pdpSubGroup,
331                 startTimeStamp, endTimeStamp, sortOrder, getRecordNum);
332     }
333
334     @Override
335     public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
336             throws PfModelException {
337         assertInitialized();
338         return new PdpStatisticsProvider().createPdpStatistics(pfDao, pdpStatisticsList);
339     }
340
341     @Override
342     public List<PdpStatistics> updatePdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
343             throws PfModelException {
344         assertInitialized();
345         return new PdpStatisticsProvider().updatePdpStatistics(pfDao, pdpStatisticsList);
346     }
347
348     @Override
349     public List<PdpStatistics> deletePdpStatistics(@NonNull final String name, final Date timestamp)
350             throws PfModelException {
351         assertInitialized();
352         return new PdpStatisticsProvider().deletePdpStatistics(pfDao, name, timestamp);
353     }
354
355     /**
356      * Check if the model provider is initialized.
357      */
358     private void assertInitialized() {
359         if (pfDao == null) {
360             String errorMessage = "policy models provider is not initilaized";
361             LOGGER.warn(errorMessage);
362             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
363         }
364     }
365
366     /**
367      * Assert that the policy type is not supported in any PDP group.
368      *
369      * @param policyTypeIdentifier the policy type identifier
370      * @throws PfModelException if the policy type is supported in a PDP group
371      */
372     private void assertPolicyTypeNotSupportedInPdpGroup(ToscaPolicyTypeIdentifier policyTypeIdentifier)
373             throws PfModelException {
374         for (PdpGroup pdpGroup : getPdpGroups(null)) {
375             for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
376                 if (pdpSubGroup.getSupportedPolicyTypes().contains(policyTypeIdentifier)) {
377                     throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
378                             "policy type is in use, it is referenced in PDP group " + pdpGroup.getName() + " subgroup "
379                                     + pdpSubGroup.getPdpType());
380                 }
381             }
382         }
383     }
384
385     /**
386      * Assert that the policy is not deployed in a PDP group.
387      *
388      * @param policyIdentifier the identifier of the policy
389      * @throws PfModelException thrown if the policy is deployed in a PDP group
390      */
391     private void assertPolicyNotDeployedInPdpGroup(final ToscaPolicyIdentifier policyIdentifier)
392             throws PfModelException {
393         for (PdpGroup pdpGroup : getPdpGroups(null)) {
394             for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
395                 if (pdpSubGroup.getPolicies().contains(policyIdentifier)) {
396                     throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
397                             "policy is in use, it is deployed in PDP group " + pdpGroup.getName() + " subgroup "
398                                     + pdpSubGroup.getPdpType());
399                 }
400             }
401         }
402     }
403 }