e27b9a43c3b853a7bfbb9ddd398c0716f316f263
[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  *  Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.models.provider.impl;
24
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.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
59  * a relational database.
60  *
61  * @author Liam Fallon (liam.fallon@est.tech)
62  */
63 public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider {
64
65     private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderImpl.class);
66
67     private final PolicyModelsProviderParameters parameters;
68
69     // Database connection and the DAO for reading and writing Policy Framework concepts
70     private PfDao pfDao;
71
72     /**
73      * Constructor that takes the parameters.
74      *
75      * @param parameters the parameters for the provider
76      */
77     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
78         this.parameters = parameters;
79     }
80
81     @Override
82     public void init() throws PfModelException {
83         LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
84                 parameters.getPersistenceUnit());
85
86         if (pfDao != null) {
87             String errorMessage = "provider is already initialized";
88             LOGGER.warn(errorMessage);
89             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
90         }
91
92         // Parameters for the DAO
93         final DaoParameters daoParameters = new DaoParameters();
94         daoParameters.setPluginClass(DefaultPfDao.class.getName());
95         daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
96
97         // @formatter:off
98         Properties jdbcProperties = new Properties();
99         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
100         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
101         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
102         jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, parameters.getDatabasePassword());
103         // @formatter:on
104
105         daoParameters.setJdbcProperties(jdbcProperties);
106
107         try {
108             pfDao = new PfDaoFactory().createPfDao(daoParameters);
109             pfDao.init(daoParameters);
110         } catch (Exception exc) {
111             String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
112                     + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
113
114             this.close();
115             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
116         }
117     }
118
119     @Override
120     public void close() throws PfModelException {
121         LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
122                 parameters.getPersistenceUnit());
123
124         if (pfDao != null) {
125             pfDao.close();
126             pfDao = null;
127         }
128
129         LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
130                 parameters.getPersistenceUnit());
131     }
132
133     @Override
134     public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
135         assertInitialized();
136         return new AuthorativeToscaProvider().getPolicyTypes(pfDao, name, version);
137     }
138
139     @Override
140     public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
141         assertInitialized();
142         return new AuthorativeToscaProvider().getPolicyTypeList(pfDao, name, version);
143     }
144
145     @Override
146     public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaPolicyTypeFilter filter) throws PfModelException {
147         assertInitialized();
148         return new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, filter);
149     }
150
151     @Override
152     public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaPolicyTypeFilter filter)
153             throws PfModelException {
154         assertInitialized();
155         return new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, filter);
156     }
157
158     @Override
159     public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
160             throws PfModelException {
161         assertInitialized();
162         return new AuthorativeToscaProvider().createPolicyTypes(pfDao, serviceTemplate);
163     }
164
165     @Override
166     public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
167             throws PfModelException {
168         assertInitialized();
169         return new AuthorativeToscaProvider().updatePolicyTypes(pfDao, serviceTemplate);
170     }
171
172     @Override
173     public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
174             throws PfModelException {
175         assertInitialized();
176
177         ToscaPolicyTypeIdentifier policyTypeIdentifier = new ToscaPolicyTypeIdentifier(name, version);
178         assertPolicyTypeNotSupportedInPdpGroup(policyTypeIdentifier);
179
180         return new AuthorativeToscaProvider().deletePolicyType(pfDao, name, version);
181     }
182
183     @Override
184     public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
185         assertInitialized();
186         return new AuthorativeToscaProvider().getPolicies(pfDao, name, version);
187     }
188
189     @Override
190     public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
191         assertInitialized();
192         return new AuthorativeToscaProvider().getPolicyList(pfDao, name, version);
193     }
194
195     @Override
196     public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaPolicyFilter filter) throws PfModelException {
197         assertInitialized();
198         return new AuthorativeToscaProvider().getFilteredPolicies(pfDao, filter);
199     }
200
201     @Override
202     public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaPolicyFilter filter) throws PfModelException {
203         assertInitialized();
204         return new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, filter);
205     }
206
207     @Override
208     public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
209             throws PfModelException {
210         assertInitialized();
211         return new AuthorativeToscaProvider().createPolicies(pfDao, serviceTemplate);
212     }
213
214     @Override
215     public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
216             throws PfModelException {
217         assertInitialized();
218         return new AuthorativeToscaProvider().updatePolicies(pfDao, serviceTemplate);
219     }
220
221     @Override
222     public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
223             throws PfModelException {
224         assertInitialized();
225
226         ToscaPolicyIdentifier policyIdentifier = new ToscaPolicyIdentifier(name, version);
227         assertPolicyNotDeployedInPdpGroup(policyIdentifier);
228
229         return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version);
230     }
231
232     @Override
233     public List<PdpGroup> getPdpGroups(final String name) throws PfModelException {
234         assertInitialized();
235         return new PdpProvider().getPdpGroups(pfDao, name);
236     }
237
238     @Override
239     public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
240         assertInitialized();
241         return new PdpProvider().getFilteredPdpGroups(pfDao, filter);
242     }
243
244     @Override
245     public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
246         assertInitialized();
247         return new PdpProvider().createPdpGroups(pfDao, pdpGroups);
248     }
249
250     @Override
251     public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
252         assertInitialized();
253         return new PdpProvider().updatePdpGroups(pfDao, pdpGroups);
254     }
255
256     @Override
257     public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup)
258             throws PfModelException {
259         assertInitialized();
260         new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpSubGroup);
261     }
262
263     @Override
264     public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp)
265             throws PfModelException {
266         new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpSubGroup, pdp);
267     }
268
269     @Override
270     public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException {
271         assertInitialized();
272         return new PdpProvider().deletePdpGroup(pfDao, name);
273     }
274
275     @Override
276     public List<PdpStatistics> getPdpStatistics(final String name, final Date timestamp) throws PfModelException {
277         assertInitialized();
278         return new PdpStatisticsProvider().getPdpStatistics(pfDao, name, timestamp);
279     }
280
281     @Override
282     public List<PdpStatistics> getFilteredPdpStatistics(final String name, @NonNull final String pdpGroupName,
283             final String pdpSubGroup, final Date startTimeStamp, final Date endTimeStamp, final String sortOrder,
284             final int getRecordNum) throws PfModelException {
285         assertInitialized();
286         return new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, name, pdpGroupName, pdpSubGroup,
287                 startTimeStamp, endTimeStamp, sortOrder, getRecordNum);
288     }
289
290     @Override
291     public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
292             throws PfModelException {
293         assertInitialized();
294         return new PdpStatisticsProvider().createPdpStatistics(pfDao, pdpStatisticsList);
295     }
296
297     @Override
298     public List<PdpStatistics> updatePdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
299             throws PfModelException {
300         assertInitialized();
301         return new PdpStatisticsProvider().updatePdpStatistics(pfDao, pdpStatisticsList);
302     }
303
304     @Override
305     public List<PdpStatistics> deletePdpStatistics(@NonNull final String name, final Date timestamp)
306             throws PfModelException {
307         assertInitialized();
308         return new PdpStatisticsProvider().deletePdpStatistics(pfDao, name, timestamp);
309     }
310
311     /**
312      * Check if the model provider is initialized.
313      */
314     private void assertInitialized() {
315         if (pfDao == null) {
316             String errorMessage = "policy models provider is not initilaized";
317             LOGGER.warn(errorMessage);
318             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
319         }
320     }
321
322     /**
323      * Assert that the policy type is not supported in any PDP group.
324      *
325      * @param policyTypeIdentifier the policy type identifier
326      * @throws PfModelException if the policy type is supported in a PDP group
327      */
328     private void assertPolicyTypeNotSupportedInPdpGroup(ToscaPolicyTypeIdentifier policyTypeIdentifier)
329             throws PfModelException {
330         for (PdpGroup pdpGroup : getPdpGroups(null)) {
331             for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
332                 if (pdpSubGroup.getSupportedPolicyTypes().contains(policyTypeIdentifier)) {
333                     throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
334                             "policy type is in use, it is referenced in PDP group " + pdpGroup.getName() + " subgroup "
335                                     + pdpSubGroup.getPdpType());
336                 }
337             }
338         }
339     }
340
341     /**
342      * Assert that the policy is not deployed in a PDP group.
343      *
344      * @param policyIdentifier the identifier of the policy
345      * @throws PfModelException thrown if the policy is deployed in a PDP group
346      */
347     private void assertPolicyNotDeployedInPdpGroup(final ToscaPolicyIdentifier policyIdentifier)
348             throws PfModelException {
349         for (PdpGroup pdpGroup : getPdpGroups(null)) {
350             for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
351                 if (pdpSubGroup.getPolicies().contains(policyIdentifier)) {
352                     throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
353                             "policy is in use, it is deployed in PDP group " + pdpGroup.getName() + " subgroup "
354                                     + pdpSubGroup.getPdpType());
355                 }
356             }
357         }
358     }
359 }