[POLICY-22] Reorganizing drools-apps
[policy/drools-applications.git] / controlloop / common / guard / src / main / java / org / onap / policy / guard / PIPEngineGetHistory.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * guard
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.guard;
22
23 import java.math.BigInteger;
24 import java.util.Collection;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.Properties;
28 import java.util.Set;
29
30 import javax.persistence.EntityManager;
31 import javax.persistence.Persistence;
32 import javax.persistence.Query;
33
34 import com.att.research.xacml.api.pip.PIPException;
35 import com.att.research.xacml.api.pip.PIPFinder;
36 import com.att.research.xacml.api.pip.PIPRequest;
37 import com.att.research.xacml.api.pip.PIPResponse;
38 import com.att.research.xacml.std.IdentifierImpl;
39 import com.att.research.xacml.std.StdMutableAttribute;
40 import com.att.research.xacml.std.pip.StdMutablePIPResponse;
41 import com.att.research.xacml.std.pip.StdPIPRequest;
42 import com.att.research.xacml.std.pip.StdPIPResponse;
43 import com.att.research.xacml.std.pip.engines.StdConfigurableEngine;
44 import com.att.research.xacml.api.Attribute;
45 import com.att.research.xacml.api.AttributeValue;
46 import com.att.research.xacml.api.Identifier;
47 import com.att.research.xacml.std.datatypes.DataTypes;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50
51
52
53 public class PIPEngineGetHistory extends StdConfigurableEngine{
54
55         private Log logger                                                      = LogFactory.getLog(this.getClass());
56         
57         //private static EntityManager em;
58         
59         public static final String DEFAULT_DESCRIPTION          = "PIP for retrieving Operations History from DB";
60         
61         //
62         // Base issuer string. The issuer in the policy will also contain time window information
63         // E.g., "com:att:research:xacml:guard:historydb:tw:10:min"
64         //
65         public static final String DEFAULT_ISSUER                       = "com:att:research:xacml:guard:historydb";
66
67         
68         private static final PIPRequest PIP_REQUEST_ACTOR       = new StdPIPRequest(
69                                         new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"), 
70                                         new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:actor:actor-id"), 
71                                         new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string"));
72         
73         private static final PIPRequest PIP_REQUEST_RECIPE              = new StdPIPRequest(
74                                         new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:action"), 
75                                         new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:operation:operation-id"), 
76                                         new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string"));
77         
78         private static final PIPRequest PIP_REQUEST_TARGET              = new StdPIPRequest(
79                         new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"), 
80                         new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:target:target-id"), 
81                         new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string"));
82
83         
84         private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) {
85                 AttributeValue<BigInteger> attributeValue       = null;
86                 try {
87                         attributeValue  = DataTypes.DT_INTEGER.createAttributeValue(value);
88                 } catch (Exception ex) {
89                         this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex);
90                 }
91                 if (attributeValue != null) {
92                         stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false));
93                 }
94         }
95
96         
97         
98         public PIPEngineGetHistory() {
99                 super();
100                 
101                 System.out.println("HAHAHAHAHAHAHAHAHAHAHAHAHAHAHA");
102                 
103                 // TODO Auto-generated constructor stub
104         }
105         
106         
107
108         @Override
109         public Collection<PIPRequest> attributesRequired() {
110                 // TODO Auto-generated method stub
111                 System.out.println("DADADADADADADADADADADADADA");
112                 return null;
113         }
114
115         @Override
116         public Collection<PIPRequest> attributesProvided() {
117                 // TODO Auto-generated method stub
118                 System.out.println("GAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAG");
119                 return null;
120         }
121
122         @Override
123         public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
124                 // TODO Auto-generated method stub
125                 System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Entering FeqLimiter PIP!!!");
126                 
127                 /*
128                  * First check to see if the issuer is set and then match it
129                  */
130                 String string;
131                 if ((string = pipRequest.getIssuer()) == null) {
132                         this.logger.debug("No issuer in the request...");
133                         System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - No issuer in the request!!!");
134                         return StdPIPResponse.PIP_RESPONSE_EMPTY;
135                 }
136                 else{
137                         //Notice, we are checking here for the base issuer prefix.
138                         if (!string.contains(this.getIssuer())) {
139                                 this.logger.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'"));
140                                 System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - Issuer "+ string +" does not match with: "+this.getIssuer());
141                                 return StdPIPResponse.PIP_RESPONSE_EMPTY;
142                         }
143                 }
144                 
145                 String[] s1 = string.split("tw:");
146                 String[] s2 = s1[1].split(":");
147                 String timeWindowVal = s2[0];// number [of minutes, hours, days...]
148                 String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year
149                 
150                 //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - Issuer " + string + " is OK - proceeding with the request!!!");
151                 //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - TimeWindow: " + timeWindowVal + " " + timeWindowScale);
152
153                 String actor = getActor(pipFinder).iterator().next();
154                 String operation = getRecipe(pipFinder).iterator().next();
155                 String target = getTarget(pipFinder).iterator().next();
156         
157                 String timeWindow = timeWindowVal + " " + timeWindowScale;
158                 
159                 System.out.println("Going to query DB about: "+actor + " " + operation + " " + target + " " + timeWindow);
160                 int countFromDB = getCountFromDB(actor, operation, target, timeWindow);
161                  
162                 
163                 StdMutablePIPResponse stdPIPResponse    = new StdMutablePIPResponse();
164                 
165                 this.addIntegerAttribute(stdPIPResponse,
166                                 new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"), 
167                                 new IdentifierImpl("com:att:research:xacml:test:sql:resource:operations:count"), 
168                                 countFromDB,
169                                 pipRequest);
170                 
171                 return new StdPIPResponse(stdPIPResponse);
172         }
173         
174         
175         @Override
176         public void configure(String id, Properties properties) throws PIPException {
177                 super.configure(id, properties);
178                 //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Configuring FeqLimiter PIP!!!");
179                 if (this.getDescription() == null) {
180                         this.setDescription(DEFAULT_DESCRIPTION);
181                 }
182                 if (this.getIssuer() == null) {
183                         this.setIssuer(DEFAULT_ISSUER);
184                 }
185                 /*
186                 try{
187                         em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
188                 }catch(Exception e){
189                         System.err.println("Freq limiter PIP got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.");
190                         return;
191                 }
192                 */
193                 
194         }
195
196         
197         
198         private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
199                 PIPResponse pipResponse = null;
200
201                 try {
202                         pipResponse     = pipFinder.getMatchingAttributes(pipRequest, this);
203                         if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) {
204                                 System.out.println("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString());
205                                 pipResponse     = null;
206                         }
207                         if (pipResponse.getAttributes().size() == 0) {
208                                 System.out.println("No value for " + pipRequest.getAttributeId().stringValue());
209                                 pipResponse     = null;
210                         }
211                 } catch (PIPException ex) {
212                         System.out.println("PIPException getting subject-id attribute: " + ex.getMessage());                    
213                 }
214                 return pipResponse;
215         }
216         
217         
218         private Set<String> getActor(PIPFinder pipFinder) {
219                 /*
220                  * Get the AT&T UID from either the subject id or the attuid property
221                  */
222                 PIPResponse pipResponseATTUID   = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder);
223                 if (pipResponseATTUID == null) {
224                         return null;
225                 }
226                 
227                 /*
228                  * Iterate over all of the returned results and do the LDAP requests
229                  */
230                 Collection<Attribute> listATTUIDs       = pipResponseATTUID.getAttributes();
231                 Set<String> setATTUIDs                  = new HashSet<String>();
232                 for (Attribute attributeATTUID: listATTUIDs) {
233                         Iterator<AttributeValue<String>> iterAttributeValues    = attributeATTUID.findValues(DataTypes.DT_STRING);
234                         if (iterAttributeValues != null) {
235                                 while (iterAttributeValues.hasNext()) {
236                                         String attuid   = iterAttributeValues.next().getValue();
237                                         if (attuid != null) {
238                                                 setATTUIDs.add(attuid);
239                                         }
240                                 }
241                         }
242                 }
243                 
244                 return setATTUIDs;
245         }
246
247         private Set<String> getRecipe(PIPFinder pipFinder) {
248                 /*
249                  * Get the AT&T UID from either the subject id or the attuid property
250                  */
251                 PIPResponse pipResponseATTUID   = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder);
252                 if (pipResponseATTUID == null) {
253                         return null;
254                 }
255                 
256                 /*
257                  * Iterate over all of the returned results and do the LDAP requests
258                  */
259                 Collection<Attribute> listATTUIDs       = pipResponseATTUID.getAttributes();
260                 Set<String> setATTUIDs                  = new HashSet<String>();
261                 for (Attribute attributeATTUID: listATTUIDs) {
262                         Iterator<AttributeValue<String>> iterAttributeValues    = attributeATTUID.findValues(DataTypes.DT_STRING);
263                         if (iterAttributeValues != null) {
264                                 while (iterAttributeValues.hasNext()) {
265                                         String attuid   = iterAttributeValues.next().getValue();
266                                         if (attuid != null) {
267                                                 setATTUIDs.add(attuid);
268                                         }
269                                 }
270                         }
271                 }
272                 
273                 return setATTUIDs;
274         }
275         
276         
277         private Set<String> getTarget(PIPFinder pipFinder) {
278                 /*
279                  * Get the AT&T UID from either the subject id or the attuid property
280                  */
281                 PIPResponse pipResponseATTUID   = this.getAttribute(PIP_REQUEST_TARGET, pipFinder);
282                 if (pipResponseATTUID == null) {
283                         return null;
284                 }
285                 
286                 /*
287                  * Iterate over all of the returned results and do the LDAP requests
288                  */
289                 Collection<Attribute> listATTUIDs       = pipResponseATTUID.getAttributes();
290                 Set<String> setATTUIDs                  = new HashSet<String>();
291                 for (Attribute attributeATTUID: listATTUIDs) {
292                         Iterator<AttributeValue<String>> iterAttributeValues    = attributeATTUID.findValues(DataTypes.DT_STRING);
293                         if (iterAttributeValues != null) {
294                                 while (iterAttributeValues.hasNext()) {
295                                         String attuid   = iterAttributeValues.next().getValue();
296                                         if (attuid != null) {
297                                                 setATTUIDs.add(attuid);
298                                         }
299                                 }
300                         }
301                 }
302                 
303                 return setATTUIDs;
304         }
305         
306         private static int getCountFromDB(String actor, String operation, String target, String timeWindow){
307                 
308                 long startTime = System.nanoTime();
309         
310                 
311                 
312                 EntityManager em;
313                 try{
314                         em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
315                 }catch(Exception e){
316                         System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB.");
317                         return -1;
318                 }
319                 
320                 
321                 //em.getTransaction().begin();
322                 String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor='"
323                                 + actor
324                                 + "' and operation='"
325                                 + operation
326                                 + "' and target='"
327                                 + target
328                                 + "' "
329                                 + "and endtime between date_sub(now(),interval "
330                                 + timeWindow
331                                 + ") and now()";
332                 
333                 Query nq = em.createNativeQuery(sql);
334                 
335                 int ret = ((Number)nq.getSingleResult()).intValue();
336
337                 System.out.println("###########************** History count: " + ret);
338                 
339                 //em.getTransaction().commit();
340                 long estimatedTime = System.nanoTime() - startTime;
341                 System.out.println("time took: " + (double)estimatedTime/1000/1000 + " mili sec.");
342
343                 em.close();
344                 
345                 return ret;
346                 
347                 
348         
349         }
350
351
352 }