Fix compilation issue due to generic Exception
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / XACMLPapServlet.java
index 53d801b..bedc212 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-PAP-REST
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -40,9 +40,9 @@ import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Properties;
+import java.util.Scanner;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.CopyOnWriteArrayList;
@@ -64,6 +64,7 @@ import org.onap.policy.common.ia.IntegrityAudit;
 import org.onap.policy.common.im.AdministrativeStateException;
 import org.onap.policy.common.im.ForwardProgressException;
 import org.onap.policy.common.im.IntegrityMonitor;
+import org.onap.policy.common.im.IntegrityMonitorException;
 import org.onap.policy.common.im.IntegrityMonitorProperties;
 import org.onap.policy.common.im.StandbyStatusException;
 import org.onap.policy.common.logging.ONAPLoggingContext;
@@ -80,13 +81,14 @@ import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
 import org.onap.policy.rest.XACMLRest;
 import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.dao.PolicyDBException;
+import org.onap.policy.utils.CryptoUtils;
 import org.onap.policy.utils.PolicyUtils;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
 import org.onap.policy.xacml.api.pap.OnapPDP;
 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
-import org.onap.policy.xacml.std.pap.StdPAPPolicy;
 import org.onap.policy.xacml.std.pap.StdPDP;
 import org.onap.policy.xacml.std.pap.StdPDPGroup;
 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
@@ -121,6 +123,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
        private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
        // Client Headers. 
        private static final String ENVIRONMENT_HEADER = "Environment";
+       private static final String ADD_GROUP_ERROR = "addGroupError";
+       private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
+       
+       private static final String REGEX = "[0-9a-zA-Z._ ]*";
+       
        /*
         * List of Admin Console URLs.
         * Used to send notifications when configuration changes.
@@ -128,10 +135,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         * The CopyOnWriteArrayList *should* protect from concurrency errors.
         * This list is seldom changed but often read, so the costs of this approach make sense.
         */
-       private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<String>();       
+       private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();     
        
-       private static String CONFIG_HOME;
-       private static String ACTION_HOME;
+       private static String configHome;
+       private static String actionHome;
        /*
         * This PAP instance's own URL.
         * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. 
@@ -155,26 +162,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
        private static String papDbUrl = null;
        private static String papDbUser = null;
        private static String papDbPassword = null;
-       private static Integer papTransWait = null;
-       private static Integer papTransTimeout = null;
-       private static Integer papAuditTimeout = null;
-       private static Boolean papAuditFlag = null;
-       private static Boolean papFileSystemAudit = null;
        private static String papResourceName = null;
-       private static Integer fpMonitorInterval = null; 
-       private static Integer failedCounterThreshold = null;
-       private static Integer testTransInterval = null;
-       private static Integer writeFpcInterval = null;
-       private static String papSiteName=null;
-       private static String papNodeType=null; 
-       private static String papDependencyGroups = null;
        private static String[] papDependencyGroupsFlatArray = null;
        private static String environment = null;
        private static String pdpFile = null;
        
-       private String storedRequestId = null;
-       private IntegrityMonitor im;
-       private IntegrityAudit ia;
+       private transient IntegrityMonitor im;
+       private transient IntegrityAudit ia;
        
        //MicroService Model Properties
        private static String msOnapName;
@@ -183,8 +177,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
         * this servlet starts. Its configurable by the admin.
         */
-       private Thread initiateThread = null;
-       private ONAPLoggingContext baseLoggingContext = null;
+       private static transient Thread initiateThread = null;
+       private transient ONAPLoggingContext baseLoggingContext = null;
        
        /**
         * @see HttpServlet#HttpServlet()
@@ -205,7 +199,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                String hostname = InetAddress.getLocalHost().getCanonicalHostName();
                                baseLoggingContext.setServer(hostname);
                        } catch (UnknownHostException e) {
-                               LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging");
+                               LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
                        }
                        // Initialize
                        XACMLRest.xacmlInit(config);
@@ -214,92 +208,40 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        /*
                         * Retrieve the property values
                         */
-                       CONFIG_HOME = getConfigHome();
-                       ACTION_HOME = getActionHome();
-                       papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
-                       if(papDbDriver == null){
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
-                               throw new PAPException("papDbDriver is null");
-                       }
-                       setPapDbDriver(papDbDriver);
-                       papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
-                       if(papDbUrl == null){
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
-                               throw new PAPException("papDbUrl is null");
-                       }
-                       setPapDbUrl(papDbUrl);
-                       papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
-                       if(papDbUser == null){
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
-                               throw new PAPException("papDbUser is null");
-                       }
-                       setPapDbUser(papDbUser);
-                       papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
-                       if(papDbPassword == null){
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
-                               throw new PAPException("papDbPassword is null");
-                       }
-                       setPapDbPassword(papDbPassword);
-                       papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
-                       if(papResourceName == null){
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
-                               throw new PAPException("papResourceName is null");
-                       }
-                       papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
+                       setCommonProperties();
+                       String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
                        if(papSiteName == null){
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
                                throw new PAPException("papSiteName is null");
                        }
-                       papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
+                       String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
                        if(papNodeType == null){
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
                                throw new PAPException("papNodeType is null");
                        }
-                       environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
                        //Integer will throw an exception of anything is missing or unrecognized
-                       papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
-                       papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
-                       papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
+                       int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
+                       int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
+                       int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
                        //Boolean will default to false if anything is missing or unrecognized
-                       papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
-                       papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
-                       papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
+                       boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
+                       boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
+                       String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
                        if(papDependencyGroups == null){
                                throw new PAPException("papDependencyGroups is null");
                        }
-                       try{
-                               //Now we have flattened the array into a simple comma-separated list
-                               papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
-                               //clean up the entries
-                               for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
-                                       papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
-                               }
-                               try{
-                                       if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
-                                               papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
-                                       }
-                               }catch(Exception e){
-                                       String msg = "integrity_audit_period_seconds ";
-                                       LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
-                                       PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
-                                       throw e;
-                               }
-                       }catch(Exception e){
-                               PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
-                               throw e;
-                       }
+                       setPAPDependencyGroups(papDependencyGroups);
                        //Integer will throw an exception of anything is missing or unrecognized
-                       fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
-                       failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
-                       testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
-                       writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
+                       int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
+                       int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
+                       int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
+                       int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
                        LOGGER.debug("\n\n\n**************************************"
-                                       + "\n**************************************"
+                                       + "\n*************************************"
                                        + "\n"
                                        + "\n   papDbDriver = " + papDbDriver
                                        + "\n   papDbUrl = " + papDbUrl
                                        + "\n   papDbUser = " + papDbUser
-                                       + "\n   papDbPassword = " + papDbPassword
                                        + "\n   papTransWait = " + papTransWait
                                        + "\n   papTransTimeout = " + papTransTimeout
                                        + "\n   papAuditTimeout = " + papAuditTimeout
@@ -314,7 +256,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        + "\n   papNodeType = " + papNodeType
                                        + "\n   papDependencyGroupsList = " + papDependencyGroups
                                        + "\n   papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
-                                       + "\n\n**************************************"
+                                       + "\n\n*************************************"
                                        + "\n**************************************");
                        // Pull custom persistence settings
                        Properties properties;
@@ -330,62 +272,63 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                + "XACMLProperties.getProperties()");
                                throw new ServletException(e.getMessage(), e.getCause());
                        }
-                       //Micro Service Properties
-                       msOnapName=properties.getProperty("xacml.policy.msOnapName");
-                       setMsOnapName(msOnapName);
-                       msPolicyName=properties.getProperty("xacml.policy.msPolicyName");
-                       setMsPolicyName(msPolicyName);
-                       // PDPId File location 
-                       XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
-                       if (XACMLPapServlet.pdpFile == null) {
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
-                                       + XACMLRestProperties.PROP_PDP_IDFILE);
-                               throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
-                       }
                        // Create an IntegrityMonitor
+                       if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
+                               properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
+                       }
                        im = IntegrityMonitor.getInstance(papResourceName,properties);
                        // Create an IntegrityAudit
                        ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
                        ia.startAuditThread();
                        // Create the entity manager factory
-                       emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
-                       if (emf == null) {
-                               PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
-                                               + PERSISTENCE_UNIT);
-                               throw new ServletException("Unable to create Entity Manager Factory");
-                       }
+                       setEMF(properties);
                        // we are about to call the PDPs and give them their configuration.
                        // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
-                       XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+                       setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
                        //Create the policyDBDao
-                       policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
+                       setPolicyDBDao();
                        // Load our PAP engine, first create a factory
                        ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
                        // The factory knows how to go about creating a PAP Engine
-                       XACMLPapServlet.papEngine = (PAPPolicyEngine) factory.newEngine();
+                       setPAPEngine((PAPPolicyEngine) factory.newEngine());
                        PolicyDBDaoTransaction addNewGroup = null;
