CHeckstyle and JUnit for base package in ONAP-REST
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / PDPServices.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdp.rest.api.services;
23
24 import com.att.research.xacml.api.Advice;
25 import com.att.research.xacml.api.AttributeAssignment;
26 import com.att.research.xacml.api.Decision;
27 import com.att.research.xacml.api.Obligation;
28 import com.att.research.xacml.api.Request;
29 import com.att.research.xacml.api.Response;
30 import com.att.research.xacml.api.Result;
31 import com.att.research.xacml.api.pdp.PDPEngine;
32 import com.att.research.xacml.api.pdp.PDPException;
33 import com.att.research.xacml.std.dom.DOMRequest;
34 import com.att.research.xacml.std.dom.DOMResponse;
35 import com.att.research.xacml.std.json.JSONRequest;
36 import com.att.research.xacml.std.json.JSONResponse;
37 import com.att.research.xacml.util.XACMLProperties;
38 import com.google.common.base.Strings;
39 import java.io.File;
40 import java.io.FileInputStream;
41 import java.io.FileNotFoundException;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.StringWriter;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Properties;
52 import java.util.UUID;
53 import javax.json.Json;
54 import javax.json.JsonReader;
55 import javax.xml.XMLConstants;
56 import javax.xml.parsers.DocumentBuilder;
57 import javax.xml.parsers.DocumentBuilderFactory;
58 import javax.xml.parsers.ParserConfigurationException;
59 import javax.xml.transform.Transformer;
60 import javax.xml.transform.TransformerFactory;
61 import javax.xml.transform.dom.DOMSource;
62 import javax.xml.transform.stream.StreamResult;
63 import org.apache.commons.io.IOUtils;
64 import org.onap.policy.api.PolicyConfigStatus;
65 import org.onap.policy.api.PolicyDecision;
66 import org.onap.policy.api.PolicyException;
67 import org.onap.policy.api.PolicyResponseStatus;
68 import org.onap.policy.api.PolicyType;
69 import org.onap.policy.common.logging.flexlogger.FlexLogger;
70 import org.onap.policy.common.logging.flexlogger.Logger;
71 import org.onap.policy.pdp.rest.XACMLPdpServlet;
72 import org.onap.policy.pdp.rest.api.models.PDPResponse;
73 import org.onap.policy.rest.XacmlRestProperties;
74 import org.onap.policy.std.Matches;
75 import org.onap.policy.xacml.api.XACMLErrorConstants;
76 import org.w3c.dom.Document;
77
78
79 public class PDPServices {
80     private static final Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName());
81     // Change the default Priority value here.
82     private static final int DEFAULT_PRIORITY = 9999;
83     private boolean unique = false;
84     private Boolean decide = false;
85     private String requestType = null;
86     private String requestFormat = DECISION_RAW_XACML_JSON_TYPE;
87     private List<String> policyList = null;
88     public static final String RAINYDAY_TYPE = "BB_ID";
89     public static final String DECISION_MS_NAMING_TYPE = "main-resource-keys";
90     public static final String DECISION_RAW_XACML = "raw-xacml-request";
91     public static final String DECISION_RAW_XACML_TYPE = "raw-xacml-type";
92     public static final String DECISION_RAW_XACML_XML_TYPE = "XML";
93     public static final String DECISION_RAW_XACML_JSON_TYPE = "JSON";
94
95     /**
96      * Generate request.
97      *
98      * @param reqStr the json string
99      * @param requestId the request id
100      * @param unique the unique
101      * @param decide the decide
102      * @return the collection
103      * @throws PolicyException the policy exception
104      */
105     public Collection<PDPResponse> generateRequest(String reqStr, UUID requestId, boolean unique, boolean decide)
106             throws PolicyException {
107         this.unique = unique;
108         this.decide = decide;
109         Collection<PDPResponse> results = null;
110         Response response = null;
111         // Create Request. We need XACML API here.
112         try {
113             Request request = null;
114             if (DECISION_RAW_XACML_JSON_TYPE.equals(requestFormat)) {
115                 request = JSONRequest.load(reqStr);
116                 LOGGER.info("--- Generating Request: ---" + requestId + "\n" + JSONRequest.toString(request));
117             } else {
118                 request = DOMRequest.load(reqStr);
119                 LOGGER.info("--- Generating Request: ---" + requestId + "\n" + reqStr);
120             }
121
122             // Call the PDP
123             response = callPdp(request, requestId);
124             if (response == null) {
125                 response = callPdp(request, requestId);
126             }
127
128         } catch (Exception e) {
129             LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
130             PDPResponse pdpResponse = new PDPResponse();
131             results = new HashSet<>();
132             pdpResponse.setPolicyConfigMessage("Unable to Call PDP. Error with the URL");
133             pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
134             pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED);
135             results.add(pdpResponse);
136             throw new PolicyException(e);
137         }
138
139         if (response != null) {
140             results = checkResponse(response);
141             if (policyList != null) {
142                 for (String policy : policyList) {
143                     XACMLPdpServlet.monitor.policyCountAdd(policy, 1);
144                 }
145             }
146         } else {
147             LOGGER.info("No Response Received from PDP");
148             PDPResponse pdpResponse = new PDPResponse();
149             results = new HashSet<>();
150             pdpResponse.setPolicyConfigMessage("No Response Received");
151             pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
152             pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED);
153             results.add(pdpResponse);
154         }
155         return results;
156     }
157
158     private Collection<PDPResponse> checkResponse(Response response) throws PolicyException {
159         String pdpConfigLocation = null;
160         Collection<PDPResponse> combinedResult = new HashSet<>();
161         int priority = DEFAULT_PRIORITY;
162         Map<Integer, PDPResponse> uniqueResult = new HashMap<>();
163         for (Result result : response.getResults()) {
164             // Process the decision policies. We only return one back for
165             // decision
166             if (decide) {
167                 PDPResponse pdpResponse = processDecisionResult(result);
168                 if (pdpResponse != null) {
169                     combinedResult.add(pdpResponse);
170                 } else {
171                     LOGGER.info("processDecisionResult returned null");
172                 }
173                 return combinedResult;
174             }
175             if (!result.getDecision().equals(Decision.PERMIT)) {
176                 LOGGER.info("Decision not a Permit. " + result.getDecision().toString());
177                 PDPResponse pdpResponse = new PDPResponse();
178                 pdpResponse.setStatus(
179                         XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",
180                         PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND);
181                 combinedResult.add(pdpResponse);
182                 return combinedResult;
183             } else {
184                 if (!result.getAssociatedAdvice().isEmpty()) {
185                     // Configurations should be in advice.
186                     // Also PDP took actions could be here.
187                     for (Advice advice : result.getAssociatedAdvice()) {
188                         int config = 0;
189                         int uri = 0;
190                         String configUrl = null;
191                         String policyName = null;
192                         String policyVersion = null;
193                         Matches match = new Matches();
194                         Map<String, String> matchingConditions = new HashMap<>();
195                         Map<String, String> configAttributes = new HashMap<>();
196                         Map<String, String> responseAttributes = new HashMap<>();
197                         Map<String, String> actionTaken = new HashMap<>();
198                         PDPResponse pdpResponse = new PDPResponse();
199                         Map<String, String> adviseAttributes = new HashMap<>();
200                         for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
201                             adviseAttributes.put(attribute.getAttributeId().stringValue(),
202                                     attribute.getAttributeValue().getValue().toString());
203                             if ("CONFIGURATION".equalsIgnoreCase(attribute.getAttributeValue().getValue().toString())) {
204                                 config++;
205                             } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
206                                 uri++;
207                                 if (uri == 1) {
208                                     configUrl = attribute.getAttributeValue().getValue().toString();
209                                     pdpConfigLocation = configUrl.replace("$URL",
210                                             XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS));
211                                 } else {
212                                     if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) {
213                                         throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
214                                                 + "Error having multiple URI in the Policy");
215                                     }
216                                 }
217                             } else if ("PolicyName".equalsIgnoreCase(attribute.getAttributeId().stringValue())) {
218                                 policyName = attribute.getAttributeValue().getValue().toString();
219                                 policyList.add(policyName);
220                             } else if ("VersionNumber".equalsIgnoreCase(attribute.getAttributeId().stringValue())) {
221                                 policyVersion = attribute.getAttributeValue().getValue().toString();
222                             } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())) {
223                                 try {
224                                     priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString());
225                                 } catch (Exception e) {
226                                     LOGGER.error(
227                                             XACMLErrorConstants.ERROR_DATA_ISSUE
228                                                     + "Unable to Parse Integer for Priority. Setting to default value",
229                                             e);
230                                     priority = DEFAULT_PRIORITY;
231                                 }
232                             } else if (attribute.getAttributeId().stringValue().startsWith("matching")) {
233                                 matchingConditions.put(
234                                         attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""),
235                                         attribute.getAttributeValue().getValue().toString());
236                                 if ("ONAPName".equals(
237                                         attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""))) {
238                                     match.setOnapName(attribute.getAttributeValue().getValue().toString());
239                                     matchingConditions.put("ECOMPName",
240                                             attribute.getAttributeValue().getValue().toString());
241                                 } else if ("ConfigName".equals(
242                                         attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""))) {
243                                     match.setConfigName(attribute.getAttributeValue().getValue().toString());
244                                 } else {
245                                     configAttributes.put(
246                                             attribute.getAttributeId().stringValue().replaceFirst("(matching).", ""),
247                                             attribute.getAttributeValue().getValue().toString());
248                                 }
249                             } else if (attribute.getAttributeId().stringValue().startsWith("key:")) {
250                                 responseAttributes.put(
251                                         attribute.getAttributeId().stringValue().replaceFirst("(key).", ""),
252                                         attribute.getAttributeValue().getValue().toString());
253                             } else if (attribute.getAttributeId().stringValue().startsWith("controller:")) {
254                                 responseAttributes.put("$" + attribute.getAttributeId().stringValue(),
255                                         attribute.getAttributeValue().getValue().toString());
256                             } else if (attribute.getAttributeId().stringValue().startsWith("dependencies:")) {
257                                 responseAttributes.put("$dependency$",
258                                         attribute.getAttributeValue().getValue().toString());
259                             }
260                         }
261                         if (!configAttributes.isEmpty()) {
262                             match.setConfigAttributes(configAttributes);
263                         }
264                         if ((config == 1) && (uri == 1)) {
265                             // If there is a configuration.
266                             try {
267                                 LOGGER.debug("Configuration Call to : " + configUrl);
268                                 pdpResponse = configCall(pdpConfigLocation);
269                             } catch (Exception e) {
270                                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
271                                 pdpResponse.setStatus("Error in Calling the Configuration URL " + e,
272                                         PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND);
273                             }
274                             pdpResponse.setPolicyName(policyName);
275                             pdpResponse.setPolicyVersion(policyVersion);
276                             pdpResponse.setMatchingConditions(matchingConditions);
277                             pdpResponse.setResponseAttributes(responseAttributes);
278                             if (!unique) {
279                                 combinedResult.add(pdpResponse);
280                             } else {
281                                 if (!uniqueResult.isEmpty()) {
282                                     if (uniqueResult.containsKey(priority)) {
283                                         // Not any more unique, check the
284                                         // matching conditions size
285                                         int oldSize = uniqueResult.get(priority).getMatchingConditions().size();
286                                         int newSize = matchingConditions.size();
287                                         if (oldSize < newSize) {
288                                             uniqueResult.put(priority, pdpResponse);
289                                         } else if (oldSize == newSize) {
290                                             pdpResponse = new PDPResponse();
291                                             pdpResponse.setStatus(
292                                                     "Two/more Policies have Same Priority and matching conditions, Please correct your policies.",
293                                                     PolicyResponseStatus.NO_ACTION_REQUIRED,
294                                                     PolicyConfigStatus.CONFIG_NOT_FOUND);
295                                             combinedResult.add(pdpResponse);
296                                             unique = false;
297                                             return combinedResult;
298                                         }
299                                     } else {
300                                         uniqueResult.put(priority, pdpResponse);
301                                     }
302                                 } else {
303                                     uniqueResult.put(priority, pdpResponse);
304                                 }
305                             }
306                         } else {
307                             // Else it is Action Taken.
308                             LOGGER.info("Action Taken by PDP. ");
309                             actionTaken.putAll(adviseAttributes);
310                             pdpResponse.setActionTaken(actionTaken);
311                             pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_TAKEN);
312                             pdpResponse.setPolicyResponseMessage("Action Taken by the PDP");
313                             combinedResult.add(pdpResponse);
314                         }
315                     }
316                 }
317                 if (!result.getObligations().isEmpty()) {
318                     // Obligation actions
319                     // Action advised should be in obligations.
320                     for (Obligation obligation : result.getObligations()) {
321                         Map<String, String> actionAdvised = new HashMap<>();
322                         PDPResponse pdpResponse = new PDPResponse();
323                         for (AttributeAssignment attribute : obligation.getAttributeAssignments()) {
324                             actionAdvised.put(attribute.getAttributeId().stringValue(),
325                                     attribute.getAttributeValue().getValue().toString());
326                         }
327                         pdpResponse.setActionAdvised(actionAdvised);
328                         pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_ADVISED);
329                         pdpResponse.setPolicyResponseMessage("Action has been Advised ");
330                         combinedResult.add(pdpResponse);
331                     }
332                 }
333             }
334         }
335         if (unique) {
336             // Select Unique policy.
337             int minNum = DEFAULT_PRIORITY;
338             for (int num : uniqueResult.keySet()) {
339                 if (num < minNum) {
340                     minNum = num;
341                 }
342             }
343             combinedResult.add(uniqueResult.get(minNum));
344             // Turn off Unique
345             unique = false;
346         }
347
348         return combinedResult;
349     }
350
351     /**
352      * Process Decision Result.
353      *
354      * @param result input from Response.
355      * @return pdpResposne based on result.
356      */
357     private PDPResponse processDecisionResult(Result result) {
358         PDPResponse pdpResponse = new PDPResponse();
359         pdpResponse.setDecision(PolicyDecision.DENY);
360
361         if (!result.getDecision().equals(Decision.PERMIT)) {
362             LOGGER.info("processDecisionResult: Decision not a Permit. " + result.getDecision().toString());
363             String indeterminatePropValue = XACMLProperties.getProperty("decision.indeterminate.response");
364             if (result.getDecision().equals(Decision.INDETERMINATE) && indeterminatePropValue != null) {
365                 if ("PERMIT".equalsIgnoreCase(indeterminatePropValue)) {
366                     pdpResponse.setDecision(PolicyDecision.PERMIT);
367                 } else {
368                     pdpResponse.setDecision(PolicyDecision.DENY);
369                 }
370             } else {
371                 pdpResponse.setDecision(PolicyDecision.DENY);
372             }
373             for (Advice advice : result.getAssociatedAdvice()) {
374                 for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
375                     pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString());
376                     break;
377                 }
378             }
379             pdpResponse.setStatus(
380                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",
381                     PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_NOT_FOUND);
382         } else {
383             checkDecision(pdpResponse, result);
384         }
385         return pdpResponse;
386     }
387
388
389     /**
390      * Check for Decision for decision based calls.
391      *
392      * @param pdpResponseInput pdpResponse.
393      * @param result result.
394      * @return pdpResponse.
395      */
396     private PDPResponse checkDecision(PDPResponse pdpResponseInput, Result result) {
397         PDPResponse pdpResponse = pdpResponseInput;
398         // check for Decision for decision based calls.
399         pdpResponse.setDecision(PolicyDecision.PERMIT);
400
401         // if this is a Rainy Day treatment decision we need to get
402         // the selected treatment
403         if (!Strings.isNullOrEmpty(requestType) && RAINYDAY_TYPE.equals(requestType)) {
404             pdpResponse.setDetails(getRainyDayTreatment(result));
405         } else if (!Strings.isNullOrEmpty(requestType) && DECISION_MS_NAMING_TYPE.equals(requestType)) {
406             boolean configRetrieved = false;
407             for (Advice advice : result.getAssociatedAdvice()) {
408                 configRetrieved = checkConfig(advice, configRetrieved, pdpResponse);
409             }
410             if (!configRetrieved) {
411                 LOGGER.error(" Failed to retrieve Config data for " + DECISION_MS_NAMING_TYPE);
412                 pdpResponse.setDetails("Error in retrieving Config Data");
413             }
414
415         } else {
416             pdpResponse.setDetails("Decision Permit. OK!");
417         }
418         return pdpResponse;
419     }
420
421     /**
422      * Check if there is a configuration.
423      *
424      * @param advice advice.
425      * @param configRetrieved boolean.
426      * @param pdpResponse pdpResposneInput.
427      * @return pdpResponse.
428      */
429     private boolean checkConfig(Advice advice, boolean configRetrieved, PDPResponse pdpResponse) {
430         for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
431             if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
432                 String configUrl = attribute.getAttributeValue().getValue().toString();
433                 String pdpConfigLocation =
434                         configUrl.replace("$URL", XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS));
435                 // If there is a configuration.
436                 try {
437                     LOGGER.debug("processDecisionResult: Configuration Call to : " + configUrl);
438                     pdpResponse = configCall(pdpConfigLocation);
439                     pdpResponse.setDecision(PolicyDecision.PERMIT);
440                     pdpResponse.setDetails(pdpResponse.getConfig());
441                     configRetrieved = true;
442                     break;
443                 } catch (Exception e) {
444                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
445                     LOGGER.error(" Failed to retrieve Config data for " + configUrl);
446                     pdpResponse.setDetails("Error in retrieving Config Data from the Configuration URL " + configUrl);
447                 }
448             }
449         }
450         return configRetrieved;
451     }
452
453     private String getRainyDayTreatment(Result result) {
454         String treatment = null;
455         if (result != null && !result.getAssociatedAdvice().isEmpty()) {
456             // Get the desired treatment for requested errorCode from the Advice
457             for (Advice advice : result.getAssociatedAdvice()) {
458                 Map<String, String> adviseAttributes = new HashMap<>();
459                 for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
460                     adviseAttributes.put(attribute.getAttributeId().stringValue(),
461                             attribute.getAttributeValue().getValue().toString());
462                     if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())) {
463                         treatment = attribute.getAttributeValue().getValue().toString();
464                     }
465                 }
466             }
467         }
468         return treatment;
469     }
470
471     private PDPResponse configCall(String pdpConfigLocation) throws PDPException, IOException {
472         PDPResponse pdpResponse = new PDPResponse();
473         if (pdpConfigLocation.contains("/")) {
474             pdpConfigLocation = pdpConfigLocation.replace("/", File.separator);
475         }
476         try (InputStream inputStream = new FileInputStream(new File(pdpConfigLocation))) {
477             if (pdpConfigLocation.endsWith("json")) {
478                 pdpResponse.setType(PolicyType.JSON);
479                 try (JsonReader jsonReader = Json.createReader(inputStream)) {
480                     pdpResponse.setConfig(jsonReader.readObject().toString());
481                 }
482             } else if (pdpConfigLocation.endsWith("xml")) {
483                 pdpResponse.setType(PolicyType.XML);
484                 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
485                 dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
486                 dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
487                 DocumentBuilder db = null;
488                 try {
489                     db = dbf.newDocumentBuilder();
490                     Document document = db.parse(inputStream);
491                     DOMSource domSource = new DOMSource(document);
492                     StringWriter writer = new StringWriter();
493                     StreamResult result = new StreamResult(writer);
494                     TransformerFactory tf = TransformerFactory.newInstance();
495                     Transformer transformer;
496                     transformer = tf.newTransformer();
497                     transformer.transform(domSource, result);
498                     pdpResponse.setConfig(writer.toString());
499                 } catch (Exception e) {
500                     LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
501                     throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the XML config",
502                             e);
503                 }
504             } else if (pdpConfigLocation.endsWith("properties")) {
505                 pdpResponse.setType(PolicyType.PROPERTIES);
506                 Properties configProp = new Properties();
507                 configProp.load(inputStream);
508                 Map<String, String> propVal = new HashMap<>();
509                 for (String name : configProp.stringPropertyNames()) {
510                     propVal.put(name, configProp.getProperty(name));
511                 }
512                 pdpResponse.setProperty(propVal);
513             } else if (pdpConfigLocation.endsWith("txt")) {
514                 pdpResponse.setType(PolicyType.OTHER);
515                 String other = IOUtils.toString(inputStream);
516                 IOUtils.closeQuietly(inputStream);
517                 pdpResponse.setConfig(other);
518             } else {
519                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found");
520                 pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
521                 pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found.");
522                 inputStream.close();
523                 return pdpResponse;
524             }
525             LOGGER.info("config Retrieved " + pdpConfigLocation);
526             pdpResponse.setStatus("Config Retrieved! ", PolicyResponseStatus.NO_ACTION_REQUIRED,
527                     PolicyConfigStatus.CONFIG_RETRIEVED);
528             return pdpResponse;
529         } catch (FileNotFoundException e) {
530             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
531             throw new PDPException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e);
532         } catch (IOException | ParserConfigurationException e) {
533             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
534             throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Cannot open a connection to the configURL",
535                     e);
536         }
537     }
538
539     /**
540      * Call pdp.
541      *
542      * @param request the request
543      * @param requestIdParam the request id param
544      * @return the response
545      */
546     public Response callPdp(Request request, UUID requestIdParam) {
547         policyList = new ArrayList<>();
548         Response response = null;
549         // Get the PDPEngine
550         if (requestIdParam == null) {
551             requestIdParam = UUID.randomUUID();
552             LOGGER.debug("No request ID provided, sending generated ID: " + requestIdParam.toString());
553         } else {
554             LOGGER.debug("Using provided request ID: " + requestIdParam.toString());
555         }
556         PDPEngine pdpEngine = XACMLPdpServlet.getPDPEngine();
557         if (pdpEngine == null) {
558             String message = "PDPEngine not loaded.";
559             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message + "\n RequestId : " + requestIdParam);
560             return response;
561         }
562         XACMLPdpServlet.monitor.pdpEvaluationAttempts();
563         // call the PDPEngine to decide and give the response on the Request.
564         long timeStart;
565         long timeEnd;
566         try {
567             synchronized (XACMLPdpServlet.getPDPEngineLock()) {
568                 timeStart = System.currentTimeMillis();
569                 response = pdpEngine.decide(request);
570                 timeEnd = System.currentTimeMillis();
571             }
572
573             String outgoingResponseString = null;
574             if (DECISION_RAW_XACML_JSON_TYPE.equalsIgnoreCase(requestFormat)) {
575                 outgoingResponseString = JSONResponse.toString(response);
576                 LOGGER.info("Response from the PDP is : \n" + JSONResponse.toString(response, true) + "\n RequestId : "
577                         + requestIdParam + " pdpEngine : " + pdpEngine);
578             } else {
579                 outgoingResponseString = DOMResponse.toString(response);
580                 LOGGER.info("Response from the PDP is : \n" + DOMResponse.toString(response, true) + "\n RequestId : "
581                         + requestIdParam + " pdpEngine : " + pdpEngine);
582             }
583
584             XACMLPdpServlet.monitor.computeLatency(timeEnd - timeStart);
585
586             // adding the jmx values for NA, Permit and Deny
587             //
588             if (outgoingResponseString.contains("NotApplicable")
589                     || outgoingResponseString.contains("Decision not a Permit")) {
590                 XACMLPdpServlet.monitor.pdpEvaluationNA();
591             }
592
593             if (outgoingResponseString.contains("Permit")
594                     && !outgoingResponseString.contains("Decision not a Permit")) {
595                 XACMLPdpServlet.monitor.pdpEvaluationPermit();
596             }
597
598             if (outgoingResponseString.contains("Deny")) {
599                 XACMLPdpServlet.monitor.pdpEvaluationDeny();
600             }
601         } catch (Exception e) {
602             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e + "\n RequestId : " + requestIdParam);
603             return null;
604         }
605         return response;
606     }
607
608     public String getRequestType() {
609         return requestType;
610     }
611
612     public void setRequestType(String requestType) {
613         this.requestType = requestType;
614     }
615
616     /**
617      * Returns the requestFormat.
618      *
619      * @return the requestFormat.
620      */
621     public String getRequestFormat() {
622         return requestFormat;
623     }
624
625     /**
626      * Set the Request Format.
627      *
628      * @param requestMode to set requestFormat.
629      */
630     public void setRequestFormat(String requestMode) {
631         this.requestFormat = requestMode;
632     }
633
634 }