update Db provider to support query number
[policy/models.git] / models-pdp / src / main / java / org / onap / policy / models / pdp / persistence / provider / PdpStatisticsProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Model
4  * ================================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation.
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.pdp.persistence.provider;
24
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.stream.Collectors;
31 import javax.ws.rs.core.Response;
32 import lombok.NonNull;
33 import org.onap.policy.models.base.PfKey;
34 import org.onap.policy.models.base.PfModelException;
35 import org.onap.policy.models.base.PfModelRuntimeException;
36 import org.onap.policy.models.base.PfTimestampKey;
37 import org.onap.policy.models.base.PfValidationResult;
38 import org.onap.policy.models.dao.PfDao;
39 import org.onap.policy.models.pdp.concepts.PdpStatistics;
40 import org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44
45 /**
46  * This class provides the provision of information on PAP concepts in the database to callers.
47  *
48  * @author Ning Xi (ning.xi@est.tech)
49  */
50 public class PdpStatisticsProvider {
51     private static final Logger LOGGER = LoggerFactory.getLogger(PdpStatisticsProvider.class);
52
53     // Recurring string constants
54     private static final String NOT_VALID = "\" is not valid \n";
55     private static final String DESC_ORDER = "DESC";
56
57     /**
58      * Get PDP statistics.
59      *
60      * @param dao the DAO to use to access the database
61      * @param name the name of the PDP statistics to get, null to get all PDPs
62      * @return the PDP statistics found
63      * @throws PfModelException on errors getting PDP statistics
64      */
65     public List<PdpStatistics> getPdpStatistics(@NonNull final PfDao dao, final String name, final Date timestamp)
66             throws PfModelException {
67
68         List<PdpStatistics> pdpStatistics = new ArrayList<>();
69         if (name != null) {
70             pdpStatistics
71                     .add(dao.get(JpaPdpStatistics.class, new PfTimestampKey(name, PfKey.NULL_KEY_VERSION, timestamp))
72                             .toAuthorative());
73         } else {
74             return asPdpStatisticsList(dao.getAll(JpaPdpStatistics.class));
75         }
76         return pdpStatistics;
77     }
78
79     /**
80      * Get filtered PDP statistics.
81      *
82      * @param dao the DAO to use to access the database
83      * @param name the pdpInstance name for the PDP statistics to get
84      * @param pdpGroupName pdpGroupName to filter statistics
85      * @param pdpSubGroup pdpSubGroupType name to filter statistics
86      * @param startTimeStamp startTimeStamp to filter statistics
87      * @param endTimeStamp endTimeStamp to filter statistics
88      * @param sortOrder sortOrder to query database
89      * @param getRecordNum Total query count from database
90      * @return the PDP statistics found
91      * @throws PfModelException on errors getting policies
92      */
93     public List<PdpStatistics> getFilteredPdpStatistics(@NonNull final PfDao dao, final String name,
94             @NonNull final String pdpGroupName, final String pdpSubGroup, final Date startTimeStamp,
95             final Date endTimeStamp, final String sortOrder, final int getRecordNum) {
96         Map<String, Object> filterMap = new HashMap<>();
97         filterMap.put("pdpGroupName", pdpGroupName);
98         if (pdpSubGroup != null) {
99             filterMap.put("pdpSubGroupName", pdpSubGroup);
100         }
101
102         return asPdpStatisticsList(dao.getFiltered(JpaPdpStatistics.class, name, PfKey.NULL_KEY_VERSION, startTimeStamp,
103                 endTimeStamp, filterMap, sortOrder, getRecordNum));
104     }
105
106     /**
107      * Creates PDP statistics.
108      *
109      * @param dao the DAO to use to access the database
110      * @param pdpStatisticsList a specification of the PDP statistics to create
111      * @return the PDP statistics created
112      * @throws PfModelException on errors creating PDP statistics
113      */
114     public List<PdpStatistics> createPdpStatistics(@NonNull final PfDao dao,
115             @NonNull final List<PdpStatistics> pdpStatisticsList) throws PfModelException {
116
117         for (PdpStatistics pdpStatistics : pdpStatisticsList) {
118             JpaPdpStatistics jpaPdpStatistics = new JpaPdpStatistics();
119             jpaPdpStatistics.fromAuthorative(pdpStatistics);
120
121             PfValidationResult validationResult = jpaPdpStatistics.validate(new PfValidationResult());
122             if (!validationResult.isOk()) {
123                 String errorMessage = "pdp statictics \"" + jpaPdpStatistics.getName() + NOT_VALID + validationResult;
124                 LOGGER.warn(errorMessage);
125                 throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
126             }
127
128             dao.create(jpaPdpStatistics);
129         }
130
131         // Return the created PDP statistics
132         List<PdpStatistics> pdpStatistics = new ArrayList<>(pdpStatisticsList.size());
133
134         for (PdpStatistics pdpStatisticsItem : pdpStatisticsList) {
135             JpaPdpStatistics jpaPdpStatistics =
136                     dao.get(JpaPdpStatistics.class, new PfTimestampKey(pdpStatisticsItem.getPdpInstanceId(),
137                             PfKey.NULL_KEY_VERSION, pdpStatisticsItem.getTimeStamp()));
138             pdpStatistics.add(jpaPdpStatistics.toAuthorative());
139         }
140
141         return pdpStatistics;
142     }
143
144     /**
145      * Updates PDP statistics.
146      *
147      * @param dao the DAO to use to access the database
148      * @param pdpStatisticsList a specification of the PDP statistics to update
149      * @return the PDP statistics updated
150      * @throws PfModelException on errors updating PDP statistics
151      */
152     public List<PdpStatistics> updatePdpStatistics(@NonNull final PfDao dao,
153             @NonNull final List<PdpStatistics> pdpStatisticsList) throws PfModelException {
154
155         for (PdpStatistics pdpStatistics : pdpStatisticsList) {
156             JpaPdpStatistics jpaPdpStatistics = new JpaPdpStatistics();
157             jpaPdpStatistics.fromAuthorative(pdpStatistics);
158
159             PfValidationResult validationResult = jpaPdpStatistics.validate(new PfValidationResult());
160             if (!validationResult.isOk()) {
161                 String errorMessage = "pdp statistics \"" + jpaPdpStatistics.getId() + NOT_VALID + validationResult;
162                 LOGGER.warn(errorMessage);
163                 throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
164             }
165
166             dao.update(jpaPdpStatistics);
167         }
168
169         // Return the created PDP statistics
170         List<PdpStatistics> pdpStatistics = new ArrayList<>(pdpStatisticsList.size());
171
172         for (PdpStatistics pdpStatisticsItem : pdpStatisticsList) {
173             JpaPdpStatistics jpaPdpStatistics =
174                     dao.get(JpaPdpStatistics.class, new PfTimestampKey(pdpStatisticsItem.getPdpInstanceId(),
175                             PfKey.NULL_KEY_VERSION, pdpStatisticsItem.getTimeStamp()));
176             pdpStatistics.add(jpaPdpStatistics.toAuthorative());
177         }
178
179         return pdpStatistics;
180     }
181
182     /**
183      * Delete a PDP statistics.
184      *
185      * @param dao the DAO to use to access the database
186      * @param name the name of the policy to get, null to get all PDP statistics
187      * @param timestamp the timeStamp of statistics to delete, null to delete all statistics record of given PDP
188      * @return the PDP statistics list deleted
189      * @throws PfModelException on errors deleting PDP statistics
190      */
191     public List<PdpStatistics> deletePdpStatistics(@NonNull final PfDao dao, @NonNull final String name,
192             final Date timestamp) {
193         List<PdpStatistics> pdpStatisticsListToDel = asPdpStatisticsList(dao.getFiltered(JpaPdpStatistics.class, name,
194                 PfKey.NULL_KEY_VERSION, timestamp, timestamp, null, DESC_ORDER, 0));
195
196         pdpStatisticsListToDel.stream().forEach(s -> dao.delete(JpaPdpStatistics.class,
197                 new PfTimestampKey(s.getPdpInstanceId(), PfKey.NULL_KEY_VERSION, s.getTimeStamp())));
198
199         return pdpStatisticsListToDel;
200     }
201
202     /**
203      * Convert JPA PDP statistics list to an PDP statistics list.
204      *
205      * @param jpaPdpStatisticsList the list to convert
206      * @return the PDP statistics list
207      */
208     private List<PdpStatistics> asPdpStatisticsList(List<JpaPdpStatistics> jpaPdpStatisticsList) {
209         return jpaPdpStatisticsList.stream().map(JpaPdpStatistics::toAuthorative).collect(Collectors.toList());
210     }
211 }