2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.guard;
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;
30 import javax.persistence.EntityManager;
31 import javax.persistence.Persistence;
32 import javax.persistence.Query;
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;
53 public class PIPEngineGetHistory extends StdConfigurableEngine{
55 private Log logger = LogFactory.getLog(this.getClass());
57 //private static EntityManager em;
59 public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB";
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"
65 public static final String DEFAULT_ISSUER = "com:att:research:xacml:guard:historydb";
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"));
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"));
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"));
84 private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) {
85 AttributeValue<BigInteger> attributeValue = null;
87 attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value);
88 } catch (Exception ex) {
89 this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex);
91 if (attributeValue != null) {
92 stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false));
98 public PIPEngineGetHistory() {
101 System.out.println("HAHAHAHAHAHAHAHAHAHAHAHAHAHAHA");
103 // TODO Auto-generated constructor stub
109 public Collection<PIPRequest> attributesRequired() {
110 // TODO Auto-generated method stub
111 System.out.println("DADADADADADADADADADADADADA");
116 public Collection<PIPRequest> attributesProvided() {
117 // TODO Auto-generated method stub
118 System.out.println("GAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAG");
123 public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
124 // TODO Auto-generated method stub
125 System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Entering FeqLimiter PIP!!!");
128 * First check to see if the issuer is set and then match it
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;
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;
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
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);
153 String actor = getActor(pipFinder).iterator().next();
154 String operation = getRecipe(pipFinder).iterator().next();
155 String target = getTarget(pipFinder).iterator().next();
157 String timeWindow = timeWindowVal + " " + timeWindowScale;
159 System.out.println("Going to query DB about: "+actor + " " + operation + " " + target + " " + timeWindow);
160 int countFromDB = getCountFromDB(actor, operation, target, timeWindow);
163 StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse();
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"),
171 return new StdPIPResponse(stdPIPResponse);
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);
182 if (this.getIssuer() == null) {
183 this.setIssuer(DEFAULT_ISSUER);
187 em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
189 System.err.println("Freq limiter PIP got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.");
198 private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
199 PIPResponse pipResponse = null;
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());
207 if (pipResponse.getAttributes().size() == 0) {
208 System.out.println("No value for " + pipRequest.getAttributeId().stringValue());
211 } catch (PIPException ex) {
212 System.out.println("PIPException getting subject-id attribute: " + ex.getMessage());
218 private Set<String> getActor(PIPFinder pipFinder) {
220 * Get the AT&T UID from either the subject id or the attuid property
222 PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder);
223 if (pipResponseATTUID == null) {
228 * Iterate over all of the returned results and do the LDAP requests
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);
247 private Set<String> getRecipe(PIPFinder pipFinder) {
249 * Get the AT&T UID from either the subject id or the attuid property
251 PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder);
252 if (pipResponseATTUID == null) {
257 * Iterate over all of the returned results and do the LDAP requests
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);
277 private Set<String> getTarget(PIPFinder pipFinder) {
279 * Get the AT&T UID from either the subject id or the attuid property
281 PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder);
282 if (pipResponseATTUID == null) {
287 * Iterate over all of the returned results and do the LDAP requests
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);
306 private static int getCountFromDB(String actor, String operation, String target, String timeWindow){
308 long startTime = System.nanoTime();
314 em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
316 System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB.");
321 //em.getTransaction().begin();
322 String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor='"
324 + "' and operation='"
329 + "and endtime between date_sub(now(),interval "
333 Query nq = em.createNativeQuery(sql);
335 int ret = ((Number)nq.getSingleResult()).intValue();
337 System.out.println("###########************** History count: " + ret);
339 //em.getTransaction().commit();
340 long estimatedTime = System.nanoTime() - startTime;
341 System.out.println("time took: " + (double)estimatedTime/1000/1000 + " mili sec.");