Change to fix SQLInvalidAuthorizationSpecException
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / operationshistory / CountRecentOperationsPip.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
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.pdp.xacml.application.common.operationshistory;
22
23 import com.att.research.xacml.api.XACML3;
24 import com.att.research.xacml.api.pip.PIPException;
25 import com.att.research.xacml.api.pip.PIPFinder;
26 import com.att.research.xacml.api.pip.PIPRequest;
27 import com.att.research.xacml.api.pip.PIPResponse;
28 import com.att.research.xacml.std.pip.StdMutablePIPResponse;
29 import com.att.research.xacml.std.pip.StdPIPResponse;
30 import com.google.common.base.Strings;
31
32 import java.sql.Timestamp;
33 import java.time.Instant;
34 import java.time.temporal.ChronoUnit;
35 import java.util.Arrays;
36 import java.util.Base64;
37 import java.util.Collection;
38 import java.util.Properties;
39
40 import javax.persistence.Persistence;
41
42 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
43 import org.onap.policy.pdp.xacml.application.common.std.StdOnapPip;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47
48 public class CountRecentOperationsPip extends StdOnapPip {
49     public static final String ISSUER_NAME = "count-recent-operations";
50     private static Logger logger = LoggerFactory.getLogger(CountRecentOperationsPip.class);
51
52     public CountRecentOperationsPip() {
53         super();
54     }
55
56     @Override
57     public Collection<PIPRequest> attributesRequired() {
58         return Arrays.asList(PIP_REQUEST_ACTOR, PIP_REQUEST_RECIPE, PIP_REQUEST_TARGET);
59     }
60
61     @Override
62     public void configure(String id, Properties properties) throws PIPException {
63         super.configure(id, properties);
64         //
65         // Create our entity manager
66         //
67         em = null;
68         try {
69             //
70             // In case there are any overloaded properties for the JPA
71             //
72             Properties emProperties = new Properties();
73             emProperties.putAll(properties);
74
75             //
76             // Need to decode the password before creating the EntityManager
77             //
78             String decodedPassword = new String(Base64.getDecoder()
79                     .decode(emProperties.getProperty("javax.persistence.jdbc.password")));
80             emProperties.setProperty("javax.persistence.jdbc.password", decodedPassword);
81
82             //
83             // Create the entity manager factory
84             //
85             em = Persistence.createEntityManagerFactory(
86                     properties.getProperty(ISSUER_NAME + ".persistenceunit"),
87                     emProperties).createEntityManager();
88         } catch (Exception e) {
89             logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e);
90         }
91     }
92
93     /**
94      * getAttributes.
95      *
96      * @param pipRequest the request
97      * @param pipFinder the pip finder
98      * @return PIPResponse
99      */
100     @Override
101     public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
102         logger.debug("getAttributes requesting attribute {} of type {} for issuer {}",
103                 pipRequest.getAttributeId(), pipRequest.getDataTypeId(), pipRequest.getIssuer());
104         //
105         // Determine if the issuer is correct
106         //
107         if (Strings.isNullOrEmpty(pipRequest.getIssuer())) {
108             logger.debug("issuer is null - returning empty response");
109             //
110             // We only respond to ourself as the issuer
111             //
112             return StdPIPResponse.PIP_RESPONSE_EMPTY;
113         }
114         if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) {
115             logger.debug("Issuer does not start with guard");
116             //
117             // We only respond to ourself as the issuer
118             //
119             return StdPIPResponse.PIP_RESPONSE_EMPTY;
120         }
121         //
122         // Parse out the issuer which denotes the time window
123         // Eg: any-prefix:tw:10:minute
124         //
125         String[] s1 = pipRequest.getIssuer().split("tw:");
126         String[] s2 = s1[1].split(":");
127         int timeWindowVal = Integer.parseInt(s2[0]);
128         String timeWindowScale = s2[1];
129         //
130         // Grab other attribute values
131         //
132         String actor = getAttribute(pipFinder, PIP_REQUEST_ACTOR);
133         String operation = getAttribute(pipFinder, PIP_REQUEST_RECIPE);
134         String target = getAttribute(pipFinder, PIP_REQUEST_TARGET);
135         String timeWindow = timeWindowVal + " " + timeWindowScale;
136         logger.info("Going to query DB about: actor {} operation {} target {} time window {}",
137                 actor, operation, target, timeWindow);
138         //
139         // Sanity check
140         //
141         if (actor == null || operation == null || target == null) {
142             //
143             // See if we have all the values
144             //
145             logger.error("missing attributes return empty");
146             return StdPIPResponse.PIP_RESPONSE_EMPTY;
147         }
148         //
149         // Ok do the database query
150         //
151         long operationCount = doDatabaseQuery(actor, operation, target, timeWindowVal, timeWindowScale);
152         //
153         // Create and return PipResponse
154         //
155         StdMutablePIPResponse pipResponse    = new StdMutablePIPResponse();
156         this.addLongAttribute(pipResponse,
157                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE,
158                 ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONCOUNT,
159                 operationCount,
160                 pipRequest);
161         return new StdPIPResponse(pipResponse);
162     }
163
164     private long doDatabaseQuery(String actor, String operation, String target, int timeWindowVal,
165             String timeWindowScale) {
166         logger.info("Querying operations history for {} {} {} {} {}",
167                 actor, operation, target, timeWindowVal, timeWindowScale);
168         //
169         // Only can query if we have an EntityManager
170         //
171         if (em == null) {
172             logger.error("No EntityManager available");
173             return -1;
174         }
175         //
176         // Do the query
177         //
178         try {
179             //
180             // We are expecting a single result
181             //
182             return em.createQuery("select count(e) from Dbao e"
183                                   + " where e.outcome<>'Failure_Guard'"
184                                   + " and e.actor= ?1"
185                                   + " and e.operation= ?2"
186                                   + " and e.target= ?3"
187                                   + " and e.endtime between"
188                                   + " ?4 and CURRENT_TIMESTAMP",
189                                   Long.class)
190                 .setParameter(1, actor)
191                 .setParameter(2, operation)
192                 .setParameter(3, target)
193                 .setParameter(4, Timestamp.from(Instant.now()
194                                                 .minus(timeWindowVal,
195                                                        stringToChronoUnit(timeWindowScale))))
196                 .getSingleResult();
197         } catch (Exception e) {
198             logger.error("Typed query failed ", e);
199             return -1;
200         }
201     }
202
203     private ChronoUnit stringToChronoUnit(String scale) {
204         //
205         // Compute the time window
206         //
207         switch (scale.toLowerCase()) {
208             case "second":
209                 return ChronoUnit.SECONDS;
210             case "minute":
211                 return ChronoUnit.MINUTES;
212             case "hour":
213                 return ChronoUnit.HOURS;
214             case "day":
215                 return ChronoUnit.DAYS;
216             case "week":
217                 return ChronoUnit.WEEKS;
218             case "month":
219                 return ChronoUnit.MONTHS;
220             case "year":
221                 return ChronoUnit.YEARS;
222             default:
223                 //
224                 // Unsupported
225                 //
226                 logger.error("Unsupported time window scale value {}", scale);
227         }
228         return null;
229     }
230
231 }