12dfbd23bf130d60519f2ef17a82ff9c130f185d
[policy/engine.git] / ECOMP-PDP-REST / src / main / java / org / openecomp / policy / pdp / rest / XACMLPdpServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-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.openecomp.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.openecomp.policy.api.PolicyParameters;
52 import org.openecomp.policy.common.im.AdministrativeStateException;
53 import org.openecomp.policy.common.im.ForwardProgressException;
54 import org.openecomp.policy.common.im.IntegrityMonitor;
55 import org.openecomp.policy.common.im.IntegrityMonitorProperties;
56 import org.openecomp.policy.common.im.StandbyStatusException;
57 import org.openecomp.policy.common.logging.ECOMPLoggingContext;
58 import org.openecomp.policy.common.logging.ECOMPLoggingUtils;
59 import org.openecomp.policy.common.logging.eelf.MessageCodes;
60 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
61 import org.openecomp.policy.pdp.rest.jmx.PdpRestMonitor;
62 import org.openecomp.policy.rest.XACMLRest;
63 import org.openecomp.policy.rest.XACMLRestProperties;
64 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
65 import org.openecomp.policy.xacml.pdp.std.functions.PolicyList;
66 import org.openecomp.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.openecomp.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         public 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 ECOMPLoggingContext 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 ECOMPLoggingContext();
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");
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                 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.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                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
419                         return;
420                 }
421                 //
422                 // What is being PUT?
423                 //
424                 String cache = request.getParameter("cache");
425                 //
426                 // Should be a list of policy and pip configurations in Java properties format
427                 //
428                 if (cache != null && request.getContentType().equals("text/x-java-properties")) {
429                         loggingContext.setServiceName("PDP.putConfig");
430                         if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) {
431                                 String message = "Content-Length larger than server will accept.";
432                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
433                                 loggingContext.transactionEnded();
434                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
435                                 PolicyLogger.audit("Transaction Failed - See Error.log");
436                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
437                                 im.endTransaction();
438                                 return;
439                         }
440                         this.doPutConfig(cache, request, response, loggingContext);
441                         loggingContext.transactionEnded();
442                         PolicyLogger.audit("Transaction ended");
443
444                         im.endTransaction();
445                 } else {
446                         String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'";
447                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message);
448                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
449                         loggingContext.transactionEnded();
450                         PolicyLogger.audit("Transaction Failed - See Error.log");
451                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
452                         im.endTransaction();
453                         return;
454                 }
455         }
456
457         protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext)  throws ServletException, IOException {
458                 try {
459                         // prevent multiple configuration changes from stacking up
460                         if (XACMLPdpServlet.queue.remainingCapacity() <= 0) {
461                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached");
462                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached");
463                                 loggingContext.transactionEnded();
464                                 PolicyLogger.audit("Transaction Failed - See Error.log");
465                                 response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing.");
466                                 return;
467                         }
468                         //
469                         // Read the properties data into an object.
470                         //
471                         Properties newProperties = new Properties();
472                         newProperties.load(request.getInputStream());
473                         // should have something in the request
474                         if (newProperties.size() == 0) {
475                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT");
476                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT");
477                                 loggingContext.transactionEnded();
478                                 PolicyLogger.audit("Transaction Failed - See Error.log");
479                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property");
480                                 return;
481                         }
482                         //
483                         // Which set of properties are they sending us? Whatever they send gets
484                         // put on the queue (if there is room).
485                         // For audit logging purposes, we consider the transaction done once the
486                         // the request gets put on the queue.
487                         //
488                         if (config.equals("policies")) {
489                                 newProperties = XACMLProperties.getPolicyProperties(newProperties, true);
490                                 if (newProperties.size() == 0) {
491                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT");
492                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT");
493                                         loggingContext.transactionEnded();
494                                         PolicyLogger.audit("Transaction Failed - See Error.log");
495                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property");
496                                         return;
497                                 }
498                                 XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null));
499                                 loggingContext.transactionEnded();
500                                 auditLogger.info("Success");
501                                 PolicyLogger.audit("Success");
502                         } else if (config.equals("pips")) {
503                                 newProperties = XACMLProperties.getPipProperties(newProperties);
504                                 if (newProperties.size() == 0) {
505                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT");
506                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT");
507                                         loggingContext.transactionEnded();
508                                         PolicyLogger.audit("Transaction Failed - See Error.log");
509                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property");
510                                         return;
511                                 }
512                                 XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties));
513                                 loggingContext.transactionEnded();
514                                 auditLogger.info("Success");
515                                 PolicyLogger.audit("Success");
516                         } else if (config.equals("all")) {
517                                 Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true);
518                                 if (newPolicyProperties.size() == 0) {
519                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT");
520                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT");
521                                         loggingContext.transactionEnded();
522                                         PolicyLogger.audit("Transaction Failed - See Error.log");
523                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property");
524                                         return;
525                                 }
526                                 Properties newPipProperties = XACMLProperties.getPipProperties(newProperties);
527                                 if (newPipProperties.size() == 0) {
528                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT");
529                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT");
530                                         loggingContext.transactionEnded();
531                                         PolicyLogger.audit("Transaction Failed - See Error.log");
532                                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property");
533                                         return;
534                                 }
535                                 XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties));
536                                 loggingContext.transactionEnded();
537                                 auditLogger.info("Success");
538                                 PolicyLogger.audit("Success");
539                         } else {
540                                 //
541                                 // Invalid value
542                                 //
543                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config);
544                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config);
545                                 loggingContext.transactionEnded();
546                                 PolicyLogger.audit("Transaction Failed - See Error.log");
547                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'");
548                                 return;
549                         }
550                 } catch (Exception e) {
551                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e);
552                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration");
553                         loggingContext.transactionEnded();
554                         PolicyLogger.audit("Transaction Failed - See Error.log");
555                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
556                         return;
557                 }
558
559         }
560
561         /**
562          * Parameters: type=hb|config|Status
563          * 
564          * 1. HeartBeat Status 
565          * HeartBeat
566          *              OK - All Policies are Loaded, All PIPs are Loaded
567          *      LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration
568          *      LAST_UPDATE_FAILED - Need to track the items that failed during last update
569          *      LOAD_FAILURE - ??? Need to determine what information is sent and how 
570          * 2. Configuration
571          * 3. Status
572          *              return the StdPDPStatus object in the Response content
573          * 
574          * 
575          * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
576          */
577         @Override
578         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
579                 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
580                 loggingContext.transactionStarted();
581                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
582                         UUID requestID = UUID.randomUUID();
583                         loggingContext.setRequestID(requestID.toString());
584                         PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one");
585                 } else {
586                         PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)");
587                 }
588                 loggingContext.metricStarted();
589                 loggingContext.metricEnded();
590                 PolicyLogger.metrics("Metric example posted here - 1 of 2");
591                 loggingContext.metricStarted();
592                 loggingContext.metricEnded();
593                 PolicyLogger.metrics("Metric example posted here - 2 of 2");
594
595                 XACMLRest.dumpRequest(request);
596
597                 String pathInfo = request.getRequestURI();
598                 if (pathInfo != null){
599                         // health check from Global Site Selector (iDNS).
600                         // DO NOT do a im.startTransaction for the test request
601                         if (pathInfo.equals("/pdp/test")) {
602                                 loggingContext.setServiceName("iDNS:PDP.test");
603                                 try {
604                                         im.evaluateSanity();
605                                         //If we make it this far, all is well
606                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
607                                         PolicyLogger.debug(message);
608                                         loggingContext.transactionEnded();
609                                         PolicyLogger.audit("Success");
610                                         response.setStatus(HttpServletResponse.SC_OK);
611                                         return;
612                                 } catch (ForwardProgressException fpe){
613                                         //No forward progress is being made
614                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress."
615                                                         + " Exception Message: " + fpe.getMessage();
616                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
617                                         loggingContext.transactionEnded();
618                                         PolicyLogger.audit("Transaction Failed - See Error.log");
619                                         // PolicyLogger.audit(MessageCodes.ERROR_SYSTEM_ERROR, message );
620                                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
621                                         return;
622                                 }catch (AdministrativeStateException ase){
623                                         //Administrative State is locked
624                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Administrative State is LOCKED "
625                                                         + " Exception Message: " + ase.getMessage();
626                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
627                                         loggingContext.transactionEnded();
628                                         PolicyLogger.audit("Transaction Failed - See Error.log");
629                                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
630                                         return;
631                                 }catch (StandbyStatusException sse){
632                                         //Administrative State is locked
633                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Standby Status is NOT PROVIDING SERVICE "
634                                                         + " Exception Message: " + sse.getMessage();
635                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
636                                         loggingContext.transactionEnded();
637                                         PolicyLogger.audit("Transaction Failed - See Error.log");
638                                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
639                                         return;
640                                 } catch (Exception e) {
641                                         //A subsystem is not making progress or is not responding
642                                         String eMsg = e.getMessage();
643                                         if(eMsg == null){
644                                                 eMsg = "No Exception Message";
645                                         }
646                                         String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
647                                                         + " Exception Message: " + eMsg;
648                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message );
649                                         //Get the specific list of subsystems that failed
650                                         String failedNodeList = null;
651                                         for(String node : dependencyNodes){
652                                                 if(eMsg.contains(node)){
653                                                         if(failedNodeList == null){
654                                                                 failedNodeList = node;
655                                                         }else{
656                                                                 failedNodeList = failedNodeList.concat(","+node);
657                                                         }
658                                                 }
659                                         }
660                                         if(failedNodeList == null){
661                                                 failedNodeList = "UnknownSubSystem";
662                                         }
663                                         response.addHeader("X-ECOMP-SubsystemFailure", failedNodeList);
664                                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
665                                         loggingContext.transactionEnded();
666                                         PolicyLogger.audit("Transaction Failed - See Error.log");
667                                         return;
668                                 }
669                         }
670                 }
671
672                 try {
673                         im.startTransaction();
674                 }
675                 catch (AdministrativeStateException | StandbyStatusException e) {
676                         String message = e.toString();
677                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
678                         loggingContext.transactionEnded();
679                         PolicyLogger.audit("Transaction Failed - See Error.log");
680                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
681                         return;
682                 }
683                 //
684                 // What are they requesting?
685                 //
686                 boolean returnHB = false;
687                 response.setHeader("Cache-Control", "no-cache");
688                 String type = request.getParameter("type");
689                 // type might be null, so use equals on string constants
690                 if ("config".equals(type)) {
691                         loggingContext.setServiceName("PDP.getConfig");
692                         response.setContentType("text/x-java-properties");
693                         try {
694                                 String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
695                                 lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n";
696                                 try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes());
697                                                 InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig());
698                                                 OutputStream os = response.getOutputStream()) {
699                                         IOUtils.copy(listInputStream, os);
700                                         IOUtils.copy(pipInputStream, os);
701                                 }
702                                 loggingContext.transactionEnded();
703                                 auditLogger.info("Success");
704                                 PolicyLogger.audit("Success");
705                                 response.setStatus(HttpServletResponse.SC_OK);
706                         } catch (Exception e) {
707                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e);
708                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file");
709                                 loggingContext.transactionEnded();
710                                 PolicyLogger.audit("Transaction Failed - See Error.log");
711                                 response.sendError(400, "Failed to copy Property file");
712                         }
713
714                 } else if ("hb".equals(type)) {
715                         returnHB = true;
716                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
717
718                 } else if ("Status".equals(type)) {
719                         loggingContext.setServiceName("PDP.getStatus");
720                         // convert response object to JSON and include in the response
721                         synchronized(pdpStatusLock) {
722                                 ObjectMapper mapper = new ObjectMapper();
723                                 mapper.writeValue(response.getOutputStream(),  status);
724                         }
725                         response.setStatus(HttpServletResponse.SC_OK);
726                         loggingContext.transactionEnded();
727                         auditLogger.info("Success");
728                         PolicyLogger.audit("Success");
729
730                 } else {
731                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type);
732                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type);
733                         loggingContext.transactionEnded();
734                         PolicyLogger.audit("Transaction Failed - See Error.log");
735                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'");
736                 }
737                 if (returnHB) {
738                         synchronized(pdpStatusLock) {
739                                 response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
740                         }
741                 }
742                 loggingContext.transactionEnded();
743                 PolicyLogger.audit("Transaction Ended");
744                 im.endTransaction();
745
746         }
747
748         /**
749          * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON according
750          * to the XACML 3.0 Specifications for both.
751          * 
752          * 
753          * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
754          */
755         @Override
756         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
757
758                 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
759                 loggingContext.transactionStarted();
760                 loggingContext.setServiceName("PDP.decide");
761                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
762                         UUID requestID = UUID.randomUUID();
763                         loggingContext.setRequestID(requestID.toString());
764                         PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one");
765                 } else {
766                         PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)");
767                 }
768                 loggingContext.metricStarted();
769                 loggingContext.metricEnded();
770                 PolicyLogger.metrics("Metric example posted here - 1 of 2");
771                 loggingContext.metricStarted();
772                 loggingContext.metricEnded();
773                 PolicyLogger.metrics("Metric example posted here - 2 of 2");
774                 monitor.pdpEvaluationAttempts();
775
776                 try {
777                         im.startTransaction();
778                 }
779                 catch (AdministrativeStateException | StandbyStatusException e) {
780                         String message = e.toString();
781                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e);
782                         loggingContext.transactionEnded();
783                         PolicyLogger.audit("Transaction Failed - See Error.log");
784                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
785                         return;
786                 }
787                 //
788                 // no point in doing any work if we know from the get-go that we cannot do anything with the request
789                 //
790                 if (status.getLoadedRootPolicies().isEmpty()) {
791                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded");
792                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded");
793                         loggingContext.transactionEnded();
794                         PolicyLogger.audit("Transaction Failed - See Error.log");
795                         response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
796                         im.endTransaction();
797                         return;
798                 }
799
800                 XACMLRest.dumpRequest(request);
801                 //
802                 // Set our no-cache header
803                 //
804                 response.setHeader("Cache-Control", "no-cache");
805                 //
806                 // They must send a Content-Type
807                 //
808                 if (request.getContentType() == null) {
809                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type");
810                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type");
811                         loggingContext.transactionEnded();
812                         PolicyLogger.audit("Transaction Failed - See Error.log");
813                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given");
814                         im.endTransaction();
815                         return;
816                 }
817                 //
818                 // Limit the Content-Length to something reasonable
819                 //
820                 if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
821                         String message = "Content-Length larger than server will accept.";
822                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
823                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
824                         loggingContext.transactionEnded();
825                         PolicyLogger.audit("Transaction Failed - See Error.log");
826                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
827                         im.endTransaction();
828                         return;
829                 }
830                 if (request.getContentLength() <= 0) {
831                         String message = "Content-Length is negative";
832                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
833                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
834                         loggingContext.transactionEnded();
835                         PolicyLogger.audit("Transaction Failed - See Error.log");
836                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
837                         im.endTransaction();
838                         return;
839                 }
840                 ContentType contentType = null;
841                 try {
842                         contentType = ContentType.parse(request.getContentType());
843                 }
844                 catch (Exception e) {
845                         String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage();
846                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e);
847                         loggingContext.transactionEnded();
848                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message);
849                         PolicyLogger.audit("Transaction Failed - See Error.log");
850                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
851                         im.endTransaction();
852                         return;
853                 }
854                 //
855                 // What exactly did they send us?
856                 //
857                 String incomingRequestString = null;
858                 Request pdpRequest = null;
859                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) ||
860                                 contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
861                                 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) {
862                         //
863                         // Read in the string
864                         //
865                         StringBuilder buffer = new StringBuilder();
866                         BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
867                         String line;
868                         try{
869                                 while((line = reader.readLine()) != null){
870                                         buffer.append(line);
871                                 }
872                         }catch(Exception e){
873                                 logger.error("Exception Occured while reading line"+e);
874                         }
875                         
876                         incomingRequestString = buffer.toString();
877                         logger.info(incomingRequestString);
878                         //
879                         // Parse into a request
880                         //
881                         try {
882                                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
883                                         pdpRequest = JSONRequest.load(incomingRequestString);
884                                 } else if (     contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
885                                                 contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
886                                         pdpRequest = DOMRequest.load(incomingRequestString);
887                                 }
888                         }
889                         catch(Exception e) {
890                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e);
891                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request");
892                                 loggingContext.transactionEnded();
893                                 PolicyLogger.audit("Transaction Failed - See Error.log");
894                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
895                                 im.endTransaction();
896                                 return;
897                         }
898                 } else {
899                         String message = "unsupported content type" + request.getContentType();
900                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
901                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
902                         loggingContext.transactionEnded();
903                         PolicyLogger.audit("Transaction Failed - See Error.log");
904                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
905                         im.endTransaction();
906                         return;
907                 }
908                 //
909                 // Did we successfully get and parse a request?
910                 //
911                 if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) {
912                         String message = "Zero Attributes found in the request";
913                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
914                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
915                         loggingContext.transactionEnded();
916                         PolicyLogger.audit("Transaction Failed - See Error.log");
917                         response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
918                         im.endTransaction();
919                         return;
920                 }
921                 //
922                 // Run it
923                 //
924                 try {
925                         //
926                         // Authenticating the Request here. 
927                         //
928                         if(!authorizeRequest(request)){
929                                 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
930                                 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
931                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message);
932                                 loggingContext.transactionEnded();
933                                 PolicyLogger.audit("Transaction Failed - See Error.log");
934                                 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
935                                 im.endTransaction();
936                                 return;
937                         }
938                         //
939                         // Get the pointer to the PDP Engine
940                         //
941                         PDPEngine myEngine = null;
942                         synchronized(pdpEngineLock) {
943                                 myEngine = XACMLPdpServlet.pdpEngine;
944                         }
945                         if (myEngine == null) {
946                                 String message = "No engine loaded.";
947                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message);
948                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
949                                 loggingContext.transactionEnded();
950                                 PolicyLogger.audit("Transaction Failed - See Error.log");
951                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
952                                 im.endTransaction();
953                                 return;
954                         }
955                         //
956                         // Send the request and save the response
957                         //
958                         long lTimeStart;
959                         long lTimeEnd;
960                         Response pdpResponse    = null;
961
962                         synchronized(pdpEngineLock) {
963                                 myEngine = XACMLPdpServlet.pdpEngine;
964                                 try {
965                                         PolicyList.clearPolicyList();
966                                         lTimeStart = System.currentTimeMillis();                
967                                         pdpResponse     = myEngine.decide(pdpRequest);
968                                         lTimeEnd = System.currentTimeMillis();
969                                 } catch (PDPException e) {
970                                         String message = "Exception during decide: " + e.getMessage();
971                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message +e);
972                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
973                                         loggingContext.transactionEnded();
974                                         PolicyLogger.audit("Transaction Failed - See Error.log");
975                                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
976                                         im.endTransaction();
977                                         return;
978                                 }
979                         }
980                         monitor.computeLatency(lTimeEnd - lTimeStart);  
981                         requestLogger.info(lTimeStart + "=" + incomingRequestString);
982                         for(String policy : PolicyList.getpolicyList()){
983                                 monitor.policyCountAdd(policy, 1);
984                         }
985
986
987                         logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList());
988
989                         //need to go through the list and find out if the value is unique and then add it other wise 
990                         //                      monitor.policyCountAdd(PolicyList.getpolicyList(), 1);
991
992                         if (logger.isDebugEnabled()) {
993                                 logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms");
994                         }
995                         //
996                         // Convert Response to appropriate Content-Type
997                         //
998                         if (pdpResponse == null) {
999                                 requestLogger.info(lTimeStart + "=" + "{}");
1000                                 throw new PDPException("Failed to get response from PDP engine.");
1001                         }
1002                         //
1003                         // Set our content-type
1004                         //
1005                         response.setContentType(contentType.getMimeType());
1006                         //
1007                         // Convert the PDP response object to a String to
1008                         // return to our caller as well as dump to our loggers.
1009                         //
1010                         String outgoingResponseString = "";
1011                         if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
1012                                 //
1013                                 // Get it as a String. This is not very efficient but we need to log our
1014                                 // results for auditing.
1015                                 //
1016                                 outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled());
1017                                 if (logger.isDebugEnabled()) {
1018                                         logger.debug(outgoingResponseString);
1019                                         //
1020                                         // Get rid of whitespace
1021                                         //
1022                                         outgoingResponseString = JSONResponse.toString(pdpResponse, false);
1023                                 }
1024                         } else if (     contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) ||
1025                                         contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
1026                                 //
1027                                 // Get it as a String. This is not very efficient but we need to log our
1028                                 // results for auditing.
1029                                 //
1030                                 outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled());
1031                                 if (logger.isDebugEnabled()) {
1032                                         logger.debug(outgoingResponseString);
1033                                         //
1034                                         // Get rid of whitespace
1035                                         //
1036                                         outgoingResponseString = DOMResponse.toString(pdpResponse, false);
1037                                 }
1038                         }
1039                         //      adding the jmx values for NA, Permit and Deny
1040                         //
1041                         if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){
1042                                 monitor.pdpEvaluationNA();
1043                         }
1044
1045                         if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){
1046                                 monitor.pdpEvaluationPermit();
1047                         }
1048
1049                         if (outgoingResponseString.contains("Deny")){
1050                                 monitor.pdpEvaluationDeny();
1051                         }
1052                         //
1053                         // lTimeStart is used as an ID within the requestLogger to match up
1054                         // request's with responses.
1055                         //
1056                         requestLogger.info(lTimeStart + "=" + outgoingResponseString);
1057                         response.getWriter().print(outgoingResponseString);
1058                 }
1059                 catch (Exception e) {
1060                         String message = "Exception executing request: " + e;
1061                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e);
1062                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message);
1063                         loggingContext.transactionEnded();
1064                         PolicyLogger.audit("Transaction Failed - See Error.log");
1065                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1066                         return;
1067                 }
1068
1069                 monitor.pdpEvaluationSuccess();
1070                 response.setStatus(HttpServletResponse.SC_OK);
1071
1072                 loggingContext.transactionEnded();
1073                 auditLogger.info("Success");
1074                 PolicyLogger.audit("Success");
1075
1076         }
1077
1078         /*
1079          * Added for Authorizing the PEP Requests for Environment check. 
1080          */
1081         private boolean authorizeRequest(HttpServletRequest request) {
1082                 // Get the client Credentials from the Request header. 
1083                 HttpServletRequest httpServletRequest = request;
1084                 String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER);
1085                 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
1086                         return true;
1087                 }else{
1088                         return false;
1089                 }
1090         }
1091
1092         @Override
1093         public void run() {
1094                 //
1095                 // Keep running until we are told to terminate
1096                 //
1097                 try {
1098                         // variable not used, but constructor has needed side-effects so don't remove:
1099                         while (! this.configThreadTerminate) {
1100                                 PutRequest request = XACMLPdpServlet.queue.take();
1101                                 StdPDPStatus newStatus = new StdPDPStatus();
1102                                 
1103                                 PDPEngine newEngine = null;
1104                                 synchronized(pdpStatusLock) {
1105                                         XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION);
1106                                         newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties);
1107                                 }
1108                                 if (newEngine != null) {
1109                                         synchronized(XACMLPdpServlet.pdpEngineLock) {
1110                                                 XACMLPdpServlet.pdpEngine = newEngine;
1111                                                 try {
1112                                                         logger.info("Saving configuration.");
1113                                                         if (request.policyProperties != null) {
1114                                                                 try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) {
1115                                                                         request.policyProperties.store(os, "");
1116                                                                 }
1117                                                         }
1118                                                         if (request.pipConfigProperties != null) {
1119                                                                 try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) {
1120                                                                         request.pipConfigProperties.store(os, "");
1121                                                                 }
1122                                                         }
1123                                                         newStatus.setStatus(Status.UP_TO_DATE);
1124                                                 } catch (Exception e) {
1125                                                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties."+e);
1126                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties");
1127                                                         newStatus.setStatus(Status.LOAD_ERRORS);
1128                                                         newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage());
1129                                                 }
1130                                         }
1131                                 } else {
1132                                         newStatus.setStatus(Status.LAST_UPDATE_FAILED);
1133                                 }
1134                                 synchronized(pdpStatusLock) {
1135                                         XACMLPdpServlet.status.set(newStatus);
1136                                 }
1137                         }
1138                 } catch (InterruptedException e) {
1139                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted"+e);
1140                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted");
1141                         Thread.currentThread().interrupt();
1142                 }
1143         }       
1144
1145         public static PDPEngine getPDPEngine(){
1146                 PDPEngine myEngine = null;
1147                 synchronized(pdpEngineLock) {
1148                         myEngine = XACMLPdpServlet.pdpEngine;
1149                 }
1150                 return myEngine;
1151         }
1152
1153         public static Constructor<?> getCreateUpdatePolicyConstructor(){
1154                 return createUpdatePolicyConstructor;
1155         }
1156         
1157         private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{
1158                 try{
1159                         Class<?> createUpdateclass = Class.forName(createUpdateResourceName);
1160                         createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class);
1161                 }catch(Exception e){
1162                         PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init");
1163                         throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage());
1164                 }
1165         }
1166 }