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