-                       try{
-                               if(((org.onap.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){
-                                       addNewGroup = policyDBDao.getNewTransaction();
-                                       OnapPDPGroup group = papEngine.getDefaultGroup();
-                                       addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
-                                       addNewGroup.commitTransaction();
-                                       addNewGroup = policyDBDao.getNewTransaction();
-                                       addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
-                                       addNewGroup.commitTransaction();
-                               }
-                       } catch(Exception e){
-                               PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database");
-                               if(addNewGroup != null){
-                                       addNewGroup.rollbackTransaction();
-                               }
-                       }
+            if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
+                try {
+                    addNewGroup = policyDBDao.getNewTransaction();
+                    OnapPDPGroup group = papEngine.getDefaultGroup();
+                    addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
+                            "automaticallyAdded");
+                    addNewGroup.commitTransaction();
+                    addNewGroup = policyDBDao.getNewTransaction();
+                    addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
+                    addNewGroup.commitTransaction();
+                } catch (Exception e) {
+                    PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
+                            " Error creating new default group in the database");
+                    if (addNewGroup != null) {
+                        addNewGroup.rollbackTransaction();
+                    }
+                }
+            }
                        policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
-                       //boolean performFileToDatabaseAudit = false;
                if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
+                       /*
+                        * Auditing the local File System groups to be in sync with the Database
+                        */
+                       
                        //get an AuditTransaction to lock out all other transactions
                        PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
-                       policyDBDao.auditLocalDatabase(XACMLPapServlet.papEngine);
+                       
+                       LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
+                LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
+                       //get the current filesystem group and update from the database if needed
+                StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
+                StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
+                if(updatedGroup!=null) {
+                       papEngine.updateGroup(updatedGroup);
+                }    
+                LOGGER.info("PapServlet:  updated group is " + papEngine.getDefaultGroup().toString());
+                
                        //release the transaction lock
                        auditTrans.close();
                }
@@ -397,13 +340,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
                        // to all its known PDP nodes.
                        if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
-                               this.initiateThread = new Thread(this);
-                               this.initiateThread.start();
+                           startInitiateThreadService(new Thread(this));
                        }
                        // After startup, the PAP does Heartbeat's to each of the PDPs periodically
-                       XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine);
-                       XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
-                       XACMLPapServlet.heartbeatThread.start();
+                       startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
 
                } catch (FactoryException | PAPException e) {
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
@@ -414,7 +354,122 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                }
        }
 
-       /**
+       private static void startInitiateThreadService(Thread thread) {
+           initiateThread = thread;
+        initiateThread.start();
+    }
+
+    private static void mapperWriteValue(ObjectMapper mapper,  HttpServletResponse response, Object value) {
+        try {
+            mapper.writeValue(response.getOutputStream(), value);
+        } catch (Exception e) {
+            LOGGER.error(e);
+        }
+    }
+
+    private static void startHeartBeatService(Heartbeat heartbeat) {
+           XACMLPapServlet.heartbeat = heartbeat;
+        XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
+        XACMLPapServlet.heartbeatThread.start();
+    }
+
+    private static void setPolicyDBDao() throws ServletException {
+           try {
+            policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
+        } catch (Exception e) {
+            throw new ServletException("Unable to Create Policy DBDao Instance",e);
+        }
+    }
+
+    private static void setEMF(Properties properties) throws ServletException {
+           emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
+        if (emf == null) {
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
+                    + PERSISTENCE_UNIT);
+            throw new ServletException("Unable to create Entity Manager Factory");
+        }
+    }
+
+    private static void setPAPURL(String papURL) {
+           XACMLPapServlet.papURL = papURL;
+    }
+
+    private static void setPAPEngine(PAPPolicyEngine newEngine) {
+           XACMLPapServlet.papEngine = newEngine;
+    }
+
+    private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
+           try{
+            //Now we have flattened the array into a simple comma-separated list
+            papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
+            //clean up the entries
+            for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
+                papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
+            }
+            try{
+                if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
+                    papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
+                }
+            }catch(Exception e){
+                String msg = "integrity_audit_period_seconds ";
+                LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
+                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
+                throw e;
+            }
+        }catch(Exception e){
+            PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
+            throw new PAPException(e);
+        }
+    }
+
+    private static void setCommonProperties() throws PAPException {
+           setConfigHome();
+        setActionHome();
+        papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
+        if(papDbDriver == null){
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
+            throw new PAPException("papDbDriver is null");
+        }
+        setPapDbDriver(papDbDriver);
+        papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
+        if(papDbUrl == null){
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
+            throw new PAPException("papDbUrl is null");
+        }
+        setPapDbUrl(papDbUrl);
+        papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
+        if(papDbUser == null){
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
+            throw new PAPException("papDbUser is null");
+        }
+        setPapDbUser(papDbUser);
+        papDbPassword = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""));
+        if(papDbPassword == null){
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
+            throw new PAPException("papDbPassword is null");
+        }
+        setPapDbPassword(papDbPassword);
+        papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
+        if(papResourceName == null){
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
+            throw new PAPException("papResourceName is null");
+        }
+        environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
+        //Micro Service Properties
+        msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
+        setMsOnapName(msOnapName);
+        msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
+        setMsPolicyName(msPolicyName);
+        // PDPId File location 
+        XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
+        if (XACMLPapServlet.pdpFile == null) {
+            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
+                + XACMLRestProperties.PROP_PDP_IDFILE);
+            throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
+        }
+    }
+
+    /**
         * Thread used only during PAP startup to initiate change messages to all known PDPs.
         * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
         */
@@ -430,6 +485,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
         * For now we assume that we do care.
         */
+       @Override
        public void destroy() {
                // Make sure our threads are destroyed
                if (XACMLPapServlet.heartbeatThread != null) {
@@ -441,14 +497,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                XACMLPapServlet.heartbeatThread.interrupt();
                                XACMLPapServlet.heartbeatThread.join();
                        } catch (InterruptedException e) {
+                           XACMLPapServlet.heartbeatThread.interrupt();
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
                        }
                }
-               if (this.initiateThread != null) {
+               if (initiateThread != null) {
                        try {
-                               this.initiateThread.interrupt();
-                               this.initiateThread.join();
+                               initiateThread.interrupt();
+                               initiateThread.join();
                        } catch (InterruptedException e) {
+                           initiateThread.interrupt();
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
                        }
                }
@@ -473,31 +531,49 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
                }
                PolicyDBDaoTransaction pdpTransaction = null;
+               loggingContext.metricStarted();
                try {
                        im.startTransaction();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
                } catch (AdministrativeStateException ae){
                        String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
                                        + " state of " + im.getStateManager().getAdminState()
-                                       + "\n Exception Message: " + ae.getMessage();
-                       LOGGER.info(message);
-                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
-                       loggingContext.transactionEnded();
+                                       + "\n Exception Message: " +  PolicyUtils.CATCH_EXCEPTION;
+                       LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
+                       loggingContext.transactionEnded();                      
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }catch (StandbyStatusException se) {
                        String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
                                        + " of " + im.getStateManager().getStandbyStatus()
                                        + "\n Exception Message: " + se.getMessage();
-                       LOGGER.info(message);
-                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+                       LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
+                       loggingContext.transactionEnded();
+                       PolicyLogger.audit("Transaction Failed - See Error.log");
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       return;
+               } catch (IntegrityMonitorException e) {
+                       String message = "POST interface called for PAP " + papResourceName + " but an exception occurred"
+                                       + "\n Exception Message: " + e.getMessage();
+                       LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }
                try {
+                       loggingContext.metricStarted();
                        XACMLRest.dumpRequest(request);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
                        // since getParameter reads the content string, explicitly get the content before doing that.
                        // Simply getting the inputStream seems to protect it against being consumed by getParameter.
                        request.getInputStream();
@@ -512,12 +588,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                                loggingContext.transactionEnded();
                                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                                               response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
+                                               setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
                                                im.endTransaction();
                                                return;
                                        }
                                }
+                               loggingContext.metricStarted();
                                doACPost(request, response, groupId, loggingContext);
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Ended Successfully");
                                im.endTransaction();
@@ -540,18 +619,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        try {
                                                pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
                                                XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
-                                       } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) {
+                                       } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
                                                pdpTransaction.rollbackTransaction();
                                                String message = "Failed to create new PDP for id: " + id;
                                                PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
                                                loggingContext.transactionEnded();
                                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                                               response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+                                               setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                                                im.endTransaction();
                                                return;
                                        }
                                        // get the PDP we just created
-                                       pdp = XACMLPapServlet.papEngine.getPDP(id);
+                           try{
+                               pdp = XACMLPapServlet.papEngine.getPDP(id);
+                           }catch(PAPException e){
+                               LOGGER.error(e);
+                           }
                                        if (pdp == null) {
                                                if(pdpTransaction != null){
                                                        pdpTransaction.rollbackTransaction();
@@ -560,35 +643,47 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
                                                loggingContext.transactionEnded();
                                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                                               response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                                               setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                                                im.endTransaction();
                                                return;
                                        }
                                } else {
                                        String message = "PDP is Unauthorized to Connect to PAP: "+ id;
-                                       PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                        loggingContext.transactionEnded();
-                                       response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
+                                       PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
+                                       setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
                                        im.endTransaction();
                                        return;
                                }
                                try{
+                                       loggingContext.metricStarted();
                                        pdpTransaction.commitTransaction();
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
                                } catch(Exception e){
                                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
                                }
                        }
                        if (jmxport != null && jmxport != ""){
-                               ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
+                           try{
+                       ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
+                           }catch(NumberFormatException e){
+                               LOGGER.error(e);
+                           }
                        }
                        // Get the PDP's Group
