[POLICY-73] replace openecomp for policy-engine
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / XACMLPdpServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
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.pdp.rest;
22
23 import java.io.BufferedReader;
24 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.lang.reflect.Constructor;
30 import java.net.InetAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.util.Properties;
34 import java.util.UUID;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.LinkedBlockingQueue;
37
38 import javax.servlet.Servlet;
39 import javax.servlet.ServletConfig;
40 import javax.servlet.ServletException;
41 import javax.servlet.annotation.WebInitParam;
42 import javax.servlet.annotation.WebServlet;
43 import javax.servlet.http.HttpServlet;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.apache.commons.io.IOUtils;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50 import org.apache.http.entity.ContentType;
51 import org.onap.policy.api.PolicyParameters;
52 import org.onap.policy.common.im.AdministrativeStateException;
53 import org.onap.policy.common.im.ForwardProgressException;
54 import org.onap.policy.common.im.IntegrityMonitor;
55 import org.onap.policy.common.im.IntegrityMonitorProperties;
56 import org.onap.policy.common.im.StandbyStatusException;
57 import org.onap.policy.common.logging.ONAPLoggingContext;
58 import org.onap.policy.common.logging.ONAPLoggingUtils;
59 import org.onap.policy.common.logging.eelf.MessageCodes;
60 import org.onap.policy.common.logging.eelf.PolicyLogger;
61 import org.onap.policy.pdp.rest.jmx.PdpRestMonitor;
62 import org.onap.policy.rest.XACMLRest;
63 import org.onap.policy.rest.XACMLRestProperties;
64 import org.onap.policy.xacml.api.XACMLErrorConstants;
65 import org.onap.policy.xacml.pdp.std.functions.PolicyList;
66 import org.onap.policy.xacml.std.pap.StdPDPStatus;
67
68 import com.att.research.xacml.api.Request;
69 import com.att.research.xacml.api.Response;
70 import com.att.research.xacml.api.pap.PDPStatus.Status;
71 import com.att.research.xacml.api.pdp.PDPEngine;
72 import com.att.research.xacml.api.pdp.PDPException;
73 import com.att.research.xacml.std.dom.DOMRequest;
74 import com.att.research.xacml.std.dom.DOMResponse;
75 import com.att.research.xacml.std.json.JSONRequest;
76 import com.att.research.xacml.std.json.JSONResponse;
77 import com.att.research.xacml.util.XACMLProperties;
78 import com.fasterxml.jackson.databind.ObjectMapper;
79
80 /**
81  * Servlet implementation class XacmlPdpServlet
82  * 
83  * This is an implementation of the XACML 3.0 RESTful Interface with added features to support
84  * simple PAP RESTful API for policy publishing and PIP configuration changes.
85  * 
86  * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file.
87  * This properties file has all the default parameter settings. If you are running the servlet as is,
88  * then we recommend setting up you're container to run it on port 8080 with context "/pdp". Wherever
89  * the default working directory is set to, a "config" directory will be created that holds the policy
90  * and pip cache. This setting is located in the xacml.pdp.properties file.
91  * 
92  * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file
93  * system and setup the parameters as you wish. Just set the Java VM System variable to point to that file:
94  * 
95  * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties
96  * 
97  * Or if you only want to change one or two properties, simply set the Java VM System variable for that property.
98  * 
99  * -Dxacml.rest.pdp.register=false
100  *
101  *
102  */
103 @WebServlet(
104                 description = "Implements the XACML PDP RESTful API and client PAP API.", 
105                 urlPatterns = { "/" }, 
106                 loadOnStartup=1,
107                 initParams = { 
108                                 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", description = "The location of the PDP xacml.pdp.properties file holding configuration information.")
109                 })
110 public class XACMLPdpServlet extends HttpServlet implements Runnable {
111         private static final long serialVersionUID = 1L;
112         private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; //32767
113         private static final String CREATE_UPDATE_POLICY_SERVICE = "org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl";
114         //
115         // Our application debug log
116         //
117         private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class);
118         //
119         // This logger is specifically only for Xacml requests and their corresponding response.
120         // It's output ideally should be sent to a separate file from the application logger.
121         //
122         private static final Log requestLogger = LogFactory.getLog("xacml.request");
123         // 
124         // audit logger
125         private static final Log auditLogger = LogFactory.getLog("auditLogger");
126
127         private static final PdpRestMonitor monitor = PdpRestMonitor.getSingleton();
128
129         //
130         // This thread may getting invoked on startup, to let the PAP know
131         // that we are up and running.
132         //
133         private Thread registerThread = null;
134         private XACMLPdpRegisterThread registerRunnable = null;
135         //
136         // This is our PDP engine pointer. There is a synchronized lock used
137         // for access to the pointer. In case we are servicing PEP requests while
138         // an update is occurring from the PAP.
139         //
140         private static PDPEngine pdpEngine      = null;
141         private static final Object pdpEngineLock = new Object();
142         //
143         // This is our PDP's status. What policies are loaded (or not) and
144         // what PIP configurations are loaded (or not).
145         // There is a synchronized lock used for access to the object.
146         //
147         private static volatile StdPDPStatus status = new StdPDPStatus();
148         private static final Object pdpStatusLock = new Object();
149         private static Constructor<?> createUpdatePolicyConstructor;
150
151         private static final String ENVIORNMENT_HEADER = "Environment";
152         private static String environment = null;
153         //
154         // Queue of PUT requests
155         //
156         public static class PutRequest {
157                 private Properties policyProperties = null;
158                 private Properties pipConfigProperties = null;
159
160                 PutRequest(Properties policies, Properties pips) {
161                         this.policyProperties = policies;
162                         this.pipConfigProperties = pips;
163                 }
164         }
165         protected static volatile BlockingQueue<PutRequest> queue = null;
166         // For notification Delay.
167         private static int notificationDelay = 0;
168         public static int getNotificationDelay(){
169                 return XACMLPdpServlet.notificationDelay;
170         }
171
172         private static String pdpResourceName;
173         private static String[] dependencyNodes = null;
174
175         //
176         // This is our configuration thread that attempts to load
177         // a new configuration request.
178         //
179         private Thread configThread = null;
180         private volatile boolean configThreadTerminate = false;
181         private ONAPLoggingContext baseLoggingContext = null;
182         private IntegrityMonitor im;
183         /**
184          * Default constructor. 
185          */
186         public XACMLPdpServlet() {
187                 //Default constructor.
188         }
189
190         /**
191          * @see Servlet#init(ServletConfig)
192          */
193         @Override
194         public void init(ServletConfig config) throws ServletException {
195                 String createUpdateResourceName = null;
196                 String dependencyGroups = null;
197                 //
198                 // Initialize
199                 //
200                 XACMLRest.xacmlInit(config);
201                 // Load the Notification Delay. 
202                 try{
203                         XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY));
204                 }catch(Exception e){
205                         logger.info("Notification Delay Not set. Keeping it 0 as default."+e);
206                 }
207                 // Load Queue size. 
208                 int queueSize = 5; // Set default Queue Size here. 
209                 queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE",String.valueOf(queueSize)));
210                 queue = new LinkedBlockingQueue<PutRequest>(queueSize);
211                 // Load our engine - this will use the latest configuration
212                 // that was saved to disk and set our initial status object.
213                 //
214                 PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null);
215                 if (engine != null) {
216                         synchronized(pdpEngineLock) {
217                                 pdpEngine = engine;
218                         }
219                 }
220                 //
221                 // Logging stuff....
222                 //
223                 baseLoggingContext = new ONAPLoggingContext();
224                 // fixed data that will be the same in all logging output goes here
225                 try {
226                         String ipaddress = InetAddress.getLocalHost().getHostAddress();
227                         baseLoggingContext.setServer(ipaddress);
228                 } catch (UnknownHostException e) {
229                         logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"+e);
230                 }
231
232                 Properties properties;
233                 try {
234                         properties = XACMLProperties.getProperties();
235                 } catch (IOException e) {
236                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e,
237                                         "Error loading properties with: XACMLProperties.getProperties()");
238                         throw new ServletException(e.getMessage(), e.getCause());
239                 }
240                 if(properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME)==null){
241                         XACMLProperties.reloadProperties();
242                         try {
243                                 properties = XACMLProperties.getProperties();
244                         } catch (IOException e) {
245                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e,
246                                                 "Error loading properties with: XACMLProperties.getProperties()");
247                                 throw new ServletException(e.getMessage(), e.getCause());
248                         }
249                         PolicyLogger.info("\n Properties Given : \n" + properties.toString());
250                 }
251                 pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME);
252                 if(pdpResourceName == null){
253                         PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
254                         throw new ServletException("pdpResourceName is null");
255                 }
256
257                 dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS);
258                 if(dependencyGroups == null){
259                         PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, "xacml.pdp");
260                         throw new ServletException("dependency_groups is null");
261                 }
262                 // dependency_groups is a semicolon-delimited list of groups, and
263                 // each group is a comma-separated list of nodes. For our purposes
264                 // we just need a list of dependencies without regard to grouping,
265                 // so split the list into nodes separated by either comma or semicolon.
266                 dependencyNodes = dependencyGroups.split("[;,]");
267                 for (int i = 0 ; i < dependencyNodes.length ; i++){
268                         dependencyNodes[i] = dependencyNodes[i].trim();
269                 }
270
271                 // CreateUpdatePolicy ResourceName  
272                 createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE);
273                 setCreateUpdatePolicyConstructor(createUpdateResourceName);
274
275                 // Create an IntegrityMonitor
276                 try {
277                         logger.info("Creating IntegrityMonitor");
278                         im = IntegrityMonitor.getInstance(pdpResourceName, properties);
279                 } catch (Exception e) { 
280                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" +e);
281                         throw new ServletException(e);
282                 }
283
284                 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
285                 //
286                 // Kick off our thread to register with the PAP servlet.
287                 //
288                 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) {
289                         this.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext);
290                         this.registerThread = new Thread(this.registerRunnable);
291                         this.registerThread.start();
292                 }
293                 //
294                 // This is our thread that manages incoming configuration
295                 // changes.
296                 //
297                 this.configThread = new Thread(this);
298                 this.configThread.start();
299         }
300
301         /**
302          * @see Servlet#destroy()
303          */
304         @Override
305         public void destroy() {
306                 super.destroy();
307                 logger.info("Destroying....");
308                 //
309                 // Make sure the register thread is not running
310                 //
311                 if (this.registerRunnable != null) {
312                         try {
313                                 this.registerRunnable.terminate();
314                                 if (this.registerThread != null) {
315                                         this.registerThread.interrupt();
316                                         this.registerThread.join();
317                                 }
318                         } catch (InterruptedException e) {
319                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
320                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
321                         }
322                 }
323                 //
324                 // Make sure the configure thread is not running
325                 //
326                 this.configThreadTerminate = true;
327                 try {
328                         this.configThread.interrupt();
329                         this.configThread.join();
330                 } catch (InterruptedException e) {
331                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
332                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
333                 }
334                 logger.info("Destroyed.");
335         }
336
337         /**
338          * PUT - The PAP engine sends configuration information using HTTP PUT request.
339          * 
340          * One parameter is expected:
341          * 
342          * config=[policy|pip|all]
343          * 
344          *      policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP should
345          *                       be using for PEP requests.
346          * 
347          *              Specifically should AT LEAST contain the following properties:
348          *              xacml.rootPolicies
349          *              xacml.referencedPolicies
350          * 
351          *              In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache.
352          *
353          *              EXAMPLE:
354          *                      xacml.rootPolicies=PolicyA.1, PolicyB.1
355          *
356          *                      PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1
357          *                      PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1
358          *      
359          *                      xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1
360          *
361          *                      RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1
362          *                      RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1
363          *      
364          * pip - Expect a properties file that contain PIP engine configuration properties.
365          * 
366          *              Specifically should AT LEAST the following property:
367          *                      xacml.pip.engines
368          * 
369          *              In addition, any relevant information needed by the PDP to load and configure the PIPs.
370          * 
371          *              EXAMPLE:
372          *                      xacml.pip.engines=foo,bar
373          * 
374          *                      foo.classname=com.foo
375          *                      foo.sample=abc
376          *                      foo.example=xyz
377          *                      ......
378          * 
379          *                      bar.classname=com.bar
380          *                      ......
381          * 
382          * all - Expect ALL new configuration properties for the PDP
383          * 
384          * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
385          */
386         @Override
387         protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
388                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
389                 loggingContext.transactionStarted();
390                 if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())){
391                         UUID requestID = UUID.randomUUID();
392                         loggingContext.setRequestID(requestID.toString());
393                         PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one");
394                 } else {
395                         PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)");
396                 }
397                 loggingContext.metricStarted();
398                 loggingContext.metricEnded();
399                 PolicyLogger.metrics("Metric example posted here - 1 of 2");
400                 loggingContext.metricStarted();
401                 loggingContext.metricEnded();
402                 PolicyLogger.metrics("Metric example posted here - 2 of 2");
403                 //
404                 // Dump our request out
405                 //
406                 if (logger.isDebugEnabled()) {
407                         XACMLRest.dumpRequest(request);
408                 }
409
410                 try {
411                         im.startTransaction();
412                 }
413                 catch (AdministrativeStateException | StandbyStatusException e) {
414                         String message = e.toString();
415                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e);
416                         loggingContext.transactionEnded();
417                         PolicyLogger.audit("Transaction Failed - See Error.log");
418                         try{
419                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
420                         }catch(Exception e1){
421                                 logger.error("Exception occured while sending error in response" +e1);
422                         }
423                         return;
424                 }
425                 //
426                 // What is being PUT?
427                 //
428                 String cache = request.getParameter("cache");
429                 //
430                 // Should be a list of policy and pip configurations in Java properties format
431                 //
432                 if (cache != null && request.getContentType().equals("text/x-java-properties")) {
433                         loggingContext.setServiceName("PDP.putConfig");
434                         try{
435                                 if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) {
436                                         String message = "Content-Length larger than server will accept.";
437                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
438                                         loggingContext.transactionEnded();
439                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
440                                         PolicyLogger.audit("Transaction Failed - See Error.log");
441                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
442                                         im.endTransaction();
443                                         return;
444                                 }
445                                 this.doPutConfig(cache, request, response, loggingContext);
446                                 loggingContext.transactionEnded();
447                                 PolicyLogger.audit("Transaction ended");
448
449                                 im.endTransaction();
450                         }catch(Exception e){
451                                 logger.error("Exception Occured while getting Max Content lenght"+e);
452                         }
453                 } else {
454                         String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'";
455                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message);
456                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
457                         loggingContext.transactionEnded();
458                         PolicyLogger.audit("Transaction Failed - See Error.log");
459                         try{
460                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
461                         }catch(Exception e1){
462                                 logger.error("Exception occured while sending error in response" +e1);
463                         }
464                         im.endTransaction();
465                         return;
466                 }
467         }
468
469         protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext)  throws ServletException, IOException {
470                 try {
471                         // prevent multiple configuration changes from stacking up
472                         if (XACMLPdpServlet.queue.remainingCapacity() <= 0) {
473                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached");
474                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached");
475                                 loggingContext.transactionEnded();
476                                 PolicyLogger.audit("Transaction Failed - See Error.log");
477                                 response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing.");
478                                 return;
479                         }
480                         //
481                         // Read the properties data into an object.
482                         //
483                         Properties newProperties = new Properties();
484                         newProperties.load(request.getInputStream());
485                         // should have something in the request
486                         if (newProperties.size() == 0) {
487                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT");
488                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT");
489                                 loggingContext.transactionEnded();
490                                 PolicyLogger.audit("Transaction Failed - See Error.log");
491                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property");
492                                 return;
493                         }
494                         //
495                         // Which set of properties are they sending us? Whatever they send gets
496                         // put on the queue (if there is room).
497                         // For audit logging purposes, we consider the transaction done once the
498                         // the request gets put on the queue.
499                         //
500                         if (config.equals("policies")) {
501                                 newProperties = XACMLProperties.getPolicyProperties(newProperties, true);
502                                 if (newProperties.size() == 0) {
503                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT");
504                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT");
505                                         loggingContext.transactionEnded();
506                                         PolicyLogger.audit("Transaction Failed - See Error.log");
507                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property");
508                                         return;
509                                 }
510                                 XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null));
511                                 loggingContext.transactionEnded();
512                                 auditLogger.info("Success");
513                                 PolicyLogger.audit("Success");
514                         } else if (config.equals("pips")) {
515                                 newProperties = XACMLProperties.getPipProperties(newProperties);
516                                 if (newProperties.size() == 0) {
517                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT");
518                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT");
519                                         loggingContext.transactionEnded();
520                                         PolicyLogger.audit("Transaction Failed - See Error.log");
521                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property");
522                                         return;
523                                 }
524                                 XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties));
525                                 loggingContext.transactionEnded();
526                                 auditLogger.info("Success");
527                                 PolicyLogger.audit("Success");
528                         } else if (config.equals("all")) {
529                                 Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true);
530                                 if (newPolicyProperties.size() == 0) {
531                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT");
532                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT");
533                                         loggingContext.transactionEnded();
534                                         PolicyLogger.audit("Transaction Failed - See Error.log");
535                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property");
536                                         return;
537                                 }
538                                 Properties newPipProperties = XACMLProperties.getPipProperties(newProperties);
539                                 if (newPipProperties.size() == 0) {
540                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT");
541                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT");
542                                         loggingContext.transactionEnded();
543                                         PolicyLogger.audit("Transaction Failed - See Error.log");
544                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property");
545                                         return;
546                                 }
547                                 XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties));
548                                 loggingContext.transactionEnded();
549                                 auditLogger.info("Success");
550                                 PolicyLogger.audit("Success");
551                         } else {
552                                 //
553                                 // Invalid value
554                                 //
555                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config);
556                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config);
557                                 loggingContext.transactionEnded();
558                                 PolicyLogger.audit("Transaction Failed - See Error.log");
559                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'");
560                                 return;
561                         }
562                 } catch (Exception e) {
563                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e);
564                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration");
565                         loggingContext.transactionEnded();
566                         PolicyLogger.audit("Transaction Failed - See Error.log");
567                         try{
568                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
569                         }catch(Exception e1){
570                                 logger.error("Exception occured while sending error in response" +e1);
571                         }
572                         return;
573                 }
574
575         }
576
577         /**
578          * Parameters: type=hb|config|Status
579          * 
580          * 1. HeartBeat Status 
581          * HeartBeat
582          *              OK - All Policies are Loaded, All PIPs are Loaded
583          *      LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration
584          *      LAST_UPDATE_FAILED - Need to track the items that failed during last update
585          *      LOAD_FAILURE - ??? Need to determine what information is sent and how 
586          * 2. Configuration
587          * 3. Status
588          *              return the StdPDPStatus object in the Response content
589          * 
590          * 
591          * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
592          */
593         @Override
594         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
595                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
596                 loggingContext.transactionStarted();
597                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
598                         UUID requestID = UUID.randomUUID();
599                         loggingContext.setRequestID(requestID.toString());
600                         PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one");
601                 } else {
602                         PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)");
603                 }
604                 loggingContext.metricStarted();
605                 loggingContext.metricEnded();
606                 PolicyLogger.metrics("Metric example posted here - 1 of 2");
607                 loggingContext.metricStarted();
608                 loggingContext.metricEnded();
609                 PolicyLogger.metrics("Metric example posted here - 2 of 2");
610
611                 XACMLRest.dumpRequest(request);
612
613                 String pathInfo = request.getRequestURI();
614                 if (pathInfo != null){
615                         // health check from Global Site Selector (iDNS).
616                         // DO NOT do a im.startTransaction for the test request
617                         if (pathInfo.equals("/pdp/test")) {
618                                 loggingContext.setServiceName("iDNS:PDP.test");
619                                 try {
620                                         im.evaluateSanity();
621                                         //If we make it this far, all is well
622                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
623                                         PolicyLogger.debug(message);
624                                         loggingContext.transactionEnded();
625                                         PolicyLogger.audit("Success");
626                                         response.setStatus(HttpServletResponse.SC_OK);
627                                         return;
628                                 } catch (ForwardProgressException fpe){
629                                         //No forward progress is being made
630                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress."
631                                                         + " Exception Message: " + fpe.getMessage();
632                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe);
633                                         loggingContext.transactionEnded();
634                                         PolicyLogger.audit("Transaction Failed - See Error.log");
635                                         try{
636                                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
637                                         }catch(Exception e1){
638                                                 logger.error("Exception occured while sending error in response" +e1);
639                                         }
640                                         return;
641                                 }catch (AdministrativeStateException ase){
642                                         //Administrative State is locked
643                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Administrative State is LOCKED "
644                                                         + " Exception Message: " + ase.getMessage();
645                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase);
646                                         loggingContext.transactionEnded();
647                                         PolicyLogger.audit("Transaction Failed - See Error.log");
648                                         try{
649                                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
650                                         }catch(Exception e1){
651                                                 logger.error("Exception occured while sending error in response" +e1);
652                                         }
653                                         return;
654                                 }catch (StandbyStatusException sse){
655                                         //Administrative State is locked
656                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Standby Status is NOT PROVIDING SERVICE "
657                                                         + " Exception Message: " + sse.getMessage();
658                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse);
659                                         loggingContext.transactionEnded();
660                                         PolicyLogger.audit("Transaction Failed - See Error.log");
661                                         try{
662                                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
663                                         }catch(Exception e1){
664                                                 logger.error("Exception occured while sending error in response" +e1);
665                                         }
666                                         return;
667                                 } catch (Exception e) {
668                                         //A subsystem is not making progress or is not responding
669                                         String eMsg = e.getMessage();
670                                         if(eMsg == null){
671                                                 eMsg = "No Exception Message";
672                                         }
673                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
674                                                         + " Exception Message: " + eMsg;
675                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
676                                         //Get the specific list of subsystems that failed
677                                         String failedNodeList = null;
678                                         for(String node : dependencyNodes){
679                                                 if(eMsg.contains(node)){
680                                                         if(failedNodeList == null){
681                                                                 failedNodeList = node;
682                                                         }else{
683                                                                 failedNodeList = failedNodeList.concat(","+node);
684                                                         }
685                                                 }
686                                         }
687                                         if(failedNodeList == null){
688                                                 failedNodeList = "UnknownSubSystem";
689                                         }
690                                         response.addHeader("X-ONAP-SubsystemFailure", failedNodeList);
691                                         try{
692                                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
693                                         }catch(Exception e1){
694                                                 logger.error("Exception occured while sending error in response" +e1);
695                                         }
696                                         loggingContext.transactionEnded();
697                                         PolicyLogger.audit("Transaction Failed - See Error.log" + e);
698                                         return;
699                                 }
700                         }
701                 }
702
703                 try {
704                         im.startTransaction();
705                 }
706                 catch (AdministrativeStateException | StandbyStatusException e) {
707                         String message = e.toString();
708                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
709                         loggingContext.transactionEnded();
710                         PolicyLogger.audit("Transaction Failed - See Error.log" +e);
711                         try{
712                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
713                         }catch(Exception e1){
714                                 logger.error("Exception occured while sending error in response" +e1);
715                         }
716                         return;
717                 }
718                 //
719                 // What are they requesting?
720                 //
721                 boolean returnHB = false;
722                 response.setHeader("Cache-Control", "no-cache");
723                 String type = request.getParameter("type");
724                 // type might be null, so use equals on string constants
725                 if ("config".equals(type)) {
726                         loggingContext.setServiceName("PDP.getConfig");
727                         response.setContentType("text/x-java-properties");
728                         try {
729                                 String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
730                                 lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n";
731                                 try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes());
732                                                 InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig());
733                                                 OutputStream os = response.getOutputStream()) {
734                                         IOUtils.copy(listInputStream, os);
735                                         IOUtils.copy(pipInputStream, os);
736                                 }
737                                 loggingContext.transactionEnded();
738                                 auditLogger.info("Success");
739                                 PolicyLogger.audit("Success");
740                                 response.setStatus(HttpServletResponse.SC_OK);
741                         } catch (Exception e) {
742                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e);
743                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file");
744                                 loggingContext.transactionEnded();
745                                 PolicyLogger.audit("Transaction Failed - See Error.log");
746                                 try{
747                                         response.sendError(400, "Failed to copy Property file");
748                                 }catch(Exception e1){
749                                         logger.error("Exception occured while sending error in response" +e1);
750                                 }
751                         }
752
753                 } else if ("hb".equals(type)) {
754                         returnHB = true;
755                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
756
757                 } else if ("Status".equals(type)) {
758                         loggingContext.setServiceName("PDP.getStatus");
759                         // convert response object to JSON and include in the response
760                         synchronized(pdpStatusLock) {
761                                 ObjectMapper mapper = new ObjectMapper();
762                                 try{
763                                         mapper.writeValue(response.getOutputStream(),  status);
764                                 }catch(Exception e1){
765                                         logger.error("Exception occured while writing output stream" +e1);
766                                 }
767                         }
768                         response.setStatus(HttpServletResponse.SC_OK);
769                         loggingContext.transactionEnded();
770                         auditLogger.info("Success");
771                         PolicyLogger.audit("Success");
772
773                 } else {
774                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type);
775                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type);
776                         loggingContext.transactionEnded();
777                         PolicyLogger.audit("Transaction Failed - See Error.log");
778                         try{
779                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'");
780                         }catch(Exception e1){
781                                 logger.error("Exception occured while sending error in response" +e1);
782                         }
783                 }
784                 if (returnHB) {
785                         synchronized(pdpStatusLock) {
786                                 response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
787                         }
788                 }
789                 loggingContext.transactionEnded();
790                 PolicyLogger.audit("Transaction Ended");
791                 im.endTransaction();
792
793         }
794
795         /**
796          * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON according
797          * to the XACML 3.0 Specifications for both.
798          * 
799          * 
800          * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
801          */
802         @Override
803         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
804
805                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
806                 loggingContext.transactionStarted();
807                 loggingContext.setServiceName("PDP.decide");
808                 if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))){
809                         UUID requestID = UUID.randomUUID();
810                         loggingContext.setRequestID(requestID.toString());
811                         PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one");
812                 } else {
813                         PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)");
814                 }
815                 loggingContext.metricStarted();
816                 loggingContext.metricEnded();
817                 PolicyLogger.metrics("Metric example posted here - 1 of 2");
818                 loggingContext.metricStarted();
819                 loggingContext.metricEnded();
820                 PolicyLogger.metrics("Metric example posted here - 2 of 2");
821                 monitor.pdpEvaluationAttempts();
822
823                 try {
824                         im.startTransaction();
825                 }
826                 catch (AdministrativeStateException | StandbyStatusException e) {
827                         String message = e.toString();
828                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e);
829                         loggingContext.transactionEnded();
830                         PolicyLogger.audit("Transaction Failed - See Error.log");
831                         try{
832                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
833                         }catch(Exception e1){
834                                 logger.error("Exception occured while sending error in response" +e1);
835                         }
836                         return;
837                 }
838                 //
839                 // no point in doing any work if we know from the get-go that we cannot do anything with the request
840                 //
841                 if (status.getLoadedRootPolicies().isEmpty()) {
842                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded");
843                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded");
844                         loggingContext.transactionEnded();
845                         PolicyLogger.audit("Transaction Failed - See Error.log");
846                         try{
847                                 response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
848                         }catch(Exception e1){
849                                 logger.error("Exception occured while sending error in response" +e1);
850                         }
851                         im.endTransaction();
852                         return;
853                 }
854
855                 XACMLRest.dumpRequest(request);
856                 //
857                 // Set our no-cache header
858                 //
859                 response.setHeader("Cache-Control", "no-cache");
860                 //
861                 // They must send a Content-Type
862                 //
863                 if (request.getContentType() == null) {
864                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type");
865                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type");
866                         loggingContext.transactionEnded();
867                         PolicyLogger.audit("Transaction Failed - See Error.log");
868                         try{
869                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given");
870                         }catch(Exception e1){
871                                 logger.error("Exception occured while sending error in response" +e1);
872                         }
873                         im.endTransaction();
874                         return;
875                 }
876                 //
877                 // Limit the Content-Length to something reasonable
878                 //
879                 try{
880                         if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
881                                 String message = "Content-Length larger than server will accept.";
882                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
883                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
884                                 loggingContext.transactionEnded();
885                                 PolicyLogger.audit("Transaction Failed - See Error.log");
886                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
887                                 im.endTransaction();
888                                 return;
889                         }
890                 }catch(Exception e){
891                         logger.error("Exception occured while getting max content length"+e);
892                 }
893                 
894                 if (request.getContentLength() <= 0) {
895                         String message = "Content-Length is negative";
896                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
897                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
898                         loggingContext.transactionEnded();
899                         PolicyLogger.audit("Transaction Failed - See Error.log");
900                         try{
901                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
902                         }catch(Exception e1){
903                                 logger.error("Exception occured while sending error in response" +e1);
904                         }
905                         im.endTransaction();
906                         return;
907                 }
908                 ContentType contentType = null;
909                 try {
910                         contentType = ContentType.parse(request.getContentType());
911                 }
912                 catch (Exception e) {
913                         String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage();
914                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e);
915                         loggingContext.transactionEnded();
916                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message);
917                         PolicyLogger.audit("Transaction Failed - See Error.log");
918                         try{
919                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
920                         }catch(Exception e1){
921                                 logger.error("Exception occured while sending error in response" +e1);
922                         }
923                         im.endTransaction();
924                         return;
925                 }
926                 //
927                 // What exactly did they send us?
928                 //
929                 String incomingRequestString = null;
930                 Request pdpRequest = null;
931                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) ||
932                                 contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
933                                 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) {
934                         //
935                         // Read in the string
936                         //
937                         StringBuilder buffer = new StringBuilder();
938                         BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
939                         String line;
940                         try{
941                                 while((line = reader.readLine()) != null){
942                                         buffer.append(line);
943                                 }
944                         }catch(Exception e){
945                                 logger.error("Exception Occured while reading line"+e);
946                         }
947                         
948                         incomingRequestString = buffer.toString();
949                         logger.info(incomingRequestString);
950                         //
951                         // Parse into a request
952                         //
953                         try {
954                                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
955                                         pdpRequest = JSONRequest.load(incomingRequestString);
956                                 } else if (     contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
957                                                 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
958                                         pdpRequest = DOMRequest.load(incomingRequestString);
959                                 }
960                         }
961                         catch(Exception e) {
962                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e);
963                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request");
964                                 loggingContext.transactionEnded();
965                                 PolicyLogger.audit("Transaction Failed - See Error.log");
966                                 try{
967                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
968                                 }catch(Exception e1){
969                                         logger.error("Exception occured while sending error in response" +e1);
970                                 }
971                                 im.endTransaction();
972                                 return;
973                         }
974                 } else {
975                         String message = "unsupported content type" + request.getContentType();
976                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
977                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
978                         loggingContext.transactionEnded();
979                         PolicyLogger.audit("Transaction Failed - See Error.log");
980                         try{
981                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
982                         }catch(Exception e1){
983                                 logger.error("Exception occured while sending error in response" +e1);
984                         }
985                         im.endTransaction();
986                         return;
987                 }
988                 //
989                 // Did we successfully get and parse a request?
990                 //
991                 if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) {
992                         String message = "Zero Attributes found in the request";
993                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
994                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
995                         loggingContext.transactionEnded();
996                         PolicyLogger.audit("Transaction Failed - See Error.log");
997                         try{
998                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
999                         }catch(Exception e1){
1000                                 logger.error("Exception occured while sending error in response" +e1);
1001                         }
1002                         im.endTransaction();
1003                         return;
1004                 }
1005                 //
1006                 // Run it
1007                 //
1008                 try {
1009                         //
1010                         // Authenticating the Request here. 
1011                         //
1012                         if(!authorizeRequest(request)){
1013                                 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1014                                 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1015                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message);
1016                                 loggingContext.transactionEnded();
1017                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1018                                 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1019                                 im.endTransaction();
1020                                 return;
1021                         }
1022                         //
1023                         // Get the pointer to the PDP Engine
1024                         //
1025                         PDPEngine myEngine = null;
1026                         synchronized(pdpEngineLock) {
1027                                 myEngine = XACMLPdpServlet.pdpEngine;
1028                         }
1029                         if (myEngine == null) {
1030                                 String message = "No engine loaded.";
1031                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message);
1032                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
1033                                 loggingContext.transactionEnded();
1034                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1035                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1036                                 im.endTransaction();
1037                                 return;
1038                         }
1039                         //
1040                         // Send the request and save the response
1041                         //
1042                         long lTimeStart;
1043                         long lTimeEnd;
1044                         Response pdpResponse    = null;
1045
1046                         synchronized(pdpEngineLock) {
1047                                 myEngine = XACMLPdpServlet.pdpEngine;
1048                                 try {
1049                                         PolicyList.clearPolicyList();
1050                                         lTimeStart = System.currentTimeMillis();                
1051                                         pdpResponse     = myEngine.decide(pdpRequest);
1052                                         lTimeEnd = System.currentTimeMillis();
1053                                 } catch (PDPException e) {
1054                                         String message = "Exception during decide: " + e.getMessage();
1055                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message +e);
1056                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
1057                                         loggingContext.transactionEnded();
1058                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1059                                         try{
1060                                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1061                                         }catch(Exception e1){
1062                                                 logger.error("Exception occured while sending error in response" +e1);
1063                                         }
1064                                         im.endTransaction();
1065                                         return;
1066                                 }
1067                         }
1068                         monitor.computeLatency(lTimeEnd - lTimeStart);  
1069                         requestLogger.info(lTimeStart + "=" + incomingRequestString);
1070                         for(String policy : PolicyList.getpolicyList()){
1071                                 monitor.policyCountAdd(policy, 1);
1072                         }
1073
1074
1075                         logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList());
1076
1077                         //need to go through the list and find out if the value is unique and then add it other wise 
1078                         //                      monitor.policyCountAdd(PolicyList.getpolicyList(), 1);
1079
1080                         if (logger.isDebugEnabled()) {
1081                                 logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms");
1082                         }
1083                         //
1084                         // Convert Response to appropriate Content-Type
1085                         //
1086                         if (pdpResponse == null) {
1087                                 requestLogger.info(lTimeStart + "=" + "{}");
1088                                 try{
1089                                         throw new PDPException("Failed to get response from PDP engine.");
1090                                 }catch(Exception e1){
1091                                         logger.error("Exception occured while throwing Exception" +e1);
1092                                 }
1093                         }
1094                         //
1095                         // Set our content-type
1096                         //
1097                         response.setContentType(contentType.getMimeType());
1098                         //
1099                         // Convert the PDP response object to a String to
1100                         // return to our caller as well as dump to our loggers.
1101                         //
1102                         String outgoingResponseString = "";
1103                         try{
1104                                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
1105                                         //
1106                                         // Get it as a String. This is not very efficient but we need to log our
1107                                         // results for auditing.
1108                                         //
1109                                         outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled());
1110                                         if (logger.isDebugEnabled()) {
1111                                                 logger.debug(outgoingResponseString);
1112                                                 //
1113                                                 // Get rid of whitespace
1114                                                 //
1115                                                 outgoingResponseString = JSONResponse.toString(pdpResponse, false);
1116                                         }
1117                                 } else if (     contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
1118                                                 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
1119                                         //
1120                                         // Get it as a String. This is not very efficient but we need to log our
1121                                         // results for auditing.
1122                                         //
1123                                         outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled());
1124                                         if (logger.isDebugEnabled()) {
1125                                                 logger.debug(outgoingResponseString);
1126                                                 //
1127                                                 // Get rid of whitespace
1128                                                 //
1129                                                 outgoingResponseString = DOMResponse.toString(pdpResponse, false);
1130                                         }
1131                                 }       
1132                                 //      adding the jmx values for NA, Permit and Deny
1133                                 //
1134                                 if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){
1135                                         monitor.pdpEvaluationNA();
1136                                 }
1137
1138                                 if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){
1139                                         monitor.pdpEvaluationPermit();
1140                                 }
1141
1142                                 if (outgoingResponseString.contains("Deny")){
1143                                         monitor.pdpEvaluationDeny();
1144                                 }
1145                                 //
1146                                 // lTimeStart is used as an ID within the requestLogger to match up
1147                                 // request's with responses.
1148                                 //
1149                                 requestLogger.info(lTimeStart + "=" + outgoingResponseString);
1150                                 response.getWriter().print(outgoingResponseString);
1151                         }catch(Exception e){
1152                                 logger.error("Exception Occured"+e );
1153                         }
1154                 }
1155                 catch (Exception e) {
1156                         String message = "Exception executing request: " + e;
1157                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e);
1158                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message);
1159                         loggingContext.transactionEnded();
1160                         PolicyLogger.audit("Transaction Failed - See Error.log");
1161                         try{
1162                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1163                         }catch(Exception e1){
1164                                 logger.error("Exception occured while sending error in response" +e1);
1165                         }
1166                         return;
1167                 }
1168
1169                 monitor.pdpEvaluationSuccess();
1170                 response.setStatus(HttpServletResponse.SC_OK);
1171
1172                 loggingContext.transactionEnded();
1173                 auditLogger.info("Success");
1174                 PolicyLogger.audit("Success");
1175
1176         }
1177
1178         /*
1179          * Added for Authorizing the PEP Requests for Environment check. 
1180          */
1181         private boolean authorizeRequest(HttpServletRequest request) {
1182                 // Get the client Credentials from the Request header. 
1183                 HttpServletRequest httpServletRequest = request;
1184                 String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER);
1185                 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
1186                         return true;
1187                 }else{
1188                         return false;
1189                 }
1190         }
1191
1192         @Override
1193         public void run() {
1194                 //
1195                 // Keep running until we are told to terminate
1196                 //
1197                 try {
1198                         // variable not used, but constructor has needed side-effects so don't remove:
1199                         while (! this.configThreadTerminate) {
1200                                 PutRequest request = XACMLPdpServlet.queue.take();
1201                                 StdPDPStatus newStatus = new StdPDPStatus();
1202                                 
1203                                 PDPEngine newEngine = null;
1204                                 synchronized(pdpStatusLock) {
1205                                         XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION);
1206                                         newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties);
1207                                 }
1208                                 if (newEngine != null) {
1209                                         synchronized(XACMLPdpServlet.pdpEngineLock) {
1210                                                 XACMLPdpServlet.pdpEngine = newEngine;
1211                                                 try {
1212                                                         logger.info("Saving configuration.");
1213                                                         if (request.policyProperties != null) {
1214                                                                 try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) {
1215                                                                         request.policyProperties.store(os, "");
1216                                                                 }
1217                                                         }
1218                                                         if (request.pipConfigProperties != null) {
1219                                                                 try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) {
1220                                                                         request.pipConfigProperties.store(os, "");
1221                                                                 }
1222                                                         }
1223                                                         newStatus.setStatus(Status.UP_TO_DATE);
1224                                                 } catch (Exception e) {
1225                                                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties."+e);
1226                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties");
1227                                                         newStatus.setStatus(Status.LOAD_ERRORS);
1228                                                         newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage());
1229                                                 }
1230                                         }
1231                                 } else {
1232                                         newStatus.setStatus(Status.LAST_UPDATE_FAILED);
1233                                 }
1234                                 synchronized(pdpStatusLock) {
1235                                         XACMLPdpServlet.status.set(newStatus);
1236                                 }
1237                         }
1238                 } catch (InterruptedException e) {
1239                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted"+e);
1240                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted");
1241                         Thread.currentThread().interrupt();
1242                 }
1243         }       
1244
1245         public static PDPEngine getPDPEngine(){
1246                 PDPEngine myEngine = null;
1247                 synchronized(pdpEngineLock) {
1248                         myEngine = XACMLPdpServlet.pdpEngine;
1249                 }
1250                 return myEngine;
1251         }
1252
1253         public static Constructor<?> getCreateUpdatePolicyConstructor(){
1254                 return createUpdatePolicyConstructor;
1255         }
1256         
1257         private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{
1258                 try{
1259                         Class<?> createUpdateclass = Class.forName(createUpdateResourceName);
1260                         createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class);
1261                 }catch(Exception e){
1262                         PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init" +e);
1263                         throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage());
1264                 }
1265         }
1266 }