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