-                       OnapPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
+                       OnapPDPGroup group =null;
+                       try{
+                   group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
+                       }catch(PAPException e){
+                           LOGGER.error(e);
+                       }
                        if (group == null) {
                                PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
+                               setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
                                im.endTransaction();
                                return;
                        }
@@ -598,7 +693,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        Properties pipconfig = group.getPipConfigProperties();
                        // Get the current policy/pip configuration that the PDP has
                        Properties pdpProperties = new Properties();
-                       pdpProperties.load(request.getInputStream());
+                       try{
+                   pdpProperties.load(request.getInputStream());
+                       }catch(IOException e){
+                           LOGGER.error(e);
+                       }
                        LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
                        LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
                        LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
@@ -613,33 +712,52 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        // retrieve them.
                                        this.populatePolicyURL(request.getRequestURL(), policies);
                                        // Copy the properties to the output stream
-                                       policies.store(response.getOutputStream(), "");
+                                       try{
+                                           policies.store(response.getOutputStream(), "");
+                                       }catch(IOException e){
+                               LOGGER.error(e);
+                           }
                                }
                                if (pipconfig != null) {
                                        // Copy the properties to the output stream
-                                       pipconfig.store(response.getOutputStream(), "");
+                                       try{
+                                           pipconfig.store(response.getOutputStream(), "");
+                                       }catch(IOException e){
+                               LOGGER.error(e);
+                           }
                                }
                                // We are good - and we are sending them information
                                response.setStatus(HttpServletResponse.SC_OK);
-                               setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
+                               try{
+                                   setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
+                               }catch(PAPException e){
+                       LOGGER.error(e);
+                   }
                        } else {
                                // Tell them they are good
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
-                               setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
+                               try{
+                                   setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
+                               }catch(PAPException e){
+                       LOGGER.error(e);
+                   }
                        }
                        // tell the AC that something changed
+                       loggingContext.metricStarted();
                        notifyAC();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
                        loggingContext.transactionEnded();
                        auditLogger.info("Success");
                        PolicyLogger.audit("Transaction Ended Successfully");
-               } catch (PAPException e) {
+               } catch (PAPException | IOException | NumberFormatException e) {
                        if(pdpTransaction != null){
                                pdpTransaction.rollbackTransaction();
                        }
                        LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        im.endTransaction();
                        return;
                }
@@ -649,7 +767,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                im.endTransaction();
        }
 
-       /**
+       private void setResponseError(HttpServletResponse response,int responseCode, String message) {
+           try {
+               if(message != null && !message.isEmpty()){
+                      response.sendError(responseCode, message);
+               }
+        } catch (IOException e) {
+            LOGGER.error("Error setting Error response Header ", e);
+        }
+           return;
+    }
+
+    /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
@@ -664,38 +793,57 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
                }
                try {
+                       loggingContext.metricStarted();
                        XACMLRest.dumpRequest(request);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
                        String pathInfo = request.getRequestURI();
                        LOGGER.info("path info: " + pathInfo);
                        if (pathInfo != null){
                                //DO NOT do a im.startTransaction for the test request
                                if (pathInfo.equals("/pap/test")) {
-                                       testService(loggingContext, response);
+                                       try {
+                                               testService(loggingContext, response);
+                                       } catch (IOException e) {
+                                               LOGGER.debug(e);
+                                       }
                                        return;
                                }
                        }
                        //This im.startTransaction() covers all other Get transactions
                        try {
+                               loggingContext.metricStarted();
                                im.startTransaction();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
                        } catch (AdministrativeStateException ae){
                                String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
                                                + " state of " + im.getStateManager().getAdminState()
                                                + "\n Exception Message: " + ae.getMessage();
-                               LOGGER.info(message);
+                               LOGGER.info(message, ae);
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                               setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                                return;
                        }catch (StandbyStatusException se) {
                                String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
                                                + " of " + im.getStateManager().getStandbyStatus()
                                                + "\n Exception Message: " + se.getMessage();
-                               LOGGER.info(message);
+                               LOGGER.info(message, se);
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                               setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                               return;
+                       } catch (IntegrityMonitorException e) {
+                               String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
+                                               + "\n Exception Message: " + e.getMessage();
+                               LOGGER.info(message, e);
+                               PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+                               loggingContext.transactionEnded();
+                               PolicyLogger.audit("Transaction Failed - See Error.log");
+                               setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                                return;
                        }
                        // Request from the API to get the gitPath
@@ -703,7 +851,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        if (apiflag!=null) {
                                if(authorizeRequest(request)){
                                        APIRequestHandler apiRequestHandler = new APIRequestHandler();
-                                       apiRequestHandler.doGet(request,response, apiflag);
+                                       try{                            
+                                               loggingContext.metricStarted();
+                                           apiRequestHandler.doGet(request,response, apiflag);
+                                               loggingContext.metricEnded();
+                                               PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
+                                       }catch(IOException e){
+                                           LOGGER.error(e);
+                                       }
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Ended Successfully");
                                        im.endTransaction();
@@ -713,7 +868,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
+                                       setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
                                        im.endTransaction();
                                        return;
                                }
@@ -722,7 +877,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        String groupId = request.getParameter("groupId");
                        if (groupId != null) {
                                // this is from the Admin Console, so handle separately
-                               doACGet(request, response, groupId, loggingContext);
+                               try{
+                                       loggingContext.metricStarted();
+                                   doACGet(request, response, groupId, loggingContext);
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
+                               } catch(IOException e){
+                    LOGGER.error(e);
+                }
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Ended Successfully");
                                im.endTransaction();
@@ -732,19 +894,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        String id = this.getPDPID(request);
                        LOGGER.info("doGet from: " + id);
                        // Get the PDP Object
-                       OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
+                       OnapPDP pdp = null;
+                       try{
+                           pdp = XACMLPapServlet.papEngine.getPDP(id);
+                       }catch(PAPException e){
+                           LOGGER.error(e);
+                       }
                        // Is it known?
                        if (pdp == null) {
                                // Check if request came from localhost
                                if (request.getRemoteHost().equals("localhost") ||
-                                               request.getRemoteHost().equals("127.0.0.1") ||
                                                request.getRemoteHost().equals(request.getLocalAddr())) {
                                        // Return status information - basically all the groups
                                        loggingContext.setServiceName("PAP.getGroups");
                                        Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
                                        // convert response object to JSON and include in the response
-                                       ObjectMapper mapper = new ObjectMapper();
-                                       mapper.writeValue(response.getOutputStream(),  groups);
+                                       mapperWriteValue(new ObjectMapper(), response,  groups);
                                        response.setHeader("content-type", "application/json");
                                        response.setStatus(HttpServletResponse.SC_OK);
                                        loggingContext.transactionEnded();
@@ -756,19 +921,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
+                               setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
                                im.endTransaction();
                                return;
                        }
                        loggingContext.setServiceName("PAP.getPolicy");
                        // Get the PDP's Group
-                       OnapPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
+                       OnapPDPGroup group = null;
+                       try {
+                           group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
+                       } catch (PAPException e) {
+                           LOGGER.error(e);
+                       }
                        if (group == null) {
                                String message = "No group associated with pdp " + pdp.getId();
                                LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
+                               setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
                                im.endTransaction();
                                return;
                        }
@@ -779,7 +949,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+                               setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
                                im.endTransaction();
                                return;
                        }
@@ -789,12 +959,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+                               setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
                                im.endTransaction();
                                return;
                        }
-                       LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
-                                       + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
+                       try{
+                   LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
+                           + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
+                       } catch (PAPException| IOException e){
+                           LOGGER.error(e);
+                       }
                        try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
                                // Send the policy back
                                IOUtils.copy(is, os);
@@ -804,16 +978,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.audit("Transaction Ended Successfully");
                        } catch (IOException e) {
                                String message = "Failed to open policy id " + policyId;
+                               LOGGER.debug(e);
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+                               setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
                        }
                }  catch (PAPException e) {
+                       LOGGER.debug(e);
                        PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        im.endTransaction();
                        return;
                }
@@ -827,7 +1003,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         */
        protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
-               storedRequestId = loggingContext.getRequestID();
                loggingContext.transactionStarted();
                loggingContext.setServiceName("PAP.put");
                if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
