Merge "Fix final 10 vulnerabilities in policy/engine"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / XACMLPapServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.UnsupportedEncodingException;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.InetAddress;
32 import java.net.MalformedURLException;
33 import java.net.SocketTimeoutException;
34 import java.net.URL;
35 import java.net.URLDecoder;
36 import java.net.UnknownHostException;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.Properties;
45 import java.util.Scanner;
46 import java.util.Set;
47 import java.util.UUID;
48 import java.util.concurrent.CopyOnWriteArrayList;
49 import javax.json.JsonException;
50 import javax.persistence.EntityManagerFactory;
51 import javax.persistence.Persistence;
52 import javax.persistence.PersistenceException;
53 import javax.servlet.Servlet;
54 import javax.servlet.ServletConfig;
55 import javax.servlet.ServletException;
56 import javax.servlet.annotation.WebInitParam;
57 import javax.servlet.annotation.WebServlet;
58 import javax.servlet.http.HttpServlet;
59 import javax.servlet.http.HttpServletRequest;
60 import javax.servlet.http.HttpServletResponse;
61
62 import org.apache.commons.io.IOUtils;
63 import org.onap.policy.common.ia.IntegrityAudit;
64 import org.onap.policy.common.im.AdministrativeStateException;
65 import org.onap.policy.common.im.ForwardProgressException;
66 import org.onap.policy.common.im.IntegrityMonitor;
67 import org.onap.policy.common.im.IntegrityMonitorException;
68 import org.onap.policy.common.im.IntegrityMonitorProperties;
69 import org.onap.policy.common.im.StandbyStatusException;
70 import org.onap.policy.common.logging.ONAPLoggingContext;
71 import org.onap.policy.common.logging.ONAPLoggingUtils;
72 import org.onap.policy.common.logging.eelf.MessageCodes;
73 import org.onap.policy.common.logging.eelf.PolicyLogger;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
77 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
78 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
79 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
80 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
81 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
82 import org.onap.policy.rest.XACMLRest;
83 import org.onap.policy.rest.XACMLRestProperties;
84 import org.onap.policy.rest.dao.PolicyDBException;
85 import org.onap.policy.utils.CryptoUtils;
86 import org.onap.policy.utils.PolicyUtils;
87 import org.onap.policy.xacml.api.XACMLErrorConstants;
88 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
89 import org.onap.policy.xacml.api.pap.OnapPDP;
90 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
91 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
92 import org.onap.policy.xacml.std.pap.StdPDP;
93 import org.onap.policy.xacml.std.pap.StdPDPGroup;
94 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
95 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
96 import org.onap.policy.xacml.std.pap.StdPDPStatus;
97
98 import com.att.research.xacml.api.pap.PAPException;
99 import com.att.research.xacml.api.pap.PDPPolicy;
100 import com.att.research.xacml.api.pap.PDPStatus;
101 import com.att.research.xacml.util.FactoryException;
102 import com.att.research.xacml.util.XACMLProperties;
103 import com.fasterxml.jackson.databind.ObjectMapper;
104 import com.google.common.base.Splitter;
105
106 /**
107  * Servlet implementation class XacmlPapServlet
108  */
109 @WebServlet(
110                 description = "Implements the XACML PAP RESTful API.", 
111                 urlPatterns = { "/" }, 
112                 loadOnStartup=1,
113                 initParams = {
114                         @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
115                 })
116 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
117         private static final long serialVersionUID = 1L;
118         private static final Logger LOGGER      = FlexLogger.getLogger(XACMLPapServlet.class);
119         // audit (transaction) LOGGER
120         private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
121         //Persistence Unit for JPA 
122         private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
123         private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
124         // Client Headers. 
125         private static final String ENVIRONMENT_HEADER = "Environment";
126         private static final String ADD_GROUP_ERROR = "addGroupError";
127         private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
128         
129         private static final String REGEX = "[0-9a-zA-Z._ ]*";
130         
131         /*
132          * List of Admin Console URLs.
133          * Used to send notifications when configuration changes.
134          * 
135          * The CopyOnWriteArrayList *should* protect from concurrency errors.
136          * This list is seldom changed but often read, so the costs of this approach make sense.
137          */
138         private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();     
139         
140         private static String configHome;
141         private static String actionHome;
142         /*
143          * This PAP instance's own URL.
144          * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. 
145          */
146         private static String papURL = null;
147         // The heartbeat thread.
148         private static Heartbeat heartbeat = null;
149         private static Thread heartbeatThread = null;
150         //The entity manager factory for JPA access
151         private static EntityManagerFactory emf;
152         private static PolicyDBDao policyDBDao;
153         /*
154          * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
155          */
156         private static PAPPolicyEngine papEngine = null;
157         /*
158          * These are the parameters needed for DB access from the PAP
159          */
160         private static int papIntegrityAuditPeriodSeconds = -1;
161         private static String papDbDriver = null;
162         private static String papDbUrl = null;
163         private static String papDbUser = null;
164         private static String papDbPassword = null;
165         private static String papResourceName = null;
166         private static String[] papDependencyGroupsFlatArray = null;
167         private static String environment = null;
168         private static String pdpFile = null;
169         
170         private transient IntegrityMonitor im;
171         private transient IntegrityAudit ia;
172         
173         //MicroService Model Properties
174         private static String msOnapName;
175         private static String msPolicyName;
176         /*
177          * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
178          * this servlet starts. Its configurable by the admin.
179          */
180         private static transient Thread initiateThread = null;
181         private transient ONAPLoggingContext baseLoggingContext = null;
182         
183         /**
184          * @see HttpServlet#HttpServlet()
185          */
186         public XACMLPapServlet() {
187                 super();
188         }
189
190         /**
191          * @see Servlet#init(ServletConfig)
192          */
193         public void init(ServletConfig config) throws ServletException {
194                 try {
195                         // Logging
196                         baseLoggingContext = new ONAPLoggingContext();
197                         // fixed data that will be the same in all logging output goes here
198                         try {
199                                 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
200                                 baseLoggingContext.setServer(hostname);
201                         } catch (UnknownHostException e) {
202                                 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
203                         }
204                         // Initialize
205                         XACMLRest.xacmlInit(config);
206                         // Load the properties
207                         XACMLRest.loadXacmlProperties(null, null);
208                         /*
209                          * Retrieve the property values
210                          */
211                         setCommonProperties();
212                         String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
213                         if(papSiteName == null){
214                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
215                                 throw new PAPException("papSiteName is null");
216                         }
217                         String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
218                         if(papNodeType == null){
219                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
220                                 throw new PAPException("papNodeType is null");
221                         }
222                         //Integer will throw an exception of anything is missing or unrecognized
223                         int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
224                         int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
225                         int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
226                         //Boolean will default to false if anything is missing or unrecognized
227                         boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
228                         boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
229                         String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
230                         if(papDependencyGroups == null){
231                                 throw new PAPException("papDependencyGroups is null");
232                         }
233                         setPAPDependencyGroups(papDependencyGroups);
234                         //Integer will throw an exception of anything is missing or unrecognized
235                         int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
236                         int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
237                         int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
238                         int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
239                         LOGGER.debug("\n\n\n**************************************"
240                                         + "\n*************************************"
241                                         + "\n"
242                                         + "\n   papDbDriver = " + papDbDriver
243                                         + "\n   papDbUrl = " + papDbUrl
244                                         + "\n   papDbUser = " + papDbUser
245                                         + "\n   papTransWait = " + papTransWait
246                                         + "\n   papTransTimeout = " + papTransTimeout
247                                         + "\n   papAuditTimeout = " + papAuditTimeout
248                                         + "\n   papAuditFlag = " + papAuditFlag
249                                         + "\n   papFileSystemAudit = " + papFileSystemAudit
250                                         + "\n   papResourceName = " + papResourceName
251                                         + "\n   fpMonitorInterval = " + fpMonitorInterval
252                                         + "\n   failedCounterThreshold = " + failedCounterThreshold
253                                         + "\n   testTransInterval = " + testTransInterval
254                                         + "\n   writeFpcInterval = " + writeFpcInterval
255                                         + "\n   papSiteName = " + papSiteName
256                                         + "\n   papNodeType = " + papNodeType
257                                         + "\n   papDependencyGroupsList = " + papDependencyGroups
258                                         + "\n   papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
259                                         + "\n\n*************************************"
260                                         + "\n**************************************");
261                         // Pull custom persistence settings
262                         Properties properties;
263                         try {
264                                 properties = XACMLProperties.getProperties();
265                                 LOGGER.debug("\n\n\n**************************************"
266                                                 + "\n**************************************"
267                                                 + "\n\n"
268                                                 + "properties = " + properties
269                                                 + "\n\n**************************************");
270                         } catch (IOException e) {
271                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
272                                                 + "XACMLProperties.getProperties()");
273                                 throw new ServletException(e.getMessage(), e.getCause());
274                         }
275                         // Create an IntegrityMonitor
276                         if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
277                                 properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
278                         }
279                         im = IntegrityMonitor.getInstance(papResourceName,properties);
280                         // Create an IntegrityAudit
281                         ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
282                         ia.startAuditThread();
283                         // Create the entity manager factory
284                         setEMF(properties);
285                         // we are about to call the PDPs and give them their configuration.
286                         // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
287                         setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
288                         //Create the policyDBDao
289                         setPolicyDBDao();
290                         // Load our PAP engine, first create a factory
291                         ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
292                         // The factory knows how to go about creating a PAP Engine
293                         setPAPEngine((PAPPolicyEngine) factory.newEngine());
294                         PolicyDBDaoTransaction addNewGroup = null;
295             if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
296                 try {
297                     addNewGroup = policyDBDao.getNewTransaction();
298                     OnapPDPGroup group = papEngine.getDefaultGroup();
299                     addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
300                             "automaticallyAdded");
301                     addNewGroup.commitTransaction();
302                     addNewGroup = policyDBDao.getNewTransaction();
303                     addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
304                     addNewGroup.commitTransaction();
305                 } catch (Exception e) {
306                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
307                             " Error creating new default group in the database");
308                     if (addNewGroup != null) {
309                         addNewGroup.rollbackTransaction();
310                     }
311                 }
312             }
313                         policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
314                 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
315                         /*
316                          * Auditing the local File System groups to be in sync with the Database
317                          */
318                         
319                         //get an AuditTransaction to lock out all other transactions
320                         PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
321                         
322                         LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
323                 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
324                         //get the current filesystem group and update from the database if needed
325                 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
326                 StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
327                 if(updatedGroup!=null) {
328                         papEngine.updateGroup(updatedGroup);
329                 }    
330                 LOGGER.info("PapServlet:  updated group is " + papEngine.getDefaultGroup().toString());
331                 
332                         //release the transaction lock
333                         auditTrans.close();
334                 }
335                 
336                         // Sanity check for URL.
337                         if (XACMLPapServlet.papURL == null) {
338                                 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
339                         }
340                         // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
341                         // to all its known PDP nodes.
342                         if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
343                             startInitiateThreadService(new Thread(this));
344                         }
345                         // After startup, the PAP does Heartbeat's to each of the PDPs periodically
346                         startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
347
348                 } catch (FactoryException | PAPException e) {
349                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
350                         throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
351                 } catch (Exception e) {
352                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
353                         throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
354                 }
355         }
356
357         private static void startInitiateThreadService(Thread thread) {
358             initiateThread = thread;
359         initiateThread.start();
360     }
361
362     private static void mapperWriteValue(ObjectMapper mapper,  HttpServletResponse response, Object value) {
363         try {
364             mapper.writeValue(response.getOutputStream(), value);
365         } catch (Exception e) {
366             LOGGER.error(e);
367         }
368     }
369
370     private static void startHeartBeatService(Heartbeat heartbeat) {
371             XACMLPapServlet.heartbeat = heartbeat;
372         XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
373         XACMLPapServlet.heartbeatThread.start();
374     }
375
376     private static void setPolicyDBDao() throws ServletException {
377             try {
378             policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
379         } catch (Exception e) {
380             throw new ServletException("Unable to Create Policy DBDao Instance",e);
381         }
382     }
383
384     private static void setEMF(Properties properties) throws ServletException {
385             emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
386         if (emf == null) {
387             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
388                     + PERSISTENCE_UNIT);
389             throw new ServletException("Unable to create Entity Manager Factory");
390         }
391     }
392
393     private static void setPAPURL(String papURL) {
394             XACMLPapServlet.papURL = papURL;
395     }
396
397     private static void setPAPEngine(PAPPolicyEngine newEngine) {
398             XACMLPapServlet.papEngine = newEngine;
399     }
400
401     private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
402             try{
403             //Now we have flattened the array into a simple comma-separated list
404             papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
405             //clean up the entries
406             for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
407                 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
408             }
409             try{
410                 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
411                     papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
412                 }
413             }catch(Exception e){
414                 String msg = "integrity_audit_period_seconds ";
415                 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
416                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
417                 throw e;
418             }
419         }catch(Exception e){
420             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
421             throw new PAPException(e);
422         }
423     }
424
425     private static void setCommonProperties() throws PAPException {
426             setConfigHome();
427         setActionHome();
428         papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
429         if(papDbDriver == null){
430             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
431             throw new PAPException("papDbDriver is null");
432         }
433         setPapDbDriver(papDbDriver);
434         papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
435         if(papDbUrl == null){
436             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
437             throw new PAPException("papDbUrl is null");
438         }
439         setPapDbUrl(papDbUrl);
440         papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
441         if(papDbUser == null){
442             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
443             throw new PAPException("papDbUser is null");
444         }
445         setPapDbUser(papDbUser);
446         papDbPassword = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""));
447         if(papDbPassword == null){
448             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
449             throw new PAPException("papDbPassword is null");
450         }
451         setPapDbPassword(papDbPassword);
452         papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
453         if(papResourceName == null){
454             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
455             throw new PAPException("papResourceName is null");
456         }
457         environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
458         //Micro Service Properties
459         msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
460         setMsOnapName(msOnapName);
461         msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
462         setMsPolicyName(msPolicyName);
463         // PDPId File location 
464         XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
465         if (XACMLPapServlet.pdpFile == null) {
466             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
467                 + XACMLRestProperties.PROP_PDP_IDFILE);
468             throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
469         }
470     }
471
472     /**
473          * Thread used only during PAP startup to initiate change messages to all known PDPs.
474          * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
475          */
476         @Override
477         public void run() {
478                 // send the current configuration to all the PDPs that we know about
479                 changed();
480         }
481
482         /**
483          * @see Servlet#destroy()
484          * 
485          * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
486          * For now we assume that we do care.
487          */
488         @Override
489         public void destroy() {
490                 // Make sure our threads are destroyed
491                 if (XACMLPapServlet.heartbeatThread != null) {
492                         // stop the heartbeat
493                         try {
494                                 if (XACMLPapServlet.heartbeat != null) {
495                                         XACMLPapServlet.heartbeat.terminate();
496                                 }
497                                 XACMLPapServlet.heartbeatThread.interrupt();
498                                 XACMLPapServlet.heartbeatThread.join();
499                         } catch (InterruptedException e) {
500                             XACMLPapServlet.heartbeatThread.interrupt();
501                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
502                         }
503                 }
504                 if (initiateThread != null) {
505                         try {
506                                 initiateThread.interrupt();
507                                 initiateThread.join();
508                         } catch (InterruptedException e) {
509                             initiateThread.interrupt();
510                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
511                         }
512                 }
513         }
514
515         /**
516          * Called by:
517          *      - PDP nodes to register themselves with the PAP, and
518          *      - Admin Console to make changes in the PDP Groups.
519          * 
520          * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
521          */
522         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
523                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
524                 loggingContext.transactionStarted();
525                 loggingContext.setServiceName("PAP.post");
526                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
527                         UUID requestID = UUID.randomUUID();
528                         loggingContext.setRequestID(requestID.toString());
529                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
530                 } else {
531                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
532                 }
533                 PolicyDBDaoTransaction pdpTransaction = null;
534                 loggingContext.metricStarted();
535                 try {
536                         im.startTransaction();
537                         loggingContext.metricEnded();
538                         PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
539                 } catch (AdministrativeStateException ae){
540                         String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
541                                         + " state of " + im.getStateManager().getAdminState()
542                                         + "\n Exception Message: " +  PolicyUtils.CATCH_EXCEPTION;
543                         LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
544                         loggingContext.metricEnded();
545                         PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
546                         loggingContext.transactionEnded();                      
547                         PolicyLogger.audit("Transaction Failed - See Error.log");
548                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
549                         return;
550                 }catch (StandbyStatusException se) {
551                         String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
552                                         + " of " + im.getStateManager().getStandbyStatus()
553                                         + "\n Exception Message: " + se.getMessage();
554                         LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
555                         loggingContext.metricEnded();
556                         PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
557                         loggingContext.transactionEnded();
558                         PolicyLogger.audit("Transaction Failed - See Error.log");
559                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
560                         return;
561                 } catch (IntegrityMonitorException e) {
562                         String message = "POST interface called for PAP " + papResourceName + " but an exception occurred"
563                                         + "\n Exception Message: " + e.getMessage();
564                         LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e);
565                         loggingContext.metricEnded();
566                         PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
567                         loggingContext.transactionEnded();
568                         PolicyLogger.audit("Transaction Failed - See Error.log");
569                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
570                         return;
571                 }
572                 try {
573                         loggingContext.metricStarted();
574                         XACMLRest.dumpRequest(request);
575                         loggingContext.metricEnded();
576                         PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
577                         // since getParameter reads the content string, explicitly get the content before doing that.
578                         // Simply getting the inputStream seems to protect it against being consumed by getParameter.
579                         request.getInputStream();
580                         String groupId = request.getParameter("groupId");
581                         String apiflag = request.getParameter("apiflag");
582                         if(groupId != null) {
583                                 // Is this from the Admin Console or API?
584                                 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
585                                         // this is from the API so we need to check the client credentials before processing the request
586                                         if(!authorizeRequest(request)){
587                                                 String message = "PEP not Authorized for making this Request!!";
588                                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
589                                                 loggingContext.transactionEnded();
590                                                 PolicyLogger.audit("Transaction Failed - See Error.log");
591                                                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
592                                                 im.endTransaction();
593                                                 return;
594                                         }
595                                 }
596                                 loggingContext.metricStarted();
597                                 doACPost(request, response, groupId, loggingContext);
598                                 loggingContext.metricEnded();
599                                 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
600                                 loggingContext.transactionEnded();
601                                 PolicyLogger.audit("Transaction Ended Successfully");
602                                 im.endTransaction();
603                                 return;
604                         }
605                         // Request is from a PDP asking for its config.
606                         loggingContext.setServiceName("PDP:PAP.register");
607                         // Get the PDP's ID
608                         String id = this.getPDPID(request);
609                         String jmxport = this.getPDPJMX(request);
610                         LOGGER.info("Request(doPost) from PDP coming up: " + id);
611                         // Get the PDP Object
612                         OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
613                         // Is it known?
614                         if (pdp == null) {
615                                 LOGGER.info("Unknown PDP: " + id);
616                                 // Check PDP ID
617                                 if(CheckPDP.validateID(id)){
618                                         pdpTransaction = policyDBDao.getNewTransaction();
619                                         try {
620                                                 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
621                                                 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
622                                         } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
623                                                 pdpTransaction.rollbackTransaction();
624                                                 String message = "Failed to create new PDP for id: " + id;
625                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
626                                                 loggingContext.transactionEnded();
627                                                 PolicyLogger.audit("Transaction Failed - See Error.log");
628                                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
629                                                 im.endTransaction();
630                                                 return;
631                                         }
632                                         // get the PDP we just created
633                             try{
634                                 pdp = XACMLPapServlet.papEngine.getPDP(id);
635                             }catch(PAPException e){
636                                 LOGGER.error(e);
637                             }
638                                         if (pdp == null) {
639                                                 if(pdpTransaction != null){
640                                                         pdpTransaction.rollbackTransaction();
641                                                 }
642                                                 String message = "Failed to create new PDP for id: " + id;
643                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
644                                                 loggingContext.transactionEnded();
645                                                 PolicyLogger.audit("Transaction Failed - See Error.log");
646                                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
647                                                 im.endTransaction();
648                                                 return;
649                                         }
650                                 } else {
651                                         String message = "PDP is Unauthorized to Connect to PAP: "+ id;
652                                         loggingContext.transactionEnded();
653                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
654                                         setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
655                                         PolicyLogger.audit("Transaction Failed - See Error.log");
656                                         im.endTransaction();
657                                         return;
658                                 }
659                                 try{
660                                         loggingContext.metricStarted();
661                                         pdpTransaction.commitTransaction();
662                                         loggingContext.metricEnded();
663                                         PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
664                                 } catch(Exception e){
665                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
666                                 }
667                         }
668                         if (jmxport != null && jmxport != ""){
669                             try{
670                         ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
671                             }catch(NumberFormatException e){
672                                 LOGGER.error(e);
673                             }
674                         }
675                         // Get the PDP's Group
676                         OnapPDPGroup group =null;
677                         try{
678                     group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
679                         }catch(PAPException e){
680                             LOGGER.error(e);
681                         }
682                         if (group == null) {
683                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
684                                 loggingContext.transactionEnded();
685                                 PolicyLogger.audit("Transaction Failed - See Error.log");
686                                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
687                                 im.endTransaction();
688                                 return;
689                         }
690                         // Determine what group the PDP node is in and get
691                         // its policy/pip properties.
692                         Properties policies = group.getPolicyProperties();
693                         Properties pipconfig = group.getPipConfigProperties();
694                         // Get the current policy/pip configuration that the PDP has
695                         Properties pdpProperties = new Properties();
696                         try{
697                     pdpProperties.load(request.getInputStream());
698                         }catch(IOException e){
699                             LOGGER.error(e);
700                         }
701                         LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
702                         LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
703                         LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
704                         // Validate the node's properties
705                         boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
706                         // Send back current configuration
707                         if (isCurrent == false) {
708                                 // Tell the PDP we are sending back the current policies/pip config
709                                 LOGGER.info("PDP configuration NOT current.");
710                                 if (policies != null) {
711                                         // Put URL's into the properties in case the PDP needs to
712                                         // retrieve them.
713                                         this.populatePolicyURL(request.getRequestURL(), policies);
714                                         // Copy the properties to the output stream
715                                         try{
716                                             policies.store(response.getOutputStream(), "");
717                                         }catch(IOException e){
718                                 LOGGER.error(e);
719                             }
720                                 }
721                                 if (pipconfig != null) {
722                                         // Copy the properties to the output stream
723                                         try{
724                                             pipconfig.store(response.getOutputStream(), "");
725                                         }catch(IOException e){
726                                 LOGGER.error(e);
727                             }
728                                 }
729                                 // We are good - and we are sending them information
730                                 response.setStatus(HttpServletResponse.SC_OK);
731                                 try{
732                                     setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
733                                 }catch(PAPException e){
734                         LOGGER.error(e);
735                     }
736                         } else {
737                                 // Tell them they are good
738                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
739                                 try{
740                                     setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
741                                 }catch(PAPException e){
742                         LOGGER.error(e);
743                     }
744                         }
745                         // tell the AC that something changed
746                         loggingContext.metricStarted();
747                         notifyAC();
748                         loggingContext.metricEnded();
749                         PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
750                         loggingContext.transactionEnded();
751                         auditLogger.info("Success");
752                         PolicyLogger.audit("Transaction Ended Successfully");
753                 } catch (PAPException | IOException | NumberFormatException e) {
754                         if(pdpTransaction != null){
755                                 pdpTransaction.rollbackTransaction();
756                         }
757                         LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
758                         loggingContext.transactionEnded();
759                         PolicyLogger.audit("Transaction Failed - See Error.log");
760                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
761                         im.endTransaction();
762                         return;
763                 }
764                 //Catch anything that fell through
765                 loggingContext.transactionEnded();
766                 PolicyLogger.audit("Transaction Ended");
767                 im.endTransaction();
768         }
769
770         private void setResponseError(HttpServletResponse response,int responseCode, String message) {
771             try {
772                 if(message != null && !message.isEmpty()){
773                        response.sendError(responseCode, message);
774                 }
775         } catch (IOException e) {
776             LOGGER.error("Error setting Error response Header ", e);
777         }
778             return;
779     }
780
781     /**
782          * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
783          */
784         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
785                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
786                 loggingContext.transactionStarted();
787                 loggingContext.setServiceName("PAP.get");
788                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
789                         UUID requestID = UUID.randomUUID();
790                         loggingContext.setRequestID(requestID.toString());
791                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
792                 } else {
793                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
794                 }
795                         loggingContext.metricStarted();
796                         XACMLRest.dumpRequest(request);
797                         loggingContext.metricEnded();
798                         PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
799                         String pathInfo = request.getRequestURI();
800                         LOGGER.info("path info: " + pathInfo);
801                         if (pathInfo != null){
802                                 //DO NOT do a im.startTransaction for the test request
803                                 if (pathInfo.equals("/pap/test")) {
804                                         try {
805                                                 testService(loggingContext, response);
806                                         } catch (IOException e) {
807                                                 LOGGER.debug(e);
808                                         }
809                                         return;
810                                 }
811                         }
812                         //This im.startTransaction() covers all other Get transactions
813                         try {
814                                 loggingContext.metricStarted();
815                                 im.startTransaction();
816                                 loggingContext.metricEnded();
817                                 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
818                         } catch (AdministrativeStateException ae){
819                                 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
820                                                 + " state of " + im.getStateManager().getAdminState()
821                                                 + "\n Exception Message: " + ae.getMessage();
822                                 LOGGER.info(message, ae);
823                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
824                                 loggingContext.transactionEnded();
825                                 PolicyLogger.audit("Transaction Failed - See Error.log");
826                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
827                                 return;
828                         }catch (StandbyStatusException se) {
829                                 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
830                                                 + " of " + im.getStateManager().getStandbyStatus()
831                                                 + "\n Exception Message: " + se.getMessage();
832                                 LOGGER.info(message, se);
833                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
834                                 loggingContext.transactionEnded();
835                                 PolicyLogger.audit("Transaction Failed - See Error.log");
836                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
837                                 return;
838                         } catch (IntegrityMonitorException e) {
839                                 String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
840                                                 + "\n Exception Message: " + e.getMessage();
841                                 LOGGER.info(message, e);
842                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
843                                 loggingContext.transactionEnded();
844                                 PolicyLogger.audit("Transaction Failed - See Error.log");
845                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
846                                 return;
847                         }
848                         // Request from the API to get the gitPath
849                         String apiflag = request.getParameter("apiflag");
850                         if (apiflag!=null) {
851                                 if(authorizeRequest(request)){
852                                         APIRequestHandler apiRequestHandler = new APIRequestHandler();
853                                         try{                            
854                                                 loggingContext.metricStarted();
855                                             apiRequestHandler.doGet(request,response, apiflag);
856                                                 loggingContext.metricEnded();
857                                                 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
858                                         }catch(IOException e){
859                                             LOGGER.error(e);
860                                         }
861                                         loggingContext.transactionEnded();
862                                         PolicyLogger.audit("Transaction Ended Successfully");
863                                         im.endTransaction();
864                                         return;
865                                 } else {
866                                         String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
867                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
868                                         loggingContext.transactionEnded();
869                                         PolicyLogger.audit("Transaction Failed - See Error.log");
870                                         setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
871                                         im.endTransaction();
872                                         return;
873                                 }
874                         }
875                         // Is this from the Admin Console?
876                         String groupId = request.getParameter("groupId");
877                         if (groupId != null) {
878                                 // this is from the Admin Console, so handle separately
879                                 try{
880                                         loggingContext.metricStarted();
881                                     doACGet(request, response, groupId, loggingContext);
882                                         loggingContext.metricEnded();
883                                         PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
884                                 } catch(IOException e){
885                     LOGGER.error(e);
886                 }
887                                 loggingContext.transactionEnded();
888                                 PolicyLogger.audit("Transaction Ended Successfully");
889                                 im.endTransaction();
890                                 return;
891                         }
892                         // Get the PDP's ID
893                         String id = this.getPDPID(request);
894                         LOGGER.info("doGet from: " + id);
895                         // Get the PDP Object
896                         OnapPDP pdp = null;
897                         try{
898                             pdp = XACMLPapServlet.papEngine.getPDP(id);
899                         }catch(PAPException e){
900                             LOGGER.error(e);
901                         }
902                         // Is it known?
903                         if (pdp == null) {
904                                 // Check if request came from localhost
905                                 if (request.getRemoteHost().equals("localhost") ||
906                                                 request.getRemoteHost().equals(request.getLocalAddr())) {
907                                         // Return status information - basically all the groups
908                                         loggingContext.setServiceName("PAP.getGroups");
909                                         Set<OnapPDPGroup> groups = null;
910                                         try {
911                                             groups = papEngine.getOnapPDPGroups();
912                                         } catch(PAPException e) {
913                                             LOGGER.debug(e);
914                                             PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
915                                             loggingContext.transactionEnded();
916                                             PolicyLogger.audit("Transaction Failed - See Error.log");
917                                             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
918                                             im.endTransaction();
919                                             return;
920                                         }
921                                         // convert response object to JSON and include in the response
922                                         mapperWriteValue(new ObjectMapper(), response,  groups);
923                                         response.setHeader("content-type", "application/json");
924                                         response.setStatus(HttpServletResponse.SC_OK);
925                                         loggingContext.transactionEnded();
926                                         PolicyLogger.audit("Transaction Ended Successfully");
927                                         im.endTransaction();
928                                         return;
929                                 }
930                                 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
931                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
932                                 loggingContext.transactionEnded();
933                                 PolicyLogger.audit("Transaction Failed - See Error.log");
934                                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
935                                 im.endTransaction();
936                                 return;
937                         }
938                         loggingContext.setServiceName("PAP.getPolicy");
939                         // Get the PDP's Group
940                         OnapPDPGroup group = null;
941                         try {
942                             group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
943                         } catch (PAPException e) {
944                             LOGGER.error(e);
945                         }
946                         if (group == null) {
947                                 String message = "No group associated with pdp " + pdp.getId();
948                                 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
949                                 loggingContext.transactionEnded();
950                                 PolicyLogger.audit("Transaction Failed - See Error.log");
951                                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
952                                 im.endTransaction();
953                                 return;
954                         }
955                         // Which policy do they want?
956                         String policyId = request.getParameter("id");
957                         if (policyId == null) {
958                                 String message = "Did not specify an id for the policy";
959                                 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
960                                 loggingContext.transactionEnded();
961                                 PolicyLogger.audit("Transaction Failed - See Error.log");
962                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
963                                 im.endTransaction();
964                                 return;
965                         }
966                         PDPPolicy policy = group.getPolicy(policyId);
967                         if (policy == null) {
968                                 String message = "Unknown policy: " + policyId;
969                                 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
970                                 loggingContext.transactionEnded();
971                                 PolicyLogger.audit("Transaction Failed - See Error.log");
972                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
973                                 im.endTransaction();
974                                 return;
975                         }
976                         try{
977                     LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
978                             + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
979                         } catch (PAPException| IOException e){
980                             LOGGER.error(e);
981                         }
982                         try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
983                                 // Send the policy back
984                                 IOUtils.copy(is, os);
985                                 response.setStatus(HttpServletResponse.SC_OK);
986                                 loggingContext.transactionEnded();
987                                 auditLogger.info("Success");
988                                 PolicyLogger.audit("Transaction Ended Successfully");
989                         } catch (IOException e) {
990                                 String message = "Failed to open policy id " + policyId;
991                                 LOGGER.debug(e);
992                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
993                                 loggingContext.transactionEnded();
994                                 PolicyLogger.audit("Transaction Failed - See Error.log");
995                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
996                         }
997                 loggingContext.transactionEnded();
998                 PolicyLogger.audit("Transaction Ended");
999                 im.endTransaction();
1000         }
1001         
1002         /**
1003          * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
1004          */
1005         protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1006                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1007                 loggingContext.transactionStarted();
1008                 loggingContext.setServiceName("PAP.put");
1009                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1010                         UUID requestID = UUID.randomUUID();
1011                         loggingContext.setRequestID(requestID.toString());
1012                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
1013                 } else {
1014                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
1015                 }
1016                 try {
1017                         loggingContext.metricStarted();
1018                         im.startTransaction();
1019                         loggingContext.metricEnded();
1020                         PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
1021                 } catch(AdministrativeStateException e) {
1022                     String message = "PUT interface called for PAP " + papResourceName + 
1023                             " but it has an Administrative state of " + im.getStateManager().getAdminState() +
1024                             "\n Exception Message: " + e.getMessage();
1025                     logMessage(e, message, loggingContext, response);
1026                     return;
1027                 } catch(StandbyStatusException e) {
1028                     String message = "PUT interface called for PAP " + papResourceName + 
1029                             " but it has a Standby Status of " + im.getStateManager().getStandbyStatus() +
1030                             "\n Exception Message: " + e.getMessage();
1031                     logMessage(e, message, loggingContext, response);
1032                     return;
1033                 } catch (IntegrityMonitorException e) {
1034                     String message = "PUT interface called for PAP " + papResourceName +
1035                             " but an exception occurred" +
1036                             "\n Exception Message: " + e.getMessage();
1037                     logMessage(e, message, loggingContext, response);
1038                     return;
1039                 }
1040
1041                 loggingContext.metricStarted();
1042                 XACMLRest.dumpRequest(request);
1043                 loggingContext.metricEnded();
1044                 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1045                 //need to check if request is from the API or Admin console
1046                 String apiflag = request.getParameter("apiflag");
1047                 //This would occur if a PolicyDBDao notification was received
1048                 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1049                 if(policyDBDaoRequestUrl != null){
1050                         LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
1051                         String policyDBDaoRequestEntityId = request.getParameter("entityid");
1052                         String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1053                         String policyDBDaoRequestExtraData = request.getParameter("extradata");
1054                         if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1055                                 setResponseError(response,400, "entityid or entitytype not supplied");
1056                                 loggingContext.transactionEnded();
1057                                 PolicyLogger.audit("Transaction Ended Successfully");
1058                                 im.endTransaction();
1059                                 return;
1060                         }
1061                         loggingContext.metricStarted(); 
1062                         LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1063                         policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1064                         loggingContext.metricEnded();
1065                         PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1066                         response.setStatus(200);
1067                         loggingContext.transactionEnded();
1068                         PolicyLogger.audit("Transaction Ended Successfully");
1069                         im.endTransaction();
1070                         return;
1071                 }
1072                 /*
1073                  * Request for ImportService 
1074                  */
1075                 String importService = request.getParameter("importService");
1076                 if (importService != null) {
1077                         if(authorizeRequest(request)){
1078                                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1079                                 try{
1080                                         loggingContext.metricStarted(); 
1081                                     apiRequestHandler.doPut(request, response, importService);
1082                                         loggingContext.metricEnded();
1083                                         PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1084                                 }catch(IOException e){
1085                                     LOGGER.error(e);
1086                                 }
1087                                 im.endTransaction();
1088                                 return;
1089                         } else {
1090                                 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1091                                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1092                                 loggingContext.transactionEnded();
1093                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1094                                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1095                                 return;
1096                         }
1097                 }
1098                 //
1099                 // See if this is Admin Console registering itself with us
1100                 //
1101                 String acURLString = request.getParameter("adminConsoleURL");
1102                 if (acURLString != null) {
1103                         loggingContext.setServiceName("AC:PAP.register");
1104                         // remember this Admin Console for future updates
1105                         if ( ! adminConsoleURLStringList.contains(acURLString)) {
1106                                 adminConsoleURLStringList.add(acURLString);
1107                         }
1108                         if (LOGGER.isDebugEnabled()) {
1109                                 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1110                         }
1111                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1112                         loggingContext.transactionEnded();
1113                         auditLogger.info("Success");
1114                         PolicyLogger.audit("Transaction Ended Successfully");
1115                         im.endTransaction();
1116                         return;
1117                 }
1118                 /*
1119                  * This is to update the PDP Group with the policy/policies being pushed
1120                  * Part of a 2 step process to push policies to the PDP that can now be done 
1121                  * From both the Admin Console and the PolicyEngine API
1122                  */
1123                 String groupId = request.getParameter("groupId");
1124                 if (groupId != null) {
1125                         if(apiflag!=null){
1126                                 if(!authorizeRequest(request)){
1127                                         String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1128                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1129                                         loggingContext.transactionEnded();
1130                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1131                                         setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1132                                         return;
1133                                 }
1134                                 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1135                                     try{
1136                                         updateGroupsFromAPI(request, response, groupId, loggingContext);
1137                                     }catch(IOException e){
1138                                         LOGGER.error(e);
1139                                     }
1140                                         loggingContext.transactionEnded();
1141                                         PolicyLogger.audit("Transaction Ended Successfully");
1142                                         im.endTransaction();
1143                                         return;
1144                                 }
1145                         }
1146                         // this is from the Admin Console, so handle separately
1147                         try {
1148                                 loggingContext.metricEnded();
1149                             doACPut(request, response, groupId, loggingContext);
1150                                 loggingContext.metricEnded();
1151                                 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1152                         } catch (IOException e) {
1153                 LOGGER.error(e);
1154             }
1155                         loggingContext.transactionEnded();
1156                         PolicyLogger.audit("Transaction Ended Successfully");
1157                         im.endTransaction();
1158                         return;
1159                 }
1160                 //
1161                 // Request is for policy validation and creation
1162                 //
1163                 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1164                         // this request is from the Admin Console
1165                         SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1166                         try{
1167                                 loggingContext.metricStarted();
1168                             savePolicyHandler.doPolicyAPIPut(request, response);
1169                                 loggingContext.metricEnded();
1170                                 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1171                         } catch (IOException e) {
1172                 LOGGER.error(e);
1173             }
1174                         loggingContext.transactionEnded();
1175                         PolicyLogger.audit("Transaction Ended Successfully");
1176                         im.endTransaction();
1177                         return;
1178                 } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1179                         // this request is from the Policy Creation API 
1180                         if(authorizeRequest(request)){
1181                                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1182                                 try{
1183                                         loggingContext.metricStarted();
1184                                     apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1185                                         loggingContext.metricEnded();
1186                                         PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1187                     } catch (IOException e) {
1188                         LOGGER.error(e);
1189                     }
1190                                 loggingContext.transactionEnded();
1191                                 PolicyLogger.audit("Transaction Ended Successfully");
1192                                 im.endTransaction();
1193                                 return;
1194                         } else {
1195                                 String message = "PEP not Authorized for making this Request!!";
1196                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1197                                 loggingContext.transactionEnded();
1198                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1199                                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1200                                 im.endTransaction();
1201                                 return;
1202                         }
1203                 }
1204                 // We do not expect anything from anywhere else.
1205                 // This method is here in case we ever need to support other operations.
1206                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1207                 loggingContext.transactionEnded();
1208                 PolicyLogger.audit("Transaction Failed - See Error.log");
1209                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1210                 loggingContext.transactionEnded();
1211                 PolicyLogger.audit("Transaction Failed - See error.log");
1212                 im.endTransaction();
1213         }
1214
1215         /**
1216          * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1217          */
1218         protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1219                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1220                 loggingContext.transactionStarted();
1221                 loggingContext.setServiceName("PAP.delete");
1222                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1223                         UUID requestID = UUID.randomUUID();
1224                         loggingContext.setRequestID(requestID.toString());
1225                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1226                 } else {
1227                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1228                 }
1229                 try {
1230                         loggingContext.metricStarted();
1231                         im.startTransaction();
1232                         loggingContext.metricEnded();
1233                         PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1234                 } catch (AdministrativeStateException ae){
1235                         String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1236                                         + " state of " + im.getStateManager().getAdminState()
1237                                         + "\n Exception Message: " + ae.getMessage();
1238                         LOGGER.info(message, ae);
1239                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1240                         loggingContext.transactionEnded();
1241                         PolicyLogger.audit("Transaction Failed - See Error.log");
1242                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1243                         return;
1244                 }catch (StandbyStatusException se) {
1245                         String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1246                                         + " of " + im.getStateManager().getStandbyStatus()
1247                                         + "\n Exception Message: " + se.getMessage();
1248                         LOGGER.info(message, se);
1249                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1250                         loggingContext.transactionEnded();
1251                         PolicyLogger.audit("Transaction Failed - See Error.log");
1252                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1253                         return;
1254                 } catch (IntegrityMonitorException e) {
1255                         String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
1256                                         + "\n Exception Message: " + e.getMessage();
1257                         LOGGER.info(message, e);
1258                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1259                         loggingContext.transactionEnded();
1260                         PolicyLogger.audit("Transaction Failed - See Error.log");
1261                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1262                         return;
1263                 }
1264                 loggingContext.metricStarted();
1265                 XACMLRest.dumpRequest(request);
1266                 loggingContext.metricEnded();
1267                 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1268                 String groupId = request.getParameter("groupId");
1269                 String apiflag = request.getParameter("apiflag");
1270                 if (groupId != null) {
1271                         // Is this from the Admin Console or API?
1272                         if(apiflag!=null) {
1273                                 if(!authorizeRequest(request)){
1274                                         String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1275                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1276                                         loggingContext.transactionEnded();
1277                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1278                                         setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1279                                         return;
1280                                 }
1281                                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1282                                 try {
1283                                         loggingContext.metricStarted();
1284                                         apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1285                                         loggingContext.metricEnded();
1286                                         PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1287                                 } catch (Exception e) {
1288                                         LOGGER.error("Exception Occured"+e);
1289                                 }
1290                                 if(apiRequestHandler.getNewGroup()!=null){
1291                                         groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1292                                 }
1293                                 return;
1294                         }
1295                         // this is from the Admin Console, so handle separately
1296                         try{
1297                                 loggingContext.metricStarted();
1298                             doACDelete(request, response, groupId, loggingContext);
1299                                 loggingContext.metricEnded();
1300                                 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1301                         } catch (IOException e) {
1302                 LOGGER.error(e);
1303             }
1304                         loggingContext.transactionEnded();
1305                         PolicyLogger.audit("Transaction Ended Successfully");
1306                         im.endTransaction();
1307                         return;
1308                 }
1309                 //Catch anything that fell through
1310                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1311                 loggingContext.transactionEnded();
1312                 PolicyLogger.audit("Transaction Failed - See Error.log");
1313                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1314                 im.endTransaction();
1315         }
1316
1317         private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1318                 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1319                 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1320                 if (localRootPolicies == null || localReferencedPolicies == null) {
1321                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+"  ReferencedPolicies="+localReferencedPolicies);
1322                         return false;
1323                 }
1324                 // Compare the policies and pipconfig properties to the pdpProperties
1325                 try {
1326                         // the policy properties includes only xacml.rootPolicies and 
1327                         // xacml.referencedPolicies without any .url entries
1328                         Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1329                         Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1330                         if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1331                                         localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1332                                         pdpPipConfig.equals(pipconfig)) {
1333                                 // The PDP is current
1334                                 return true;
1335                         }
1336                 } catch (Exception e) {
1337                         // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1338                         // or if there are policies that do not have a corresponding ".url" property.
1339                         // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1340                         PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1341                 }
1342                 return false;
1343         }
1344
1345         private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1346                 String lists[] = new String[2];
1347                 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1348                 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1349                 for (String list : lists) {
1350                         if (list != null && list.isEmpty() == false) {
1351                                 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1352                                         String url = urlPath + "?id=" + id;
1353                                         LOGGER.info("Policy URL for " + id + ": " + url);
1354                                         policies.setProperty(id + ".url", url);
1355                                 }
1356                         }
1357                 }
1358         }
1359
1360         protected String getPDPID(HttpServletRequest request) {
1361                 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1362                 if (pdpURL == null || pdpURL.isEmpty()) {
1363                         // Should send back its port for identification
1364                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1365                         pdpURL = "";
1366                 }
1367                 return pdpURL;
1368         }
1369
1370         protected String getPDPJMX(HttpServletRequest request) {
1371                 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1372                 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1373                         // Should send back its port for identification
1374                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1375                         return null;
1376                 }
1377                 return pdpJMMX;
1378         }
1379         
1380         /**
1381          * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1382          * 
1383          * @param request
1384          * @param response
1385          * @param groupId
1386          * @param loggingContext 
1387          * @throws ServletException
1388          * @throws IOException
1389          */
1390         public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1391                 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1392                 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1393                 try {
1394                         // for PUT operations the group may or may not need to exist before the operation can be done
1395                         StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1396                         
1397                         // get the request input stream content into a String
1398                         String json = null;
1399                         java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1400                         scanner.useDelimiter("\\A");
1401                         json =  scanner.hasNext() ? scanner.next() : "";
1402                         scanner.close();
1403
1404                         PolicyLogger.info("pushPolicy request from API: " + json);
1405                         
1406                         // convert Object sent as JSON into local object
1407                         StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1408                         
1409                         //Get the current policies from the Group and Add the new one
1410                         Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1411                         currentPoliciesInGroup = group.getPolicies();
1412                         //If the selected policy is in the group we must remove the old version of it
1413                         LOGGER.info("Removing old version of the policy");
1414                         for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
1415                                 if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
1416                                         group.removePolicy(existingPolicy);
1417                                         LOGGER.info("Removing policy: " + existingPolicy);
1418                                         break;
1419                                 }
1420                         }
1421                         
1422                         // Assume that this is an update of an existing PDP Group
1423                         loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1424                         try{
1425                                 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1426                         } catch(Exception e){
1427                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1428                                                 +"group="+group.getId());
1429                                 throw new PAPException(e.getMessage()); 
1430                         }
1431                         
1432                         LOGGER.info("Calling updatGroup() with new group");
1433                         papEngine.updateGroup(group);
1434                         String policyId = "empty";
1435                         if(policy !=null && policy.getId() != null){
1436                                 policyId = policy.getId();
1437                         }
1438                         if(!policyId.matches(REGEX) ){
1439                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1440                                 response.addHeader("error",ADD_GROUP_ERROR);
1441                                 response.addHeader("message", "Policy Id is not valid");
1442                                 return;
1443                         }
1444                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1445                         response.addHeader("operation", "push");
1446                         response.addHeader("policyId", policyId);
1447                         response.addHeader("groupId", groupId);
1448                         
1449                         LOGGER.info("Group '" + group.getId() + "' updated");
1450                         
1451                         loggingContext.metricStarted();
1452                         acPutTransaction.commitTransaction();
1453                         loggingContext.metricEnded();
1454                         PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1455                         loggingContext.metricStarted();
1456                         notifyAC();
1457                         loggingContext.metricEnded();
1458                         PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1459
1460                         // Group changed, which might include changing the policies     
1461                         groupChanged(group, loggingContext);
1462                         loggingContext.transactionEnded();
1463                         LOGGER.info("Success");
1464
1465                         if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1466                                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1467                                 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1468                                         LOGGER.debug("Precheck Successful.");
1469                                 }
1470                         }
1471
1472                         PolicyLogger.audit("Transaction Ended Successfully");
1473                         return;
1474                 } catch (PAPException e) {
1475                         acPutTransaction.rollbackTransaction();
1476                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1477                         loggingContext.transactionEnded();
1478                         PolicyLogger.audit("Transaction Failed - See Error.log");
1479                         String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1480                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1481                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1482                         response.addHeader("error",ADD_GROUP_ERROR);
1483                         response.addHeader("message", message);
1484                         return;
1485                 }
1486         }
1487
1488         /**
1489          * Requests from the Admin Console for operations not on single specific objects
1490          * 
1491          * @param request
1492          * @param response
1493          * @param groupId
1494          * @param loggingContext
1495          * @throws ServletException
1496          * @throws IOException
1497          */
1498         private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1499                 PolicyDBDaoTransaction doACPostTransaction = null;
1500                 try {
1501                         String groupName = request.getParameter("groupName");
1502                         String groupDescription = request.getParameter("groupDescription");
1503                         String apiflag = request.getParameter("apiflag");
1504                         if (groupName != null && groupDescription != null) {
1505                                 // Args:              group=<groupId> groupName=<name> groupDescription=<description>            <= create a new group
1506                                 loggingContext.setServiceName("AC:PAP.createGroup");
1507                                 String unescapedName = null;
1508                                 String unescapedDescription = null;
1509                                 try{
1510                                     unescapedName = URLDecoder.decode(groupName, "UTF-8");
1511                                     unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1512                                 } catch (UnsupportedEncodingException e) {
1513                                     LOGGER.error(e);
1514                                 }
1515                                 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1516                                 try {                                   
1517                                         newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1518                                         papEngine.newGroup(unescapedName, unescapedDescription);
1519                                         loggingContext.metricStarted();
1520                                         newGroupTransaction.commitTransaction();
1521                                         loggingContext.metricEnded();
1522                                         PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1523                                 } catch (Exception e) {
1524                                         newGroupTransaction.rollbackTransaction();
1525                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1526                                         loggingContext.transactionEnded();
1527                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1528                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1529                                         return;
1530                                 }
1531                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1532                                 if (LOGGER.isDebugEnabled()) {
1533                                         LOGGER.debug("New Group '" + groupId + "' created");
1534                                 }
1535                                 // tell the Admin Consoles there is a change
1536                                 loggingContext.metricStarted();
1537                                 notifyAC();
1538                                 loggingContext.metricEnded();
1539                                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1540                                 // new group by definition has no PDPs, so no need to notify them of changes
1541                                 loggingContext.transactionEnded();
1542                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1543                                 auditLogger.info("Success");
1544                                 PolicyLogger.audit("Transaction Ended Successfully");
1545                                 return;
1546                         }
1547                         // for all remaining POST operations the group must exist before the operation can be done
1548                         OnapPDPGroup group = null;
1549                         try{
1550                             group = papEngine.getGroup(groupId);
1551                         } catch (PAPException e){
1552                             LOGGER.error(e);
1553                         }
1554                         if (group == null) {
1555                                 String message = "Unknown groupId '" + groupId + "'";
1556                                 //for fixing Header Manipulation of Fortify issue
1557                                 if(!message.matches(REGEX)){
1558                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1559                                         response.addHeader("error",ADD_GROUP_ERROR);
1560                                         response.addHeader("message", "GroupId Id is not valid");
1561                                         return;
1562                                 }
1563                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1564                                 loggingContext.transactionEnded();
1565                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1566                                 if (apiflag!=null){
1567                                         response.addHeader("error", "unknownGroupId");
1568                                         response.addHeader("operation", "push");
1569                                         response.addHeader("message", message);
1570                                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1571                                 } else {
1572                                         setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1573                                 }
1574                                 return;
1575                         }
1576                         
1577                         // If the request contains a policyId then we know we are pushing the policy to PDP
1578                         if (request.getParameter("policyId") != null) {
1579                                 
1580                                 if(apiflag!=null){
1581                                         loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1582                                         LOGGER.info("PushPolicy Request From The API");
1583                                 } else {
1584                                         loggingContext.setServiceName("AC:PAP.postPolicy");
1585                                         LOGGER.info("PushPolicy Request From The AC");
1586                                 }
1587                                 
1588                                 String policyId = request.getParameter("policyId");
1589                                 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1590                                 StdPDPGroup updatedGroup = null;
1591                                 try {
1592                                         //Copying the policy to the file system and updating groups in database
1593                                         LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
1594                                         updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1595                                         loggingContext.metricStarted();
1596                                         addPolicyToGroupTransaction.commitTransaction();
1597                                         loggingContext.metricEnded();
1598                                         PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1599                                         LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
1600                                         
1601                                 } catch (Exception e) {
1602                                         addPolicyToGroupTransaction.rollbackTransaction();
1603                                         String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1604                                         //for fixing Header Manipulation of Fortify issue
1605                                         if(!message.matches(REGEX)){
1606                                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1607                                                 response.addHeader("error",ADD_GROUP_ERROR);
1608                                                 response.addHeader("message", "Policy Id is not valid");
1609                                                 return;
1610                                         }
1611                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1612                                         loggingContext.transactionEnded();
1613                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1614                                         if (apiflag!=null){
1615                                                 response.addHeader("error", "policyCopyError");
1616                                                 response.addHeader("message", message);
1617                                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1618                                         } else {
1619                                                 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1620                                         }
1621                                         return;
1622                                 }
1623                                 
1624                                 if(apiflag != null){
1625                                         /*
1626                                          * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
1627                                          * The GUI does this from the POLICY-SDK-APP code.
1628                                          */
1629                                         
1630                                         // Get new transaction to perform updateGroup()
1631                                         PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1632                                         try {
1633                                                 // get the request content into a String and read the inputStream into a buffer
1634                                                 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1635                                                 scanner.useDelimiter("\\A");
1636                                                 String json =  scanner.hasNext() ? scanner.next() : "";
1637                                                 scanner.close();
1638                                                 
1639                                                 // convert Object sent as JSON into local object
1640                                                 ObjectMapper mapper = new ObjectMapper();
1641                                                 Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1642                                                 StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1643                                                 
1644                                                 LOGGER.info("Request JSON Payload: " + json);
1645
1646                                                 // Assume that this is an update of an existing PDP Group
1647                                                 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1648                                                 try{
1649                                                         acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
1650                                                 } catch(Exception e){
1651                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
1652                                                                         + e);
1653                                                         throw new PAPException(e.getMessage()); 
1654                                                 }
1655                                                 
1656                                                 LOGGER.info("Calling updatGroup() with new group");
1657                                                 papEngine.updateGroup(updatedGroup);
1658                                                 
1659                                                 LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
1660                                                 
1661                                                 // Commit transaction to send notification to other PAPs
1662                                                 loggingContext.metricStarted();
1663                                                 acPutTransaction.commitTransaction();
1664                                                 loggingContext.metricEnded();
1665                                                 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1666                                                 loggingContext.metricStarted();
1667                                                 
1668                                                 notifyAC();
1669                                                 loggingContext.metricEnded();
1670                                                 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1671                                                 
1672                                                 // Group changed to send notification to PDPs, which might include changing the policies        
1673                                                 groupChanged(updatedGroup,loggingContext);
1674                                                 loggingContext.transactionEnded();
1675                                                 LOGGER.info("Success");
1676
1677                                                 if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1678                                                         PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1679                                                         if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1680                                                                 LOGGER.debug("Precheck Successful.");
1681                                                         }
1682                                                 }
1683                                                 
1684                                                 //delete temporary policy file from the bin directory
1685                                                 Files.deleteIfExists(Paths.get(policy.getId()));
1686                                                         
1687                                         } catch (Exception e) {
1688                                                 acPutTransaction.rollbackTransaction();
1689                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1690                                                 loggingContext.transactionEnded();
1691                                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1692                                                 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
1693                                                 LOGGER.error(message);
1694                                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1695                                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1696                                                 response.addHeader("error",ADD_GROUP_ERROR);
1697                                                 response.addHeader("message", message);
1698                                                 return;
1699                                         }
1700                                 }
1701                                 
1702                                 // policy file copied ok and the Group was updated on the PDP
1703                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1704                                 response.addHeader("operation", "push");
1705                                 response.addHeader("policyId", policyId);
1706                                 response.addHeader("groupId", groupId);
1707                                 
1708                                 LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1709                                 loggingContext.transactionEnded();
1710                                 auditLogger.info("Success");
1711                                 LOGGER.info("Transaction Ended Successfully");
1712                                 
1713                                 return;
1714                         } else if (request.getParameter("default") != null) {
1715                                 // Args:       group=<groupId> default=true               <= make default
1716                                 // change the current default group to be the one identified in the request.
1717                                 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1718                                 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1719                                 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1720                                 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1721                                 try {
1722                                         setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1723                                         papEngine.setDefaultGroup(group);
1724                                         loggingContext.metricStarted();
1725                                         setDefaultGroupTransaction.commitTransaction();
1726                                         loggingContext.metricEnded();
1727                                         PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1728                                 } catch (Exception e) {
1729                                         setDefaultGroupTransaction.rollbackTransaction();
1730                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1731                                         loggingContext.transactionEnded();
1732                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1733                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1734                                         return;
1735                                 }
1736                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1737                                 if (LOGGER.isDebugEnabled()) {
1738                                         LOGGER.debug("Group '" + groupId + "' set to be default");
1739                                 }
1740                                 // Notify the Admin Consoles that something changed
1741                                 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1742                                 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1743                                 loggingContext.metricStarted();
1744                                 notifyAC();
1745                                 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1746                                 loggingContext.metricEnded();
1747                                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1748                                 loggingContext.transactionEnded();
1749                                 auditLogger.info("Success");
1750                                 LOGGER.info("Transaction Ended Successfully");
1751                                 return;
1752                         } else if (request.getParameter("pdpId") != null) {
1753                                 doACPostTransaction = policyDBDao.getNewTransaction();
1754                                 // Args:       group=<groupId> pdpId=<pdpId>               <= move PDP to group
1755                                 loggingContext.setServiceName("AC:PAP.movePDP");
1756                                 String pdpId = request.getParameter("pdpId");
1757                                 OnapPDP pdp = papEngine.getPDP(pdpId);
1758                                 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1759                                 try{
1760                                         doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1761                                 }catch(Exception e){    
1762                                         doACPostTransaction.rollbackTransaction();
1763                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", 
1764                                                         " Error while moving pdp in the database: "
1765                                                                         +"pdp="+pdp.getId()+",to group="+group.getId());
1766                                         throw new PAPException(e.getMessage());
1767                                 }
1768                                 papEngine.movePDP((OnapPDP) pdp, group);
1769                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1770                                 if (LOGGER.isDebugEnabled()) {
1771                                         LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1772                                 }
1773                                 // update the status of both the original group and the new one
1774                                 ((StdPDPGroup)originalGroup).resetStatus();
1775                                 ((StdPDPGroup)group).resetStatus();
1776                                 // Notify the Admin Consoles that something changed
1777                                 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1778                                 loggingContext.metricStarted();
1779                                 notifyAC();
1780                                 loggingContext.metricEnded();
1781                                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1782                                 // Need to notify the PDP that it's config may have changed
1783                                 pdpChanged(pdp, loggingContext);
1784                                 loggingContext.metricStarted();
1785                                 doACPostTransaction.commitTransaction();
1786                                 loggingContext.metricEnded();
1787                                 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1788                                 loggingContext.transactionEnded();
1789                                 auditLogger.info("Success");
1790                                 PolicyLogger.audit("Transaction Ended Successfully");
1791                                 return;
1792                         }
1793                 } catch (PAPException e) {
1794                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1795                         loggingContext.transactionEnded();
1796                         PolicyLogger.audit("Transaction Failed - See Error.log");
1797                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1798                         return;
1799                 }
1800         }
1801
1802         /**
1803          * Requests from the Admin Console to GET info about the Groups and PDPs
1804          * 
1805          * @param request
1806          * @param response
1807          * @param groupId
1808          * @param loggingContext 
1809          * @throws ServletException
1810          * @throws IOException
1811          */
1812         private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1813                 try {
1814                         String parameterDefault = request.getParameter("default");
1815                         String pdpId = request.getParameter("pdpId");
1816                         String pdpGroup = request.getParameter("getPDPGroup");
1817                         if ("".equals(groupId)) {
1818                                 // request IS from AC but does not identify a group by name
1819                                 if (parameterDefault != null) {
1820                                         // Request is for the Default group (whatever its id)
1821                                         loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1822                                         OnapPDPGroup group = papEngine.getDefaultGroup();
1823                                         // convert response object to JSON and include in the response
1824                                         mapperWriteValue(new ObjectMapper(), response,  group);
1825                                         if (LOGGER.isDebugEnabled()) {
1826                                                 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1827                                         }
1828                                         response.setStatus(HttpServletResponse.SC_OK);
1829                                         response.setHeader("content-type", "application/json");
1830                                         try{
1831                         response.getOutputStream().close();
1832                     } catch (IOException e){
1833                         LOGGER.error(e);
1834                     }
1835                                         loggingContext.transactionEnded();
1836                                         auditLogger.info("Success");
1837                                         PolicyLogger.audit("Transaction Ended Successfully");
1838                                         return;
1839                                 } else if (pdpId != null) {
1840                                         // Request is related to a PDP
1841                                         if (pdpGroup == null) {
1842                                                 // Request is for the (unspecified) group containing a given PDP
1843                                                 loggingContext.setServiceName("AC:PAP.getPDP");
1844                                                 OnapPDP pdp = null;
1845                                                 try{
1846                                                     pdp = papEngine.getPDP(pdpId);
1847                                                 }catch(PAPException e){
1848                                                     LOGGER.error(e);
1849                                                 }
1850                                                 // convert response object to JSON and include in the response
1851                                                 mapperWriteValue(new ObjectMapper(), response,  pdp);
1852                                                 if (LOGGER.isDebugEnabled()) {
1853                                                         LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1854                                                 }
1855                                                 response.setStatus(HttpServletResponse.SC_OK);
1856                                                 response.setHeader("content-type", "application/json");
1857                                                 try{
1858                             response.getOutputStream().close();
1859                         } catch (IOException e){
1860                             LOGGER.error(e);
1861                         }
1862                                                 loggingContext.transactionEnded();
1863                                                 auditLogger.info("Success");
1864                                                 PolicyLogger.audit("Transaction Ended Successfully");
1865                                                 return;
1866                                         } else {
1867                                                 // Request is for the group containing a given PDP
1868                                                 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1869                                                 OnapPDPGroup group =null;
1870                                                 try{
1871                                                     OnapPDP pdp = papEngine.getPDP(pdpId);
1872                                 group = papEngine.getPDPGroup((OnapPDP) pdp);
1873                                                 }catch(PAPException e){
1874                                                     LOGGER.error(e);
1875                                                 }
1876                                                 // convert response object to JSON and include in the response
1877                                                 mapperWriteValue(new ObjectMapper(), response,  group);
1878                                                 if (LOGGER.isDebugEnabled()) {
1879                                                         LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1880                                                 }
1881                                                 response.setStatus(HttpServletResponse.SC_OK);
1882                                                 response.setHeader("content-type", "application/json");
1883                                                 try{
1884                                 response.getOutputStream().close();
1885                             } catch (IOException e){
1886                                 LOGGER.error(e);
1887                             }
1888                                                 loggingContext.transactionEnded();
1889                                                 auditLogger.info("Success");
1890                                                 PolicyLogger.audit("Transaction Ended Successfully");
1891                                                 return;
1892                                         }
1893                                 } else {
1894                                         // request is for top-level properties about all groups
1895                                         loggingContext.setServiceName("AC:PAP.getAllGroups");
1896                                         Set<OnapPDPGroup> groups = null;
1897                                         try {
1898                                             groups = papEngine.getOnapPDPGroups();
1899                                         } catch(PAPException e) {
1900                                             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1901                                             loggingContext.transactionEnded();
1902                                             PolicyLogger.audit("Transaction Failed - See Error.log");
1903                                             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1904                                             return;
1905                                         }
1906                                         // convert response object to JSON and include in the response
1907                                         mapperWriteValue(new ObjectMapper(), response,  groups);
1908                                         if (LOGGER.isDebugEnabled()) {
1909                                                 LOGGER.debug("GET All groups req");
1910                                         }
1911                                         response.setStatus(HttpServletResponse.SC_OK);
1912                                         response.setHeader("content-type", "application/json");
1913                                         try{
1914                             response.getOutputStream().close();
1915                         } catch (IOException e){
1916                             LOGGER.error(e);
1917                         }
1918                                         loggingContext.transactionEnded();
1919                                         auditLogger.info("Success");
1920                                         PolicyLogger.audit("Transaction Ended Successfully");
1921                                         return;
1922                                 }
1923                         }
1924                         // for all other GET operations the group must exist before the operation can be done
1925                         OnapPDPGroup group = null;
1926                         try{
1927                             group = papEngine.getGroup(groupId);
1928                         } catch(PAPException e){
1929                             LOGGER.error(e);
1930                         }
1931                         if (group == null) {
1932                                 String message = "Unknown groupId '" + groupId + "'";
1933                                 //for fixing Header Manipulation of Fortify issue
1934                                 if(!message.matches(REGEX)){
1935                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1936                                         response.addHeader("error",ADD_GROUP_ERROR);
1937                                         response.addHeader("message", "Group Id is not valid");
1938                                         return;
1939                                 }
1940                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1941                                 loggingContext.transactionEnded();
1942                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1943                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1944                                 return;
1945                         }
1946                         // Figure out which request this is based on the parameters
1947                         String policyId = request.getParameter("policyId");
1948                         if (policyId != null) {
1949                                 // retrieve a policy
1950                                 loggingContext.setServiceName("AC:PAP.getPolicy");
1951                                 // convert response object to JSON and include in the response
1952                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1953                                 loggingContext.transactionEnded();
1954                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1955                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1956                         } else {
1957                                 // No other parameters, so return the identified Group
1958                                 loggingContext.setServiceName("AC:PAP.getGroup");
1959                                 // convert response object to JSON and include in the response
1960                                 mapperWriteValue(new ObjectMapper(), response,  group);
1961                                 if (LOGGER.isDebugEnabled()) {
1962                                         LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1963                                 }
1964                                 response.setStatus(HttpServletResponse.SC_OK);
1965                                 response.setHeader("content-type", "application/json");
1966                                 try{
1967                                     response.getOutputStream().close();
1968                                 } catch (IOException e){
1969                                     LOGGER.error(e);
1970                                 }
1971                                 loggingContext.transactionEnded();
1972                                 auditLogger.info("Success");
1973                                 PolicyLogger.audit("Transaction Ended Successfully");
1974                                 return;
1975                         }
1976                         // Currently there are no other GET calls from the AC.
1977                         // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP.
1978                         // Other GETs that could be called:
1979                         //                              Specific Group  (groupId=<groupId>)
1980                         //                              A Policy                (groupId=<groupId> policyId=<policyId>)
1981                         //                              A PDP                   (groupId=<groupId> pdpId=<pdpId>)
1982                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1983                         loggingContext.transactionEnded();
1984                         PolicyLogger.audit("Transaction Failed - See Error.log");
1985                         setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1986                 } catch (PAPException e) {
1987                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1988                         loggingContext.transactionEnded();
1989                         PolicyLogger.audit("Transaction Failed - See Error.log");
1990                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1991                         return;
1992                 }
1993         }
1994         
1995         /**
1996          * Requests from the Admin Console to create new items or update existing ones
1997          * 
1998          * @param request
1999          * @param response
2000          * @param groupId
2001          * @param loggingContext 
2002          * @throws ServletException
2003          * @throws IOException
2004          */
2005         private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2006                 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
2007                 try {
2008                         // for PUT operations the group may or may not need to exist before the operation can be done
2009                         OnapPDPGroup group = papEngine.getGroup(groupId);
2010                         // determine the operation needed based on the parameters in the request
2011                         // for remaining operations the group must exist before the operation can be done
2012                         if (group == null) {
2013                                 String message = "Unknown groupId '" + groupId + "'";
2014                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2015                                 loggingContext.transactionEnded();
2016                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2017                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
2018                                 return;
2019                         }
2020                         if (request.getParameter("policy") != null) {
2021                                 //        group=<groupId> policy=<policyId> contents=policy file               <= Create new policy file in group dir, or replace it if it already exists (do not touch properties)
2022                                 loggingContext.setServiceName("AC:PAP.putPolicy");
2023                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!!  ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
2024                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2025                                 loggingContext.transactionEnded();
2026                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2027                                 auditLogger.info("Success");
2028                                 PolicyLogger.audit("Transaction Ended Successfully");
2029                                 return;
2030                         } else if (request.getParameter("pdpId") != null) {
2031                                 // ARGS:        group=<groupId> pdpId=<pdpId/URL>          <= create a new PDP or Update an Existing one
2032                                 String pdpId = request.getParameter("pdpId");
2033                                 if (papEngine.getPDP(pdpId) == null) {
2034                                         loggingContext.setServiceName("AC:PAP.createPDP");
2035                                 } else {
2036                                         loggingContext.setServiceName("AC:PAP.updatePDP");
2037                                 }
2038                                 // get the request content into a String
2039                                 String json = null;
2040                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2041                                 try{
2042                                     Scanner scanner = new Scanner(request.getInputStream());
2043                                     scanner.useDelimiter("\\A");
2044                         json =  scanner.hasNext() ? scanner.next() : "";
2045                         scanner.close();
2046                                 }catch(IOException e){
2047                                     LOGGER.error(e);
2048                                 }
2049                                 LOGGER.info("JSON request from AC: " + json);
2050                                 // convert Object sent as JSON into local object
2051                                 ObjectMapper mapper = new ObjectMapper();
2052                                 Object objectFromJSON = null;
2053                                 try {
2054                                     objectFromJSON = mapper.readValue(json, StdPDP.class);
2055                                 } catch(Exception e) {
2056                                     LOGGER.error(e);
2057                                 }
2058                                 if (pdpId == null ||
2059                                                 objectFromJSON == null ||
2060                                                 ! (objectFromJSON instanceof StdPDP) ||
2061                                                 ((StdPDP)objectFromJSON).getId() == null ||
2062                                                 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
2063                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
2064                                         loggingContext.transactionEnded();
2065                                         PolicyLogger.audit("Transaction Failed - See Error.log");
2066                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
2067                                 }
2068                                 StdPDP pdp = (StdPDP) objectFromJSON;
2069                                 if(pdp != null){
2070                                     OnapPDP oPDP = null;
2071                                     try{
2072                                         oPDP = papEngine.getPDP(pdpId);
2073                                     }catch (PAPException e){
2074                                         LOGGER.error(e);
2075                                     }
2076                                         if (oPDP == null) {
2077                                                 // this is a request to create a new PDP object
2078                                                 try{
2079                                                         acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), 
2080                                                                         pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
2081                                                 } catch(Exception e){
2082                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2083                                                                         +"pdp="+ (pdp.getId()) +",to group="+group.getId());
2084                                                         throw new PAPException(e.getMessage());
2085                                                 }
2086                                                 try{
2087                                                     papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
2088                                                 }catch(PAPException e){
2089                                                     LOGGER.error(e);
2090                                                 }
2091                                         } else {
2092                                                 try{
2093                                                         acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
2094                                                 } catch(Exception e){
2095                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
2096                                                                         +"pdp="+ pdp.getId());
2097                                                         throw new PAPException(e.getMessage());
2098                                                 }
2099                                                 // this is a request to update the pdp
2100                                                 try{
2101                                                     papEngine.updatePDP(pdp);
2102                                                 }catch(PAPException e){
2103                             LOGGER.error(e);
2104                         }
2105                                         }
2106                                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2107                                         if (LOGGER.isDebugEnabled()) {
2108                                                 LOGGER.debug("PDP '" + pdpId + "' created/updated");
2109                                         }
2110                                         // adjust the group's state including the new PDP
2111                                         ((StdPDPGroup)group).resetStatus();
2112                                         // tell the Admin Consoles there is a change
2113                                         loggingContext.metricStarted();
2114                                         notifyAC();
2115                                         loggingContext.metricEnded();
2116                                         PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2117                                         // this might affect the PDP, so notify it of the change
2118                                         pdpChanged(pdp, loggingContext);
2119                                         loggingContext.metricStarted();
2120                                         acPutTransaction.commitTransaction();
2121                                         loggingContext.metricEnded();
2122                                         PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2123                                         loggingContext.transactionEnded();
2124                                         auditLogger.info("Success");
2125                                         PolicyLogger.audit("Transaction Ended Successfully");
2126                                         return;
2127                                 }else{
2128                                         try{
2129                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2130                                                                 +"pdp=null" + ",to group="+group.getId());
2131                                                 throw new PAPException("PDP is null");
2132                                         } catch(Exception e){
2133                                                 throw new PAPException("PDP is null" + e.getMessage() +e);
2134                                         }
2135                                 }
2136                         } else if (request.getParameter("pipId") != null) {
2137                                 //                group=<groupId> pipId=<pipEngineId> contents=pip properties              <= add a PIP to pip config, or replace it if it already exists (lenient operation) 
2138                                 loggingContext.setServiceName("AC:PAP.putPIP");
2139                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2140                                 loggingContext.transactionEnded();
2141                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2142                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2143                                 return;
2144                         } else {
2145                                 // Assume that this is an update of an existing PDP Group
2146                                 // ARGS:        group=<groupId>         <= Update an Existing Group
2147                                 loggingContext.setServiceName("AC:PAP.updateGroup");
2148                                 // get the request content into a String
2149                                 String json = null;
2150                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2151                 try{
2152                     Scanner scanner = new Scanner(request.getInputStream());
2153                     scanner.useDelimiter("\\A");
2154                     json =  scanner.hasNext() ? scanner.next() : "";
2155                     scanner.close();
2156                 }catch(IOException e){
2157                     LOGGER.error(e);
2158                 }
2159                                 LOGGER.info("JSON request from AC: " + json);
2160                                 // convert Object sent as JSON into local object
2161                                 ObjectMapper mapper = new ObjectMapper();
2162                                 Object objectFromJSON = null;
2163                                 try {
2164                                     objectFromJSON  = mapper.readValue(json, StdPDPGroup.class);
2165                                 } catch(Exception e) {
2166                                     LOGGER.error(e);
2167                                 }
2168                                 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
2169                                                 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
2170                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
2171                                         loggingContext.transactionEnded();
2172                                         PolicyLogger.audit("Transaction Failed - See Error.log");
2173                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
2174                                 }
2175                                 // The Path on the PAP side is not carried on the RESTful interface with the AC
2176                                 // (because it is local to the PAP)
2177                                 // so we need to fill that in before submitting the group for update
2178                                 if(objectFromJSON != null){
2179                                         ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
2180                                 }
2181                                 try{
2182                                         if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
2183                                                 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
2184                                         } else {
2185                                                 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
2186                                         }
2187                                 } catch(Exception e){
2188                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
2189                                                         +"group="+group.getId());
2190                                         LOGGER.error(e);
2191                                         throw new PAPException(e.getMessage());
2192                                 }
2193                                 
2194                                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();  
2195                                 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;        
2196                                 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {               
2197                                         LOGGER.debug("Precheck Successful.");
2198                                 }
2199                                 try{
2200                                     papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2201                                 }catch(PAPException e){
2202                                     LOGGER.error(e);
2203                                 }
2204                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2205                                 if (LOGGER.isDebugEnabled()) {
2206                                         LOGGER.debug("Group '" + group.getId() + "' updated");
2207                                 }
2208                                 loggingContext.metricStarted();
2209                                 acPutTransaction.commitTransaction();
2210                                 loggingContext.metricEnded();
2211                                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2212                                 // tell the Admin Consoles there is a change
2213                                 loggingContext.metricStarted();
2214                                 notifyAC();
2215                                 loggingContext.metricEnded();
2216                                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2217                                 // Group changed, which might include changing the policies
2218                                 groupChanged(group, loggingContext);
2219                                 loggingContext.transactionEnded();
2220                                 auditLogger.info("Success");
2221                                 PolicyLogger.audit("Transaction Ended Successfully");
2222                                 return;
2223                         }
2224                 } catch (PAPException e) {
2225                         LOGGER.debug(e);
2226                         acPutTransaction.rollbackTransaction();
2227                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2228                         loggingContext.transactionEnded();
2229                         PolicyLogger.audit("Transaction Failed - See Error.log");
2230                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2231                         return;
2232                 }
2233         }
2234         
2235         /**
2236          * Requests from the Admin Console to delete/remove items
2237          * 
2238          * @param request
2239          * @param response
2240          * @param groupId
2241          * @param loggingContext 
2242          * @throws ServletException
2243          * @throws IOException
2244          */
2245         private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2246                 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2247                 try {
2248                         // for all DELETE operations the group must exist before the operation can be done
2249                         loggingContext.setServiceName("AC:PAP.delete");
2250                         OnapPDPGroup group = papEngine.getGroup(groupId);
2251                         if (group == null) {
2252                                 String message = "Unknown groupId '" + groupId + "'";
2253                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2254                                 loggingContext.transactionEnded();
2255                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2256                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2257                                 return;
2258                         }
2259                         // determine the operation needed based on the parameters in the request
2260                         if (request.getParameter("policy") != null) {
2261                                 //        group=<groupId> policy=<policyId>  [delete=<true|false>]       <= delete policy file from group
2262                                 loggingContext.setServiceName("AC:PAP.deletePolicy");
2263                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2264                                 loggingContext.transactionEnded();
2265                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2266                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2267                                 return;
2268                         } else if (request.getParameter("pdpId") != null) {
2269                                 // ARGS:        group=<groupId> pdpId=<pdpId>                  <= delete PDP 
2270                                 String pdpId = request.getParameter("pdpId");
2271                                 OnapPDP pdp = papEngine.getPDP(pdpId);
2272                                 try{
2273                                         removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2274                                 } catch(Exception e){
2275                                         throw new PAPException(e);
2276                                 }
2277                                 try{
2278                         papEngine.removePDP((OnapPDP) pdp);
2279                                 }catch(PAPException e){
2280                     LOGGER.error(e);
2281                 }
2282                                 // adjust the status of the group, which may have changed when we removed this PDP
2283                                 ((StdPDPGroup)group).resetStatus();
2284                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2285                                 loggingContext.metricStarted();
2286                                 notifyAC();
2287                                 loggingContext.metricEnded();
2288                                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2289                                 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2290                                 pdpChanged(pdp, loggingContext);
2291                                 loggingContext.metricStarted();
2292                                 removePdpOrGroupTransaction.commitTransaction();
2293                                 loggingContext.metricEnded();
2294                                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2295                                 loggingContext.transactionEnded();
2296                                 auditLogger.info("Success");
2297                                 PolicyLogger.audit("Transaction Ended Successfully");
2298                                 return;
2299                         } else if (request.getParameter("pipId") != null) {
2300                                 //        group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2301                                 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2302                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2303                                 loggingContext.transactionEnded();
2304                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2305                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2306                                 return;
2307                         } else {
2308                                 // ARGS:      group=<groupId> movePDPsToGroupId=<movePDPsToGroupId>            <= delete a group and move all its PDPs to the given group
2309                                 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2310                                 OnapPDPGroup moveToGroup = null;
2311                                 if (moveToGroupId != null) {
2312                                     try{
2313                                         moveToGroup = papEngine.getGroup(moveToGroupId);
2314                                     }catch(PAPException e){
2315                             LOGGER.error(e);
2316                         }
2317                                 }
2318                                 // get list of PDPs in the group being deleted so we can notify them that they got changed
2319                                 Set<OnapPDP> movedPDPs = new HashSet<>();
2320                                 movedPDPs.addAll(group.getOnapPdps());
2321                                 // do the move/remove
2322                                 try{
2323                                         removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2324                                 } catch(Exception e){
2325                                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2326                                         throw new PAPException(e.getMessage());
2327                                 }
2328                                 try{
2329                                     papEngine.removeGroup(group, moveToGroup);
2330                                 }catch(PAPException e){
2331                     LOGGER.error(e);
2332                 }
2333                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2334                                 loggingContext.metricStarted();
2335                                 notifyAC();
2336                                 loggingContext.metricEnded();
2337                                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2338                                 // notify any PDPs in the removed set that their config may have changed
2339                                 for (OnapPDP pdp : movedPDPs) {
2340                                         pdpChanged(pdp, loggingContext);
2341                                 }
2342                                 loggingContext.metricStarted();
2343                                 removePdpOrGroupTransaction.commitTransaction();
2344                                 loggingContext.metricEnded();
2345                                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2346                                 loggingContext.transactionEnded();
2347                                 auditLogger.info("Success");
2348                                 PolicyLogger.audit("Transaction Ended Successfully");
2349                                 return;
2350                         }
2351                 } catch (PAPException e) {
2352                         removePdpOrGroupTransaction.rollbackTransaction();
2353                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2354                         loggingContext.transactionEnded();
2355                         PolicyLogger.audit("Transaction Failed - See Error.log");
2356                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2357                         return;
2358                 }
2359         }
2360         
2361         /**
2362          * Heartbeat thread - periodically check on PDPs' status
2363          * 
2364          * Heartbeat with all known PDPs.
2365          * 
2366          * Implementation note:
2367          * 
2368          * The PDPs are contacted Sequentially, not in Parallel.
2369          * 
2370          * If we did this in parallel using multiple threads we would simultaneously use
2371          *              - 1 thread and
2372          *              - 1 connection
2373          * for EACH PDP.
2374          * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2375          * when user changes occur.
2376          * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2377          * 
2378          * The Sequential operation does a heartbeat request to each PDP one at a time.
2379          * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2380          * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2381          * it could take a long time to cycle through all of the PDPs.
2382          * That means that this may not notice a PDP being down in a predictable time.
2383          */
2384         private class Heartbeat implements Runnable {
2385                 private PAPPolicyEngine papEngine;
2386                 private Set<OnapPDP> pdps = new HashSet<>();
2387                 private int heartbeatInterval;
2388                 private int heartbeatTimeout;
2389
2390                 public volatile boolean isRunning = false;
2391
2392                 public synchronized boolean isRunning() {
2393                         return this.isRunning;
2394                 }
2395
2396                 public synchronized void terminate() {
2397                         this.isRunning = false;
2398                 }
2399
2400                 public Heartbeat(PAPPolicyEngine papEngine2) {
2401                         papEngine = papEngine2;
2402                         this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2403                         this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2404                 }
2405
2406                 @Override
2407                 public void run() {
2408                         // Set ourselves as running
2409                         synchronized(this) {
2410                                 this.isRunning = true;
2411                         }
2412                         HashMap<String, URL> idToURLMap = new HashMap<>();
2413                         try {
2414                                 while (this.isRunning()) {
2415                                         // Wait the given time
2416                                         Thread.sleep(heartbeatInterval);
2417                                         // get the list of PDPs (may have changed since last time)
2418                                         pdps.clear();
2419                                         synchronized(papEngine) {
2420                                                 try {
2421                                                         for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2422                                                                 for (OnapPDP p : g.getOnapPdps()) {
2423                                                                         pdps.add(p);
2424                                                                 }
2425                                                         }
2426                                                 } catch (PAPException e) {
2427                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2428                                                 }
2429                                         }
2430                                         // Check for shutdown
2431                                         if (this.isRunning() == false) {
2432                                                 LOGGER.info("isRunning is false, getting out of loop.");
2433                                                 break;
2434                                         }
2435                                         // try to get the summary status from each PDP
2436                                         boolean changeSeen = false;
2437                                         for (OnapPDP pdp : pdps) {
2438                                                 // Check for shutdown
2439                                                 if (this.isRunning() == false) {
2440                                                         LOGGER.info("isRunning is false, getting out of loop.");
2441                                                         break;
2442                                                 }
2443                                                 // the id of the PDP is its url (though we add a query parameter)
2444                                                 URL pdpURL = idToURLMap.get(pdp.getId());
2445                                                 if (pdpURL == null) {
2446                                                         // haven't seen this PDP before
2447                                                         String fullURLString = null;
2448                                                         try {
2449                                                                 // Check PDP ID
2450                                                                 if(CheckPDP.validateID(pdp.getId())){
2451                                                                         fullURLString = pdp.getId() + "?type=hb";
2452                                                                         pdpURL = new URL(fullURLString);
2453                                                                         idToURLMap.put(pdp.getId(), pdpURL);
2454                                                                 }
2455                                                         } catch (MalformedURLException e) {
2456                                                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2457                                                                 continue;
2458                                                         }
2459                                                 }
2460                                                 // Do a GET with type HeartBeat
2461                                                 String newStatus = "";
2462                                                 HttpURLConnection connection = null;
2463                                                 try {
2464                                                         // Open up the connection
2465                                                         if(pdpURL != null){
2466                                                                 connection = (HttpURLConnection)pdpURL.openConnection();
2467                                                                 // Setup our method and headers
2468                                                                 connection.setRequestMethod("GET");
2469                                                                 connection.setConnectTimeout(heartbeatTimeout);
2470                                                                 // Authentication
2471                                                                 String encoding = CheckPDP.getEncoding(pdp.getId());
2472                                                                 if(encoding !=null){
2473                                                                         connection.setRequestProperty("Authorization", "Basic " + encoding);
2474                                                                 }
2475                                                                 // Do the connect
2476                                                                 connection.connect();
2477                                                                 if (connection.getResponseCode() == 204) {
2478                                                                         newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2479                                                                         if (LOGGER.isDebugEnabled()) {
2480                                                                                 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2481                                                                         }
2482                                                                 } else {
2483                                                                         // anything else is an unexpected result
2484                                                                         newStatus = PDPStatus.Status.UNKNOWN.toString();
2485                                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2486                                                                 }       
2487                                                         }
2488                                                 } catch (UnknownHostException e) {
2489                                                         newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2490                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2491                                                 } catch (SocketTimeoutException e) {
2492                                                         newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2493                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2494                                                 } catch (ConnectException e) {
2495                                                         newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2496                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2497                                                 } catch (Exception e) {
2498                                                         newStatus = PDPStatus.Status.UNKNOWN.toString();
2499                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2500                                                 } finally {
2501                                                         // cleanup the connection
2502                                                         if(connection != null)
2503                                                                 connection.disconnect();
2504                                                 }
2505                                                 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2506                                                         if (LOGGER.isDebugEnabled()) {
2507                                                                 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"'  new Status='" + newStatus + "'");
2508                                                         }
2509                                                         try {
2510                                                                 setPDPSummaryStatus(pdp, newStatus);
2511                                                         } catch (PAPException e) {
2512                                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2513                                                         }
2514                                                         changeSeen = true;
2515                                                 }
2516                                         }
2517                                         // Check for shutdown
2518                                         if (this.isRunning() == false) {
2519                                                 LOGGER.info("isRunning is false, getting out of loop.");
2520                                                 break;
2521                                         }
2522                                         // if any of the PDPs changed state, tell the ACs to update
2523                                         if (changeSeen) {
2524                                                 notifyAC();
2525                                         }
2526                                 }
2527                         } catch (InterruptedException e) {
2528                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted.  Shutting down");
2529                                 this.terminate();
2530                                 Thread.currentThread().interrupt();
2531                         }
2532                 }
2533         }
2534
2535         /*
2536          * HELPER to change Group status when PDP status is changed
2537          * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2538          */
2539         private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2540                 setPDPSummaryStatus(pdp, newStatus.toString());
2541         }
2542
2543         private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2544                 synchronized(papEngine) {
2545                         StdPDPStatus status = new StdPDPStatus();
2546                         status.setStatus(PDPStatus.Status.valueOf(newStatus));
2547                         ((StdPDP)pdp).setStatus(status);
2548                         // now adjust the group
2549                         StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2550                         // if the PDP was just deleted it may transiently exist but not be in a group
2551                         if (group != null) {
2552                                 group.resetStatus();
2553                         }
2554                 }
2555         }
2556
2557         /*
2558          * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2559          * in the PDP group directories
2560          */
2561         @Override
2562         public void changed() {
2563                 // all PDPs in all groups need to be updated/sync'd
2564                 Set<OnapPDPGroup> groups;
2565                 try {
2566                         groups = papEngine.getOnapPDPGroups();
2567                 } catch (PAPException e) {
2568                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2569                         throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2570                 }
2571                 for (OnapPDPGroup group : groups) {
2572                         groupChanged(group);
2573                 }
2574         }
2575         
2576         public void changed(ONAPLoggingContext loggingContext) {
2577                 // all PDPs in all groups need to be updated/sync'd
2578                 Set<OnapPDPGroup> groups;
2579                 try {
2580                         groups = papEngine.getOnapPDPGroups();
2581                 } catch (PAPException e) {
2582                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2583                         throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2584                 }
2585                 for (OnapPDPGroup group : groups) {
2586                         groupChanged(group, loggingContext);
2587                 }
2588         }
2589         
2590         @Override
2591         public void groupChanged(OnapPDPGroup group) {
2592                 // all PDPs within one group need to be updated/sync'd
2593                 for (OnapPDP pdp : group.getOnapPdps()) {
2594                         pdpChanged(pdp);
2595                 }
2596         }
2597
2598         public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
2599                 // all PDPs within one group need to be updated/sync'd
2600                 for (OnapPDP pdp : group.getOnapPdps()) {
2601                         pdpChanged(pdp, loggingContext);
2602                 }
2603         }
2604
2605         @Override
2606          public void pdpChanged(OnapPDP pdp) {
2607                 // kick off a thread to do an event notification for each PDP.
2608                 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2609                 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2610                 Thread t = new Thread(new UpdatePDPThread(pdp));
2611                 if(CheckPDP.validateID(pdp.getId())){
2612                         t.start();
2613                 }
2614         }
2615         
2616          public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2617                 // kick off a thread to do an event notification for each PDP.
2618                 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2619                 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2620                 Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
2621                 if(CheckPDP.validateID(pdp.getId())){
2622                         t.start();
2623                 }
2624         }
2625
2626         private class UpdatePDPThread implements Runnable {
2627                 private OnapPDP pdp;
2628                 private String requestId;
2629                 private ONAPLoggingContext loggingContext;
2630
2631                 public UpdatePDPThread(OnapPDP pdp) {
2632                         this.pdp = pdp;
2633                 }
2634
2635                 public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2636                         this.pdp = pdp;
2637                         if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
2638                                         this.requestId = loggingContext.getRequestID();
2639                         }
2640                         this.loggingContext = loggingContext;
2641                 }
2642
2643                 public void run() {
2644                         // send the current configuration to one PDP
2645                         HttpURLConnection connection = null;
2646                         // get a new logging context for the thread
2647                         try {
2648                                 if (this.loggingContext == null) {
2649                                      loggingContext = new ONAPLoggingContext(baseLoggingContext);
2650                                 } 
2651                         } catch (Exception e) {
2652                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2653                             // Since this is a server-side error, it probably does not reflect a problem on the client,
2654                             // so do not change the PDP status.
2655                             return;
2656                 }
2657                         try {
2658                                 loggingContext.setServiceName("PAP:PDP.putConfig");
2659                                 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2660                                 if ((requestId == null) || (requestId == "")) {
2661                                         UUID requestID = UUID.randomUUID();
2662                                         loggingContext.setRequestID(requestID.toString());
2663                                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one:  " + loggingContext.getRequestID());
2664                                 } else {
2665                                         loggingContext.setRequestID(requestId);
2666                                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread):  " + loggingContext.getRequestID());
2667                                 }
2668                                 loggingContext.transactionStarted();
2669                                 // the Id of the PDP is its URL
2670                                 if (LOGGER.isDebugEnabled()) {
2671                                         LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2672                                 }
2673                                 //TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
2674                                 //TODO          (need to change "cache=", implying getting some input saying which to change)
2675                                 URL url = new URL(pdp.getId() + "?cache=all");
2676                                 // Open up the connection
2677                                 connection = (HttpURLConnection)url.openConnection();
2678                                 // Setup our method and headers
2679                                 connection.setRequestMethod("PUT");
2680                                 // Authentication
2681                                 String encoding = CheckPDP.getEncoding(pdp.getId());
2682                                 if(encoding !=null){
2683                                         connection.setRequestProperty("Authorization", "Basic " + encoding);
2684                                 }
2685                                 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2686                                 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2687                                 connection.setInstanceFollowRedirects(true);
2688                                 connection.setDoOutput(true);
2689                                 try (OutputStream os = connection.getOutputStream()) {
2690                                         OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2691                                         // if the PDP was just deleted, there is no group, but we want to send an update anyway
2692                                         if (group == null) {
2693                                                 // create blank properties files
2694                                                 Properties policyProperties = new Properties();
2695                                                 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2696                                                 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2697                                                 policyProperties.store(os, "");
2698                                                 Properties pipProps = new Properties();
2699                                                 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2700                                                 pipProps.store(os, "");
2701                                         } else {
2702                                                 // send properties from the current group
2703                                                 group.getPolicyProperties().store(os, "");
2704                                                 Properties policyLocations = new Properties();
2705                                                 for (PDPPolicy policy : group.getPolicies()) {
2706                                                         policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2707                                                 }
2708                                                 policyLocations.store(os, "");
2709                                                 group.getPipConfigProperties().store(os, "");
2710                                         }
2711                                 } catch (Exception e) {
2712                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2713                                         // Since this is a server-side error, it probably does not reflect a problem on the client,
2714                                         // so do not change the PDP status.
2715                                         return;
2716                                 }
2717                                 // Do the connect
2718                                 loggingContext.metricStarted();
2719                                 connection.connect();
2720                                 loggingContext.metricEnded();
2721                                 PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
2722                                 if (connection.getResponseCode() == 204) {
2723                                         LOGGER.info("Success. We are configured correctly.");
2724                                         loggingContext.transactionEnded();
2725                                         auditLogger.info("Success. PDP is configured correctly.");
2726                                         PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2727                                         setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2728                                 } else if (connection.getResponseCode() == 200) {
2729                                         LOGGER.info("Success. PDP needs to update its configuration.");
2730                                         loggingContext.transactionEnded();
2731                                         auditLogger.info("Success. PDP needs to update its configuration.");
2732                                         PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2733                                         setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2734                                 } else {
2735                                         LOGGER.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2736                                         loggingContext.transactionEnded();
2737                                         auditLogger.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2738                                         PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2739                                         setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2740                                 }
2741                         } catch (Exception e) {
2742                                 LOGGER.debug(e);
2743                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2744                                 loggingContext.transactionEnded();
2745                                 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2746                                 try {
2747                                         setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2748                                 } catch (PAPException e1) {
2749                                         LOGGER.debug(e1);
2750                                         PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2751                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2752                                 }
2753                         } finally {
2754                                 // cleanup the connection
2755                                 if(connection != null){
2756                                         connection.disconnect();        
2757                                 }
2758                                 // tell the AC to update it's status info
2759                                 notifyAC();
2760                         }
2761                 }
2762         }
2763
2764         /*
2765          * RESTful Interface from PAP to ACs notifying them of changes
2766          */
2767         private void notifyAC() {
2768                 // kick off a thread to do one event notification for all registered ACs
2769                 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2770                 // as part of processing this message on their end.
2771                 Thread t = new Thread(new NotifyACThread());
2772                 t.start();
2773         }
2774
2775         private class NotifyACThread implements Runnable {
2776                 public void run() {
2777                         List<String> disconnectedACs = new ArrayList<>();
2778                         // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2779                         // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2780                         for (String acURL : adminConsoleURLStringList) {
2781                                 HttpURLConnection connection = null;
2782                                 try {
2783                                         acURL += "?PAPNotification=true";
2784                                         //TODO - Currently we just tell AC that "Something changed" without being specific.  Do we want to tell it which group/pdp changed?
2785                                         //TODO - If so, put correct parameters into the Query string here
2786                                         acURL += "&objectType=all" + "&action=update";
2787                                         if (LOGGER.isDebugEnabled()) {
2788                                                 LOGGER.debug("creating url for id '" + acURL + "'");
2789                                         }
2790                                         //TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
2791                                         //TODO          (need to change "cache=", implying getting some input saying which to change)
2792                                         URL url = new URL(acURL );
2793                                         // Open up the connection
2794                                         connection = (HttpURLConnection)url.openConnection();
2795                                         // Setup our method and headers
2796                                         connection.setRequestMethod("PUT");
2797                                         connection.setRequestProperty("Content-Type", "text/x-java-properties");
2798                                         // Adding this in. It seems the HttpUrlConnection class does NOT
2799                                         // properly forward our headers for POST re-direction. It does so
2800                                         // for a GET re-direction.
2801                                         // So we need to handle this ourselves.
2802                                         //TODO - is this needed for a PUT?  seems better to leave in for now?
2803                                         connection.setInstanceFollowRedirects(false);
2804                                         // Do not include any data in the PUT because this is just a
2805                                         // notification to the AC.
2806                                         // The AC will use GETs back to the PAP to get what it needs
2807                                         // to fill in the screens.
2808                                         // Do the connect
2809                                         connection.connect();
2810                                         if (connection.getResponseCode() == 204) {
2811                                                 LOGGER.info("Success. We updated correctly.");
2812                                         } else {
2813                                                 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2814                                         }
2815
2816                                 } catch (Exception e) {
2817                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2818                                         disconnectedACs.add(acURL);
2819                                 } finally {
2820                                         // cleanup the connection
2821                                         if(connection != null)
2822                                                 connection.disconnect();
2823                                 }
2824                         }
2825                         // remove any ACs that are no longer connected
2826                         if (!disconnectedACs.isEmpty()) {
2827                                 adminConsoleURLStringList.removeAll(disconnectedACs);
2828                         }
2829                 }
2830         }
2831
2832         private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2833                 LOGGER.info("Test request received");
2834                 try {
2835                         im.evaluateSanity();
2836                         //If we make it this far, all is well
2837                         String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2838                         LOGGER.info(message);
2839                         loggingContext.transactionEnded();
2840                         PolicyLogger.audit("Transaction Failed - See Error.log");
2841                         response.setStatus(HttpServletResponse.SC_OK);
2842                         return;
2843                 }catch (ForwardProgressException e){
2844                     String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
2845                             + " Exception Message: " + e.getMessage();
2846                     logMessage(e, message, loggingContext, response);
2847                     return;
2848                 }catch (AdministrativeStateException e){
2849                     String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED."
2850                             + " Exception Message: " + e.getMessage();
2851                     logMessage(e, message, loggingContext, response);
2852                     return;
2853                 }catch (StandbyStatusException e){
2854                     String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE."
2855                             + " Exception Message: " + e.getMessage();
2856                     logMessage(e, message, loggingContext, response);
2857                     return;
2858                 }catch (Exception e) {
2859                         //A subsystem is not making progress, is locked, standby or is not responding
2860                         String eMsg = e.getMessage();
2861                         if(eMsg == null){
2862                                 eMsg = "No Exception Message";
2863                         }
2864                         String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2865                                         + " Exception Message: " + eMsg;
2866                         LOGGER.info(message, e);
2867                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2868                         loggingContext.transactionEnded();
2869                         PolicyLogger.audit("Transaction Failed - See Error.log");
2870                         //Get the specific list of subsystems that failed
2871                         String ssFailureList = null;
2872                         for(String failedSS : papDependencyGroupsFlatArray){
2873                                 if(eMsg.contains(failedSS)){
2874                                         if(ssFailureList == null){
2875                                                 ssFailureList = failedSS;
2876                                         }else{
2877                                                 ssFailureList = ssFailureList.concat(","+failedSS);
2878                                         }
2879                                 }
2880                         }
2881                         if(ssFailureList == null){
2882                                 ssFailureList = "UnknownSubSystem";
2883                         }
2884                         response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2885                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2886                         return;
2887                 }
2888         }
2889
2890         /*
2891          * Authorizing the PEP Requests. 
2892          */
2893         private boolean authorizeRequest(HttpServletRequest request) { 
2894                 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2895                 // Check if the Client is Authorized. 
2896                 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2897                         return true;
2898                 }else{
2899                         return false;
2900                 }
2901         }
2902
2903         private static void loadWebapps() throws PAPException{
2904                 if(actionHome == null || configHome == null){
2905                         Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2906                         //Sanity Check
2907                         if (webappsPath == null) {
2908                                 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2909                                 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2910                         }
2911                         Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2912                         Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2913                         if (Files.notExists(webappsPathConfig)) {
2914                                 try {
2915                                         Files.createDirectories(webappsPathConfig);
2916                                 } catch (IOException e) {
2917                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2918                                                         + webappsPathConfig.toAbsolutePath().toString());
2919                                 }
2920                         }
2921                         if (Files.notExists(webappsPathAction)) {
2922                                 try {
2923                                         Files.createDirectories(webappsPathAction);
2924                                 } catch (IOException e) {
2925                                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2926                                                         + webappsPathAction.toAbsolutePath().toString(), e);
2927                                 }
2928                         }
2929                         actionHome = webappsPathAction.toString();
2930                         configHome = webappsPathConfig.toString();
2931                 }
2932         }
2933
2934         public static String getConfigHome(){
2935                 try {
2936                         loadWebapps();
2937                 } catch (PAPException e) {
2938                         LOGGER.debug(e);
2939                         return null;
2940                 }
2941                 return configHome;
2942         }
2943         
2944         private static void setConfigHome(){
2945             configHome = getConfigHome();
2946         }
2947
2948         public static String getActionHome(){
2949                 try {
2950                         loadWebapps();
2951                 } catch (PAPException e) {
2952                         LOGGER.debug(e);
2953                         return null;
2954                 }
2955                 return actionHome;
2956         }
2957         
2958         private static void setActionHome(){
2959             actionHome = getActionHome();
2960         }
2961
2962         public static EntityManagerFactory getEmf() {
2963                 return emf;
2964         }
2965         
2966         public IntegrityAudit getIa() {
2967                 return ia;
2968         }
2969         
2970         public static String getPDPFile(){
2971                 return XACMLPapServlet.pdpFile;
2972         }
2973         
2974         public static String getPersistenceUnit(){
2975                 return PERSISTENCE_UNIT;
2976         }
2977         
2978         public static PAPPolicyEngine getPAPEngine(){
2979                 return papEngine;
2980         }
2981         
2982         public static PolicyDBDaoTransaction getDbDaoTransaction(){
2983                 return policyDBDao.getNewTransaction();
2984         }
2985         public static String getPapDbDriver() {
2986                 return papDbDriver;
2987         }
2988
2989         public static void setPapDbDriver(String papDbDriver) {
2990                 XACMLPapServlet.papDbDriver = papDbDriver;
2991         }
2992
2993         public static String getPapDbUrl() {
2994                 return papDbUrl;
2995         }
2996
2997         public static void setPapDbUrl(String papDbUrl) {
2998                 XACMLPapServlet.papDbUrl = papDbUrl;
2999         }
3000
3001         public static String getPapDbUser() {
3002                 return papDbUser;
3003         }
3004
3005         public static void setPapDbUser(String papDbUser) {
3006                 XACMLPapServlet.papDbUser = papDbUser;
3007         }
3008
3009         public static String getPapDbPassword() {
3010                 return papDbPassword;
3011         }
3012
3013         public static void setPapDbPassword(String papDbPassword) {
3014                 XACMLPapServlet.papDbPassword = papDbPassword;
3015         }
3016
3017         public static String getMsOnapName() {
3018                 return msOnapName;
3019         }
3020
3021         public static void setMsOnapName(String msOnapName) {
3022                 XACMLPapServlet.msOnapName = msOnapName;
3023         }
3024
3025         public static String getMsPolicyName() {
3026                 return msPolicyName;
3027         }
3028
3029         public static void setMsPolicyName(String msPolicyName) {
3030                 XACMLPapServlet.msPolicyName = msPolicyName;
3031         }
3032         
3033         private void logMessage(Exception e, String message, ONAPLoggingContext loggingContext, HttpServletResponse response) {
3034             LOGGER.info(message, e);
3035             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
3036             loggingContext.transactionEnded();
3037             PolicyLogger.audit("Transaction Failed - See Error.log");
3038             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
3039         }
3040 }