@@ -838,46 +1013,57 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
                }
                try {
+                       loggingContext.metricStarted();
                        im.startTransaction();
-               } catch (AdministrativeStateException ae){
-                       String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative"
-                                       + " state of " + im.getStateManager().getAdminState()
-                                       + "\n Exception Message: " + ae.getMessage();
-                       LOGGER.info(message +ae);
-                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
-                       loggingContext.transactionEnded();
-                       PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                       return;
-               }catch (StandbyStatusException se) {
-                       String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
-                                       + " of " + im.getStateManager().getStandbyStatus()
-                                       + "\n Exception Message: " + se.getMessage();
-                       LOGGER.info(message  +se);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
+               } catch (IntegrityMonitorException e) {
+                       String message = "PUT interface called for PAP " + papResourceName;
+                       if (e instanceof AdministrativeStateException) {
+                               message += " but it has an Administrative state of "
+                                       + im.getStateManager().getAdminState();
+                       } else if (e instanceof StandbyStatusException) {
+                               message += " but it has a Standby Status of "
+                                       + im.getStateManager().getStandbyStatus();
+                       } else {
+                               message += " but an exception occurred";
+
+                       }
+                       message += "\n Exception Message: " + e.getMessage();
+
+                       LOGGER.info(message, e);
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }
+
+               loggingContext.metricStarted();
                XACMLRest.dumpRequest(request);
+               loggingContext.metricEnded();
+               PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
                //need to check if request is from the API or Admin console
                String apiflag = request.getParameter("apiflag");
                //This would occur if a PolicyDBDao notification was received
                String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
                if(policyDBDaoRequestUrl != null){
+                       LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
                        String policyDBDaoRequestEntityId = request.getParameter("entityid");
-                       //String policyDBDaoRequestEntityType = request.getParameter("entitytype");
                        String policyDBDaoRequestEntityType = request.getParameter("entitytype");
                        String policyDBDaoRequestExtraData = request.getParameter("extradata");
                        if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
-                               response.sendError(400, "entityid or entitytype not supplied");
+                               setResponseError(response,400, "entityid or entitytype not supplied");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Ended Successfully");
                                im.endTransaction();
                                return;
                        }
-                       policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);                     
+                       loggingContext.metricStarted(); 
+                       LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
+                       policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
                        response.setStatus(200);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Ended Successfully");
@@ -891,7 +1077,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                if (importService != null) {
                        if(authorizeRequest(request)){
                                APIRequestHandler apiRequestHandler = new APIRequestHandler();
-                               apiRequestHandler.doPut(request, response, importService);
+                               try{
+                                       loggingContext.metricStarted(); 
+                                   apiRequestHandler.doPut(request, response, importService);
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
+                               }catch(IOException e){
+                                   LOGGER.error(e);
+                               }
                                im.endTransaction();
                                return;
                        } else {
@@ -899,7 +1092,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
+                               setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
                                return;
                        }
                }
@@ -922,7 +1115,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        } catch(UnsupportedEncodingException e){
                                PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
                                                + "\npolicyToCreateUpdate = " + " ");
-                               response.sendError(500,"policyToCreateUpdate encoding not supported"
+                               setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToCreateUpdate encoding not supported"
                                                + "\nfailure with the following exception: " + e);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See error.log");
@@ -935,14 +1128,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
                        }catch(Exception e){
                                renameTransaction.rollbackTransaction();
-                               response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
+                               setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
                                                + "\nfailure with the following exception: " + e);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See error.log");
                                im.endTransaction();
                                return;
                        }
+                       loggingContext.metricStarted();
                        renameTransaction.commitTransaction();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet goPut commitTransaction");
                        response.setStatus(HttpServletResponse.SC_OK);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Ended Successfully");
@@ -982,11 +1178,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
+                                       setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
                                        return;
                                }
                                if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
-                                       updateGroupsFromAPI(request, response, groupId, loggingContext);
+                                   try{
+                                       updateGroupsFromAPI(request, response, groupId, loggingContext);
+                                   }catch(IOException e){
+                                       LOGGER.error(e);
+                                   }
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Ended Successfully");
                                        im.endTransaction();
@@ -994,7 +1194,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                }
                        }
                        // this is from the Admin Console, so handle separately
-                       doACPut(request, response, groupId, loggingContext);
+                       try {
+                               loggingContext.metricEnded();
+                           doACPut(request, response, groupId, loggingContext);
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
+                       } catch (IOException e) {
+                LOGGER.error(e);
+            }
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Ended Successfully");
                        im.endTransaction();
@@ -1006,7 +1213,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
                        // this request is from the Admin Console
                        SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
-                       savePolicyHandler.doPolicyAPIPut(request, response);
+                       try{
+                               loggingContext.metricStarted();
+                           savePolicyHandler.doPolicyAPIPut(request, response);
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
+                       } catch (IOException e) {
+                LOGGER.error(e);
+            }
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Ended Successfully");
                        im.endTransaction();
@@ -1015,7 +1229,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        // this request is from the Policy Creation API 
                        if(authorizeRequest(request)){
                                APIRequestHandler apiRequestHandler = new APIRequestHandler();
-                               apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
+                               try{
+                                       loggingContext.metricStarted();
+                                   apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
+                   } catch (IOException e) {
+                       LOGGER.error(e);
+                   }
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Ended Successfully");
                                im.endTransaction();
@@ -1025,7 +1246,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
+                               setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
                                im.endTransaction();
                                return;
                        }
@@ -1035,7 +1256,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
                loggingContext.transactionEnded();
                PolicyLogger.audit("Transaction Failed - See Error.log");
-               response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
+               setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
                loggingContext.transactionEnded();
                PolicyLogger.audit("Transaction Failed - See error.log");
                im.endTransaction();
@@ -1056,29 +1277,44 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
                }
                try {
+                       loggingContext.metricStarted();
                        im.startTransaction();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
                } catch (AdministrativeStateException ae){
                        String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
                                        + " state of " + im.getStateManager().getAdminState()
                                        + "\n Exception Message: " + ae.getMessage();
-                       LOGGER.info(message);
+                       LOGGER.info(message, ae);
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }catch (StandbyStatusException se) {
                        String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
                                        + " of " + im.getStateManager().getStandbyStatus()
                                        + "\n Exception Message: " + se.getMessage();
-                       LOGGER.info(message);
+                       LOGGER.info(message, se);
+                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
+                       loggingContext.transactionEnded();
+                       PolicyLogger.audit("Transaction Failed - See Error.log");
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       return;
+               } catch (IntegrityMonitorException e) {
+                       String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
+                                       + "\n Exception Message: " + e.getMessage();
+                       LOGGER.info(message, e);
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }
+               loggingContext.metricStarted();
                XACMLRest.dumpRequest(request);
+               loggingContext.metricEnded();
+               PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
                String groupId = request.getParameter("groupId");
                String apiflag = request.getParameter("apiflag");
                if (groupId != null) {
@@ -1089,22 +1325,32 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
+                                       setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
                                        return;
                                }
                                APIRequestHandler apiRequestHandler = new APIRequestHandler();
                                try {
+                                       loggingContext.metricStarted();
                                        apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
                                } catch (Exception e) {
                                        LOGGER.error("Exception Occured"+e);
                                }
                                if(apiRequestHandler.getNewGroup()!=null){
-                                       groupChanged(apiRequestHandler.getNewGroup());
+                                       groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
                                }
                                return;
                        }
                        // this is from the Admin Console, so handle separately
-                       doACDelete(request, response, groupId, loggingContext);
+                       try{
+                               loggingContext.metricStarted();
+                           doACDelete(request, response, groupId, loggingContext);
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
+                       } catch (IOException e) {
+                LOGGER.error(e);
+            }
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Ended Successfully");
                        im.endTransaction();
@@ -1114,7 +1360,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
                loggingContext.transactionEnded();
                PolicyLogger.audit("Transaction Failed - See Error.log");
-               response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
+               setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
                im.endTransaction();
        }
 
@@ -1193,52 +1439,36 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         */
        public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
                PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
+               PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
                try {
                        // for PUT operations the group may or may not need to exist before the operation can be done
                        StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
+                       
                        // get the request input stream content into a String
                        String json = null;
                        java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
                        scanner.useDelimiter("\\A");
                        json =  scanner.hasNext() ? scanner.next() : "";
                        scanner.close();
-                       PolicyLogger.info("JSON request from PolicyEngine API: " + json);
+
+                       PolicyLogger.info("pushPolicy request from API: " + json);
+                       
                        // convert Object sent as JSON into local object
                        StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
-                       Set<PDPPolicy> policies = new HashSet<>();
-                       if(policy!=null){
-                               policies.add(policy);
-                       }
+                       
                        //Get the current policies from the Group and Add the new one
                        Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
                        currentPoliciesInGroup = group.getPolicies();
-                       //If the selected policy is in the group we must remove it because the name is default
-                       Iterator<PDPPolicy> policyIterator = policies.iterator();
-                       LOGGER.debug("policyIterator....." + policies);
-                       while (policyIterator.hasNext()) {
-                               PDPPolicy selPolicy = policyIterator.next();
-                               for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
-                                       if (existingPolicy.getId().equals(selPolicy.getId())) {
-                                               group.removePolicyFromGroup(existingPolicy);
-                                               LOGGER.debug("Removing policy: " + existingPolicy);
-                                               break;
-                                       }
-                               }
-                       }
-                       //Update the PDP Group after removing old version of policy
-                       Set<PDPPolicy> updatedPoliciesInGroup = new HashSet<>();
-                       updatedPoliciesInGroup = group.getPolicies();
-                       //need to remove the policy with default name from group
-                       for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
-                               if (updatedPolicy.getName().equalsIgnoreCase("default")) {
-                                       group.removePolicyFromGroup(updatedPolicy);
+                       //If the selected policy is in the group we must remove the old version of it
+                       LOGGER.info("Removing old version of the policy");
+                       for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
+                               if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
+                                       group.removePolicy(existingPolicy);
+                                       LOGGER.info("Removing policy: " + existingPolicy);
                                        break;
                                }
                        }
-                       if(updatedPoliciesInGroup!=null){
-                               policies.addAll(updatedPoliciesInGroup);
-                       }
-                       group.setPolicies(policies);
+                       
                        // Assume that this is an update of an existing PDP Group
                        loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
                        try{
@@ -1248,28 +1478,43 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                +"group="+group.getId());
                                throw new PAPException(e.getMessage()); 
                        }
+                       
+                       LOGGER.info("Calling updatGroup() with new group");
                        papEngine.updateGroup(group);
                        String policyId = "empty";
-                       if(policy!=null){
+                       if(policy !=null && policy.getId() != null){
                                policyId = policy.getId();
                        }
+                       if(!policyId.matches(REGEX) ){
+                               response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                               response.addHeader("error",ADD_GROUP_ERROR);
+                               response.addHeader("message", "Policy Id is not valid");
+                               return;
+                       }
                        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                        response.addHeader("operation", "push");
                        response.addHeader("policyId", policyId);
                        response.addHeader("groupId", groupId);
-                       if (LOGGER.isDebugEnabled()) {          
-                               LOGGER.debug("Group '" + group.getId() + "' updated");
-                       }
+                       
+                       LOGGER.info("Group '" + group.getId() + "' updated");
+                       
+                       loggingContext.metricStarted();
                        acPutTransaction.commitTransaction();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
+                       loggingContext.metricStarted();
                        notifyAC();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
+
                        // Group changed, which might include changing the policies     
-                       groupChanged(group);
+                       groupChanged(group, loggingContext);
                        loggingContext.transactionEnded();
-                       auditLogger.info("Success");
+                       LOGGER.info("Success");
 
                        if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
                                PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
-                               if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) {
+                               if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
                                        LOGGER.debug("Precheck Successful.");
                                }
                        }
@@ -1282,9 +1527,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
                        String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-                       response.addHeader("error","addGroupError");
+                       response.addHeader("error",ADD_GROUP_ERROR);
                        response.addHeader("message", message);
                        return;
                }
@@ -1309,20 +1554,28 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        if (groupName != null && groupDescription != null) {
                                // Args:              group=<groupId> groupName=<name> groupDescription=<description>            <= create a new group
                                loggingContext.setServiceName("AC:PAP.createGroup");
-                               String unescapedName = URLDecoder.decode(groupName, "UTF-8");
-                               String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
+                               String unescapedName = null;
+                               String unescapedDescription = null;
+                               try{
+                                   unescapedName = URLDecoder.decode(groupName, "UTF-8");
+                                   unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
+                               } catch (UnsupportedEncodingException e) {
+                                   LOGGER.error(e);
+                               }
                                PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
                                try {                                   
                                        newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
                                        papEngine.newGroup(unescapedName, unescapedDescription);
+                                       loggingContext.metricStarted();
                                        newGroupTransaction.commitTransaction();
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
                                } catch (Exception e) {
                                        newGroupTransaction.rollbackTransaction();
                                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
                                        loggingContext.transactionEnded();
-       
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(500, "Unable to create new group '" + groupId + "'");
+                                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
                                        return;
                                }
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
@@ -1330,7 +1583,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        LOGGER.debug("New Group '" + groupId + "' created");
                                }
                                // tell the Admin Consoles there is a change
+                               loggingContext.metricStarted();
                                notifyAC();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
                                // new group by definition has no PDPs, so no need to notify them of changes
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
@@ -1339,9 +1595,21 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                return;
                        }
                        // for all remaining POST operations the group must exist before the operation can be done
-                       OnapPDPGroup group = papEngine.getGroup(groupId);
+                       OnapPDPGroup group = null;
+                       try{
+                           group = papEngine.getGroup(groupId);
+                       } catch (PAPException e){
+                           LOGGER.error(e);
+                       }
                        if (group == null) {
                                String message = "Unknown groupId '" + groupId + "'";
+                               //for fixing Header Manipulation of Fortify issue
+                               if(!message.matches(REGEX)){
+                                       response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                                       response.addHeader("error",ADD_GROUP_ERROR);
+                                       response.addHeader("message", "GroupId Id is not valid");
+                                       return;
+                               }
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
@@ -1351,61 +1619,45 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        response.addHeader("message", message);
                                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                                } else {
-                                       response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+                                       setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
                                }
                                return;
                        }
-                       // determine the operation needed based on the parameters in the request
+                       
+                       // If the request contains a policyId then we know we are pushing the policy to PDP
                        if (request.getParameter("policyId") != null) {
-                               //      Args:        group=<groupId> policy=<policyId>          <= copy file
-                               // copy a policy from the request contents into a file in the group's directory on this machine
+                               
                                if(apiflag!=null){
                                        loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
+                                       LOGGER.info("PushPolicy Request From The API");
                                } else {
                                        loggingContext.setServiceName("AC:PAP.postPolicy");
+                                       LOGGER.info("PushPolicy Request From The AC");
                                }
+                               
                                String policyId = request.getParameter("policyId");
                                PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
+                               StdPDPGroup updatedGroup = null;
                                try {
-                                       InputStream is = null;
-                                       File temp= null;
-                                       if (apiflag != null){
-                                               // get the request content into a String if the request is from API 
-                                               String json = null;
-                                               // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
-                                               java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
-                                               scanner.useDelimiter("\\A");
-                                               json =  scanner.hasNext() ? scanner.next() : "";
-                                               scanner.close();
-                                               LOGGER.info("JSON request from API: " + json);
-                                               // convert Object sent as JSON into local object
-                                               ObjectMapper mapper = new ObjectMapper();
-                                               Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
-                                               StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
-                                               temp = new File(policy.getLocation());
-                                               is = new FileInputStream(temp);
-                                       } else {
-                                               is = request.getInputStream();
-                                       }
-                                       addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
-                       if (apiflag != null){
-                           ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is);
-                       } else {
-                               String name = null;
-                               if (policyId.endsWith(".xml")) {
-                                       name = policyId.replace(".xml", "");
-                                       name = name.substring(0, name.lastIndexOf("."));
-                                               }
-                               ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is);
-                       }
-                       if(is!=null && temp!=null){
-                               is.close();
-                                               temp.delete();
-                       }
+                                       //Copying the policy to the file system and updating groups in database
+                                       LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
+                                       updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
+                                       loggingContext.metricStarted();
                                        addPolicyToGroupTransaction.commitTransaction();
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
+                                       LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
+                                       
                                } catch (Exception e) {
                                        addPolicyToGroupTransaction.rollbackTransaction();
                                        String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
+                                       //for fixing Header Manipulation of Fortify issue
+                                       if(!message.matches(REGEX)){
+                                               response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                                               response.addHeader("error",ADD_GROUP_ERROR);
+                                               response.addHeader("message", "Policy Id is not valid");
+                                               return;
+                                       }
                                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
@@ -1414,21 +1666,100 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                response.addHeader("message", message);
                                                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                        } else {
-                                               response.sendError(500, message);
+                                               setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                                        }
                                        return;
                                }
+                               
+                               if(apiflag != null){
+                                       /*
+                                        * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
+                                        * The GUI does this from the POLICY-SDK-APP code.
+                                        */
+                                       
+                                       // Get new transaction to perform updateGroup()
+                                       PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
+                                       try {
+                                               // get the request content into a String and read the inputStream into a buffer
+                                               java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
+                                               scanner.useDelimiter("\\A");
+                                               String json =  scanner.hasNext() ? scanner.next() : "";
+                                               scanner.close();
+                                               
+                                               // convert Object sent as JSON into local object
+                                               ObjectMapper mapper = new ObjectMapper();
+                                               Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
+                                               StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
+                                               
+                                               LOGGER.info("Request JSON Payload: " + json);
+
+                                               // Assume that this is an update of an existing PDP Group
+                                               loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
+                                               try{
+                                                       acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
+                                               } catch(Exception e){
+                                                       PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
+                                                                       + e);
+                                                       throw new PAPException(e.getMessage()); 
+                                               }
+                                               
+                                               LOGGER.info("Calling updatGroup() with new group");
+                                               papEngine.updateGroup(updatedGroup);
+                                               
+                                               LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
+                                               
+                                               // Commit transaction to send notification to other PAPs
+                                               loggingContext.metricStarted();
+                                               acPutTransaction.commitTransaction();
+                                               loggingContext.metricEnded();
+                                               PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
+                                               loggingContext.metricStarted();
+                                               
+                                               notifyAC();
+                                               loggingContext.metricEnded();
+                                               PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
+                                               
+                                               // Group changed to send notification to PDPs, which might include changing the policies        
+                                               groupChanged(updatedGroup,loggingContext);
+                                               loggingContext.transactionEnded();
+                                               LOGGER.info("Success");
+
+                                               if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
+                                                       PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
+                                                       if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
+                                                               LOGGER.debug("Precheck Successful.");
+                                                       }
+                                               }
+                                               
+                                               //delete temporary policy file from the bin directory
+                                               Files.deleteIfExists(Paths.get(policy.getId()));
+                                                       
+                                       } catch (Exception e) {
+                                               acPutTransaction.rollbackTransaction();
+                                               PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
+                                               loggingContext.transactionEnded();
+                                               PolicyLogger.audit("Transaction Failed - See Error.log");
+                                               String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
+                                               LOGGER.error(message);
+                                               setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+                                               response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                                               response.addHeader("error",ADD_GROUP_ERROR);
+                                               response.addHeader("message", message);
+                                               return;
+                                       }
+                               }
+                               
                                // policy file copied ok and the Group was updated on the PDP
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                                response.addHeader("operation", "push");
                                response.addHeader("policyId", policyId);
                                response.addHeader("groupId", groupId);
-                               if (LOGGER.isDebugEnabled()) {
-                                       LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
-                               }
+                               
+                               LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
-                               PolicyLogger.audit("Transaction Ended Successfully");
+                               LOGGER.info("Transaction Ended Successfully");
+                               
                                return;
                        } else if (request.getParameter("default") != null) {
                                // Args:       group=<groupId> default=true               <= make default
@@ -1439,15 +1770,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
                                try {
                                        setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
-                                       papEngine.SetDefaultGroup(group);
+                                       papEngine.setDefaultGroup(group);
+                                       loggingContext.metricStarted();
                                        setDefaultGroupTransaction.commitTransaction();
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
                                } catch (Exception e) {
                                        setDefaultGroupTransaction.rollbackTransaction();
                                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
                                        loggingContext.transactionEnded();
-       
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(500, "Unable to set group '" + groupId + "' to default");
+                                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
                                        return;
                                }
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
@@ -1457,11 +1790,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                // Notify the Admin Consoles that something changed
                                // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
                                //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
+                               loggingContext.metricStarted();
                                notifyAC();
                                // This does not affect any PDPs in the existing groups, so no need to notify them of this change
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
-                               PolicyLogger.audit("Transaction Ended Successfully");
+                               LOGGER.info("Transaction Ended Successfully");
                                return;
                        } else if (request.getParameter("pdpId") != null) {
                                doACPostTransaction = policyDBDao.getNewTransaction();
@@ -1489,10 +1825,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                ((StdPDPGroup)group).resetStatus();
                                // Notify the Admin Consoles that something changed
                                // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
+                               loggingContext.metricStarted();
                                notifyAC();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
                                // Need to notify the PDP that it's config may have changed
-                               pdpChanged(pdp);
+                               pdpChanged(pdp, loggingContext);
+                               loggingContext.metricStarted();
                                doACPostTransaction.commitTransaction();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
                                PolicyLogger.audit("Transaction Ended Successfully");
@@ -1502,7 +1844,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        return;
                }
        }
@@ -1517,7 +1859,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         * @throws ServletException
         * @throws IOException
         */
-       private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
+       private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
                try {
                        String parameterDefault = request.getParameter("default");
                        String pdpId = request.getParameter("pdpId");
@@ -1529,14 +1871,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        loggingContext.setServiceName("AC:PAP.getDefaultGroup");
                                        OnapPDPGroup group = papEngine.getDefaultGroup();
                                        // convert response object to JSON and include in the response
-                                       ObjectMapper mapper = new ObjectMapper();
-                                       mapper.writeValue(response.getOutputStream(),  group);
+                                       mapperWriteValue(new ObjectMapper(), response,  group);
                                        if (LOGGER.isDebugEnabled()) {
                                                LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
                                        }
                                        response.setStatus(HttpServletResponse.SC_OK);
                                        response.setHeader("content-type", "application/json");
-                                       response.getOutputStream().close();
+                                       try{
+                        response.getOutputStream().close();
+                    } catch (IOException e){
+                        LOGGER.error(e);
+                    }
                                        loggingContext.transactionEnded();
                                        auditLogger.info("Success");
                                        PolicyLogger.audit("Transaction Ended Successfully");
@@ -1546,16 +1891,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        if (pdpGroup == null) {
                                                // Request is for the (unspecified) group containing a given PDP
                                                loggingContext.setServiceName("AC:PAP.getPDP");
-                                               OnapPDP pdp = papEngine.getPDP(pdpId);
+                                               OnapPDP pdp = null;
+                                               try{
+                                                   pdp = papEngine.getPDP(pdpId);
+                                               }catch(PAPException e){
+                                                   LOGGER.error(e);
+                                               }
                                                // convert response object to JSON and include in the response
-                                               ObjectMapper mapper = new ObjectMapper();
-                                               mapper.writeValue(response.getOutputStream(),  pdp);
+                                               mapperWriteValue(new ObjectMapper(), response,  pdp);
                                                if (LOGGER.isDebugEnabled()) {
                                                        LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
                                                }
                                                response.setStatus(HttpServletResponse.SC_OK);
                                                response.setHeader("content-type", "application/json");
-                                               response.getOutputStream().close();
+                                               try{
+                            response.getOutputStream().close();
+                        } catch (IOException e){
+                            LOGGER.error(e);
+                        }
                                                loggingContext.transactionEnded();
                                                auditLogger.info("Success");
                                                PolicyLogger.audit("Transaction Ended Successfully");
@@ -1563,17 +1916,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        } else {
                                                // Request is for the group containing a given PDP
                                                loggingContext.setServiceName("AC:PAP.getGroupForPDP");
-                                               OnapPDP pdp = papEngine.getPDP(pdpId);
-                                               OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
+                                               OnapPDPGroup group =null;
+                                               try{
+                                                   OnapPDP pdp = papEngine.getPDP(pdpId);
+                               group = papEngine.getPDPGroup((OnapPDP) pdp);
+                                               }catch(PAPException e){
+                                                   LOGGER.error(e);
+                                               }
                                                // convert response object to JSON and include in the response
-                                               ObjectMapper mapper = new ObjectMapper();
-                                               mapper.writeValue(response.getOutputStream(),  group);
+                                               mapperWriteValue(new ObjectMapper(), response,  group);
                                                if (LOGGER.isDebugEnabled()) {
                                                        LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
                                                }
                                                response.setStatus(HttpServletResponse.SC_OK);
                                                response.setHeader("content-type", "application/json");
-                                               response.getOutputStream().close();
+                                               try{
+                               response.getOutputStream().close();
+                           } catch (IOException e){
+                               LOGGER.error(e);
+                           }
                                                loggingContext.transactionEnded();
                                                auditLogger.info("Success");
                                                PolicyLogger.audit("Transaction Ended Successfully");
@@ -1584,14 +1945,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        loggingContext.setServiceName("AC:PAP.getAllGroups");
                                        Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
                                        // convert response object to JSON and include in the response
-                                       ObjectMapper mapper = new ObjectMapper();
-                                       mapper.writeValue(response.getOutputStream(),  groups);
+                                       mapperWriteValue(new ObjectMapper(), response,  groups);
                                        if (LOGGER.isDebugEnabled()) {
                                                LOGGER.debug("GET All groups req");
                                        }
                                        response.setStatus(HttpServletResponse.SC_OK);
                                        response.setHeader("content-type", "application/json");
-                                       response.getOutputStream().close();
+                                       try{
+                           response.getOutputStream().close();
+                       } catch (IOException e){
+                           LOGGER.error(e);
+                       }
                                        loggingContext.transactionEnded();
                                        auditLogger.info("Success");
                                        PolicyLogger.audit("Transaction Ended Successfully");
@@ -1599,14 +1963,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                }
                        }
                        // for all other GET operations the group must exist before the operation can be done
-                       OnapPDPGroup group = papEngine.getGroup(groupId);
+                       OnapPDPGroup group = null;
+                       try{
+                           group = papEngine.getGroup(groupId);
+                       } catch(PAPException e){
+                           LOGGER.error(e);
+                       }
                        if (group == null) {
                                String message = "Unknown groupId '" + groupId + "'";
+                               //for fixing Header Manipulation of Fortify issue
+                               if(!message.matches(REGEX)){
+                                       response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                                       response.addHeader("error",ADD_GROUP_ERROR);
+                                       response.addHeader("message", "Group Id is not valid");
+                                       return;
+                               }
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
                                loggingContext.transactionEnded();
-
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+                               setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
                                return;
                        }
                        // Figure out which request this is based on the parameters
@@ -1618,19 +1993,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
+                               setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
                        } else {
                                // No other parameters, so return the identified Group
                                loggingContext.setServiceName("AC:PAP.getGroup");
                                // convert response object to JSON and include in the response
-                               ObjectMapper mapper = new ObjectMapper();
-                               mapper.writeValue(response.getOutputStream(),  group);
+                               mapperWriteValue(new ObjectMapper(), response,  group);
                                if (LOGGER.isDebugEnabled()) {
                                        LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
                                }
                                response.setStatus(HttpServletResponse.SC_OK);
                                response.setHeader("content-type", "application/json");
-                               response.getOutputStream().close();
+                               try{
+                                   response.getOutputStream().close();
+                               } catch (IOException e){
+                                   LOGGER.error(e);
+                               }
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
                                PolicyLogger.audit("Transaction Ended Successfully");
@@ -1645,12 +2023,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+                       setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
                } catch (PAPException e) {
                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        return;
                }
        }
@@ -1665,7 +2043,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         * @throws ServletException
         * @throws IOException
         */
-       private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
+       private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
                PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
                try {
                        // for PUT operations the group may or may not need to exist before the operation can be done
@@ -1677,7 +2055,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
+                               setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
                                return;
                        }
                        if (request.getParameter("policy") != null) {
@@ -1701,10 +2079,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                // get the request content into a String
                                String json = null;
                                // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
-                               java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
-                               scanner.useDelimiter("\\A");
-                               json =  scanner.hasNext() ? scanner.next() : "";
-                               scanner.close();
+                               try{
+                                   Scanner scanner = new Scanner(request.getInputStream());
+                                   scanner.useDelimiter("\\A");
+                       json =  scanner.hasNext() ? scanner.next() : "";
+                       scanner.close();
+                               }catch(IOException e){
+                                   LOGGER.error(e);
+                               }
                                LOGGER.info("JSON request from AC: " + json);
                                // convert Object sent as JSON into local object
                                ObjectMapper mapper = new ObjectMapper();
@@ -1717,11 +2099,17 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
+                                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
                                }
                                StdPDP pdp = (StdPDP) objectFromJSON;
                                if(pdp != null){
-                                       if (papEngine.getPDP(pdpId) == null) {
+                                   OnapPDP oPDP = null;
+                                   try{
+                                       oPDP = papEngine.getPDP(pdpId);
+                                   }catch (PAPException e){
+                                       LOGGER.error(e);
+                                   }
+                                       if (oPDP == null) {
                                                // this is a request to create a new PDP object
                                                try{
                                                        acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), 
@@ -1731,7 +2119,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                                        +"pdp="+ (pdp.getId()) +",to group="+group.getId());
                                                        throw new PAPException(e.getMessage());
                                                }
-                                               papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
+                                               try{
+                                                   papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
+                                               }catch(PAPException e){
+                                                   LOGGER.error(e);
+                                               }
                                        } else {
                                                try{
                                                        acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
@@ -1741,7 +2133,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                                        throw new PAPException(e.getMessage());
                                                }
                                                // this is a request to update the pdp
-                                               papEngine.updatePDP(pdp);
+                                               try{
+                                                   papEngine.updatePDP(pdp);
+                                               }catch(PAPException e){
+                            LOGGER.error(e);
+                        }
                                        }
                                        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                                        if (LOGGER.isDebugEnabled()) {
@@ -1750,10 +2146,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        // adjust the group's state including the new PDP
                                        ((StdPDPGroup)group).resetStatus();
                                        // tell the Admin Consoles there is a change
+                                       loggingContext.metricStarted();
                                        notifyAC();
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
                                        // this might affect the PDP, so notify it of the change
-                                       pdpChanged(pdp);
+                                       pdpChanged(pdp, loggingContext);
+                                       loggingContext.metricStarted();
                                        acPutTransaction.commitTransaction();
+                                       loggingContext.metricEnded();
+                                       PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
                                        loggingContext.transactionEnded();
                                        auditLogger.info("Success");
                                        PolicyLogger.audit("Transaction Ended Successfully");
@@ -1773,7 +2175,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+                               setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
                                return;
                        } else {
                                // Assume that this is an update of an existing PDP Group
@@ -1782,10 +2184,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                // get the request content into a String
                                String json = null;
                                // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
-                               java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
-                               scanner.useDelimiter("\\A");
-                               json =  scanner.hasNext() ? scanner.next() : "";
-                               scanner.close();
+                try{
+                    Scanner scanner = new Scanner(request.getInputStream());
+                    scanner.useDelimiter("\\A");
+                    json =  scanner.hasNext() ? scanner.next() : "";
+                    scanner.close();
+                }catch(IOException e){
+                    LOGGER.error(e);
+                }
                                LOGGER.info("JSON request from AC: " + json);
                                // convert Object sent as JSON into local object
                                ObjectMapper mapper = new ObjectMapper();
@@ -1795,7 +2201,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
                                        loggingContext.transactionEnded();
                                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                                       response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON);
+                                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
                                }
                                // The Path on the PAP side is not carried on the RESTful interface with the AC
                                // (because it is local to the PAP)
@@ -1804,41 +2210,55 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
                                }
                                try{
-                                       acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
+                                       if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
+                                               acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
+                                       } else {
+                                               acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
+                                       }
                                } catch(Exception e){
                                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
                                                        +"group="+group.getId());
+                                       LOGGER.error(e);
                                        throw new PAPException(e.getMessage());
                                }
                                
                                PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();  
                                OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;        
-                               if (pushPolicyHandler.preSafetyCheck(updatedGroup, CONFIG_HOME)) {              
+                               if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {               
                                        LOGGER.debug("Precheck Successful.");
                                }
-                               
-                papEngine.updateGroup((StdPDPGroup)objectFromJSON);
-
+                               try{
+                                   papEngine.updateGroup((StdPDPGroup)objectFromJSON);
+                               }catch(PAPException e){
+                                   LOGGER.error(e);
+                               }
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                                if (LOGGER.isDebugEnabled()) {
                                        LOGGER.debug("Group '" + group.getId() + "' updated");
                                }
+                               loggingContext.metricStarted();
                                acPutTransaction.commitTransaction();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
                                // tell the Admin Consoles there is a change
+                               loggingContext.metricStarted();
                                notifyAC();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
                                // Group changed, which might include changing the policies
-                               groupChanged(group);
+                               groupChanged(group, loggingContext);
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
                                PolicyLogger.audit("Transaction Ended Successfully");
                                return;
                        }
                } catch (PAPException e) {
+                       LOGGER.debug(e);
                        acPutTransaction.rollbackTransaction();
                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        return;
                }
        }
@@ -1853,7 +2273,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
         * @throws ServletException
         * @throws IOException
         */
-       private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
+       private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
                //This code is to allow deletes to propagate to the database since delete is not implemented
                String isDeleteNotify = request.getParameter("isDeleteNotify");
                if(isDeleteNotify != null){
@@ -1861,8 +2281,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        try{
                                policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
                        } catch(UnsupportedEncodingException e){
-                               PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8");
-                               response.sendError(500,"policyToDelete encoding not supported");
+                               LOGGER.error("Unsupported URL encoding of policyToDelete (UTF-8", e);
+                               setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToDelete encoding not supported");
                                return;
                        }
                        PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
@@ -1870,11 +2290,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                deleteTransaction.deletePolicy(policyToDelete);
                        } catch(Exception e){
                                deleteTransaction.rollbackTransaction();
-                               response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) "
+                               setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"deleteTransaction.deleteTransaction(policyToDelete) "
                                                + "\nfailure with the following exception: " + e);
                                return;
                        }
+                       loggingContext.metricStarted();
                        deleteTransaction.commitTransaction();
+                       loggingContext.metricEnded();
+                       PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
                        response.setStatus(HttpServletResponse.SC_OK);
                        return;
                }
@@ -1888,7 +2311,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
+                               setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
                                return;
                        }
                        // determine the operation needed based on the parameters in the request
@@ -1898,7 +2321,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+                               setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
                                return;
                        } else if (request.getParameter("pdpId") != null) {
                                // ARGS:        group=<groupId> pdpId=<pdpId>                  <= delete PDP 
@@ -1907,16 +2330,26 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                try{
                                        removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
                                } catch(Exception e){
-                                       throw new PAPException();
+                                       throw new PAPException(e);
                                }
-                               papEngine.removePDP((OnapPDP) pdp);
+                               try{
+                       papEngine.removePDP((OnapPDP) pdp);
+                               }catch(PAPException e){
+                    LOGGER.error(e);
+                }
                                // adjust the status of the group, which may have changed when we removed this PDP
                                ((StdPDPGroup)group).resetStatus();
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+                               loggingContext.metricStarted();
                                notifyAC();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
                                // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
-                               pdpChanged(pdp);
+                               pdpChanged(pdp, loggingContext);
+                               loggingContext.metricStarted();
                                removePdpOrGroupTransaction.commitTransaction();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
                                PolicyLogger.audit("Transaction Ended Successfully");
@@ -1927,14 +2360,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed - See Error.log");
-                               response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+                               setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
                                return;
                        } else {
                                // ARGS:      group=<groupId> movePDPsToGroupId=<movePDPsToGroupId>            <= delete a group and move all its PDPs to the given group
                                String moveToGroupId = request.getParameter("movePDPsToGroupId");
                                OnapPDPGroup moveToGroup = null;
                                if (moveToGroupId != null) {
-                                       moveToGroup = papEngine.getGroup(moveToGroupId);
+                                   try{
+                                       moveToGroup = papEngine.getGroup(moveToGroupId);
+                                   }catch(PAPException e){
+                           LOGGER.error(e);
+                       }
                                }
                                // get list of PDPs in the group being deleted so we can notify them that they got changed
                                Set<OnapPDP> movedPDPs = new HashSet<>();
@@ -1946,14 +2383,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
                                        throw new PAPException(e.getMessage());
                                }
-                               papEngine.removeGroup(group, moveToGroup);
+                               try{
+                                   papEngine.removeGroup(group, moveToGroup);
+                               }catch(PAPException e){
+                    LOGGER.error(e);
+                }
                                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+                               loggingContext.metricStarted();
                                notifyAC();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
                                // notify any PDPs in the removed set that their config may have changed
                                for (OnapPDP pdp : movedPDPs) {
-                                       pdpChanged(pdp);
+                                       pdpChanged(pdp, loggingContext);
                                }
+                               loggingContext.metricStarted();
                                removePdpOrGroupTransaction.commitTransaction();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
                                loggingContext.transactionEnded();
                                auditLogger.info("Success");
                                PolicyLogger.audit("Transaction Ended Successfully");
@@ -1964,7 +2411,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(500, e.getMessage());
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                        return;
                }
        }
@@ -2138,6 +2585,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        } catch (InterruptedException e) {
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted.  Shutting down");
                                this.terminate();
+                               Thread.currentThread().interrupt();
                        }
                }
        }
@@ -2176,13 +2624,27 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        groups = papEngine.getOnapPDPGroups();
                } catch (PAPException e) {
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
-                       throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
+                       throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
                }
                for (OnapPDPGroup group : groups) {
                        groupChanged(group);
                }
        }
-
+       
+       public void changed(ONAPLoggingContext loggingContext) {
+               // all PDPs in all groups need to be updated/sync'd
+               Set<OnapPDPGroup> groups;
+               try {
+                       groups = papEngine.getOnapPDPGroups();
+               } catch (PAPException e) {
+                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
+                       throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
+               }
+               for (OnapPDPGroup group : groups) {
+                       groupChanged(group, loggingContext);
+               }
+       }
+       
        @Override
        public void groupChanged(OnapPDPGroup group) {
                // all PDPs within one group need to be updated/sync'd
@@ -2191,12 +2653,29 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                }
        }
 
+       public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
+               // all PDPs within one group need to be updated/sync'd
+               for (OnapPDP pdp : group.getOnapPdps()) {
+                       pdpChanged(pdp, loggingContext);
+               }
+       }
+
        @Override
-       public void pdpChanged(OnapPDP pdp) {
+        public void pdpChanged(OnapPDP pdp) {
+               // kick off a thread to do an event notification for each PDP.
+               // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
+               // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
+               Thread t = new Thread(new UpdatePDPThread(pdp));
+               if(CheckPDP.validateID(pdp.getId())){
+                       t.start();
+               }
+       }
+       
+        public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
                // kick off a thread to do an event notification for each PDP.
                // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
                // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
-               Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId));
+               Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
                if(CheckPDP.validateID(pdp.getId())){
                        t.start();
                }
@@ -2205,17 +2684,34 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
        private class UpdatePDPThread implements Runnable {
                private OnapPDP pdp;
                private String requestId;
+               private ONAPLoggingContext loggingContext;
+
+               public UpdatePDPThread(OnapPDP pdp) {
+                       this.pdp = pdp;
+               }
 
-               public UpdatePDPThread(OnapPDP pdp, String storedRequestId) {
+               public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
                        this.pdp = pdp;
-                       requestId = storedRequestId;
+                       if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
+                                       this.requestId = loggingContext.getRequestID();
+                       }
+                       this.loggingContext = loggingContext;
                }
 
                public void run() {
                        // send the current configuration to one PDP
                        HttpURLConnection connection = null;
                        // get a new logging context for the thread
-                       ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
+                       try {
+                               if (this.loggingContext == null) {
+                                    loggingContext = new ONAPLoggingContext(baseLoggingContext);
+                               } 
+                       } catch (Exception e) {
+                           PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
+                           // Since this is a server-side error, it probably does not reflect a problem on the client,
+                           // so do not change the PDP status.
+                           return;
+               }
                        try {
                                loggingContext.setServiceName("PAP:PDP.putConfig");
                                // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
@@ -2246,7 +2742,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                }
                                connection.setRequestProperty("Content-Type", "text/x-java-properties");
                                connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
-                               storedRequestId = null;
                                connection.setInstanceFollowRedirects(true);
                                connection.setDoOutput(true);
                                try (OutputStream os = connection.getOutputStream()) {
@@ -2278,7 +2773,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        return;
                                }
                                // Do the connect
+                               loggingContext.metricStarted();
                                connection.connect();
+                               loggingContext.metricEnded();
+                               PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
                                if (connection.getResponseCode() == 204) {
                                        LOGGER.info("Success. We are configured correctly.");
                                        loggingContext.transactionEnded();
@@ -2299,12 +2797,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                        setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
                                }
                        } catch (Exception e) {
+                               LOGGER.debug(e);
                                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
                                loggingContext.transactionEnded();
                                PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
                                try {
                                        setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
                                } catch (PAPException e1) {
+                                       LOGGER.debug(e1);
                                        PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
                                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
                                }
@@ -2398,35 +2898,23 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        PolicyLogger.audit("Transaction Failed - See Error.log");
                        response.setStatus(HttpServletResponse.SC_OK);
                        return;
-               }catch (ForwardProgressException fpe){
-                       //No forward progress is being made
-                       String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
-                                       + " Exception Message: " + fpe.getMessage();
-                       LOGGER.info(message);
-                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
-                       loggingContext.transactionEnded();
-                       PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                       return;
-               }catch (AdministrativeStateException ase){
-                       //Administrative State is locked
-                       String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED "
-                                       + " Exception Message: " + ase.getMessage();
-                       LOGGER.info(message);
-                       PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
-                       loggingContext.transactionEnded();
-                       PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                       return;
-               }catch (StandbyStatusException sse){
-                       //Administrative State is locked
-                       String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE "
-                                       + " Exception Message: " + sse.getMessage();
-                       LOGGER.info(message);
+               }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
+                       String submsg;
+                       if (e instanceof ForwardProgressException) {
+                               submsg = " is not making forward progress.";
+                       } else if (e instanceof AdministrativeStateException) {
+                               submsg = " Administrative State is LOCKED.";
+                       } else {
+                               submsg = " Standby Status is NOT PROVIDING SERVICE.";
+                       }
+
+                       String message = "GET:/pap/test called and PAP " + papResourceName + submsg
+                                       + " Exception Message: " + e.getMessage();
+                       LOGGER.info(message, e);
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }catch (Exception e) {
                        //A subsystem is not making progress, is locked, standby or is not responding
@@ -2436,7 +2924,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                        }
                        String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
                                        + " Exception Message: " + eMsg;
-                       LOGGER.info(message);
+                       LOGGER.info(message, e);
                        PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
                        loggingContext.transactionEnded();
                        PolicyLogger.audit("Transaction Failed - See Error.log");
@@ -2455,7 +2943,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                ssFailureList = "UnknownSubSystem";
                        }
                        response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
-                       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                       setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                        return;
                }
        }
@@ -2474,7 +2962,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
        }
 
        private static void loadWebapps() throws PAPException{
-               if(ACTION_HOME == null || CONFIG_HOME == null){
+               if(actionHome == null || configHome == null){
                        Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
                        //Sanity Check
                        if (webappsPath == null) {
@@ -2487,7 +2975,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                try {
                                        Files.createDirectories(webappsPathConfig);
                                } catch (IOException e) {
-                                       PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: "
+                                       PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
                                                        + webappsPathConfig.toAbsolutePath().toString());
                                }
                        }
@@ -2495,12 +2983,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                                try {
                                        Files.createDirectories(webappsPathAction);
                                } catch (IOException e) {
-                                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
+                                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
                                                        + webappsPathAction.toAbsolutePath().toString(), e);
                                }
                        }
-                       ACTION_HOME = webappsPathAction.toString();
-                       CONFIG_HOME = webappsPathConfig.toString();
+                       actionHome = webappsPathAction.toString();
+                       configHome = webappsPathConfig.toString();
                }
        }
 
@@ -2508,18 +2996,28 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
                try {
                        loadWebapps();
                } catch (PAPException e) {
+                       LOGGER.debug(e);
                        return null;
                }
-               return CONFIG_HOME;
+               return configHome;
+       }
+       
+       private static void setConfigHome(){
+           configHome = getConfigHome();
        }
 
        public static String getActionHome(){
                try {
                        loadWebapps();
                } catch (PAPException e) {
+                       LOGGER.debug(e);
                        return null;
                }
-               return ACTION_HOME;
+               return actionHome;
+       }
+       
+       private static void setActionHome(){
+           actionHome = getActionHome();
        }
 
        public static EntityManagerFactory getEmf() {