Fix vulnerabilities and bugs 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                 try {
796                         loggingContext.metricStarted();
797                         XACMLRest.dumpRequest(request);
798                         loggingContext.metricEnded();
799                         PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
800                         String pathInfo = request.getRequestURI();
801                         LOGGER.info("path info: " + pathInfo);
802                         if (pathInfo != null){
803                                 //DO NOT do a im.startTransaction for the test request
804                                 if (pathInfo.equals("/pap/test")) {
805                                         try {
806                                                 testService(loggingContext, response);
807                                         } catch (IOException e) {
808                                                 LOGGER.debug(e);
809                                         }
810                                         return;
811                                 }
812                         }
813                         //This im.startTransaction() covers all other Get transactions
814                         try {
815                                 loggingContext.metricStarted();
816                                 im.startTransaction();
817                                 loggingContext.metricEnded();
818                                 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
819                         } catch (AdministrativeStateException ae){
820                                 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
821                                                 + " state of " + im.getStateManager().getAdminState()
822                                                 + "\n Exception Message: " + ae.getMessage();
823                                 LOGGER.info(message, ae);
824                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
825                                 loggingContext.transactionEnded();
826                                 PolicyLogger.audit("Transaction Failed - See Error.log");
827                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
828                                 return;
829                         }catch (StandbyStatusException se) {
830                                 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
831                                                 + " of " + im.getStateManager().getStandbyStatus()
832                                                 + "\n Exception Message: " + se.getMessage();
833                                 LOGGER.info(message, se);
834                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
835                                 loggingContext.transactionEnded();
836                                 PolicyLogger.audit("Transaction Failed - See Error.log");
837                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
838                                 return;
839                         } catch (IntegrityMonitorException e) {
840                                 String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
841                                                 + "\n Exception Message: " + e.getMessage();
842                                 LOGGER.info(message, e);
843                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
844                                 loggingContext.transactionEnded();
845                                 PolicyLogger.audit("Transaction Failed - See Error.log");
846                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
847                                 return;
848                         }
849                         // Request from the API to get the gitPath
850                         String apiflag = request.getParameter("apiflag");
851                         if (apiflag!=null) {
852                                 if(authorizeRequest(request)){
853                                         APIRequestHandler apiRequestHandler = new APIRequestHandler();
854                                         try{                            
855                                                 loggingContext.metricStarted();
856                                             apiRequestHandler.doGet(request,response, apiflag);
857                                                 loggingContext.metricEnded();
858                                                 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
859                                         }catch(IOException e){
860                                             LOGGER.error(e);
861                                         }
862                                         loggingContext.transactionEnded();
863                                         PolicyLogger.audit("Transaction Ended Successfully");
864                                         im.endTransaction();
865                                         return;
866                                 } else {
867                                         String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
868                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
869                                         loggingContext.transactionEnded();
870                                         PolicyLogger.audit("Transaction Failed - See Error.log");
871                                         setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
872                                         im.endTransaction();
873                                         return;
874                                 }
875                         }
876                         // Is this from the Admin Console?
877                         String groupId = request.getParameter("groupId");
878                         if (groupId != null) {
879                                 // this is from the Admin Console, so handle separately
880                                 try{
881                                         loggingContext.metricStarted();
882                                     doACGet(request, response, groupId, loggingContext);
883                                         loggingContext.metricEnded();
884                                         PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
885                                 } catch(IOException e){
886                     LOGGER.error(e);
887                 }
888                                 loggingContext.transactionEnded();
889                                 PolicyLogger.audit("Transaction Ended Successfully");
890                                 im.endTransaction();
891                                 return;
892                         }
893                         // Get the PDP's ID
894                         String id = this.getPDPID(request);
895                         LOGGER.info("doGet from: " + id);
896                         // Get the PDP Object
897                         OnapPDP pdp = null;
898                         try{
899                             pdp = XACMLPapServlet.papEngine.getPDP(id);
900                         }catch(PAPException e){
901                             LOGGER.error(e);
902                         }
903                         // Is it known?
904                         if (pdp == null) {
905                                 // Check if request came from localhost
906                                 if (request.getRemoteHost().equals("localhost") ||
907                                                 request.getRemoteHost().equals(request.getLocalAddr())) {
908                                         // Return status information - basically all the groups
909                                         loggingContext.setServiceName("PAP.getGroups");
910                                         Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
911                                         // convert response object to JSON and include in the response
912                                         mapperWriteValue(new ObjectMapper(), response,  groups);
913                                         response.setHeader("content-type", "application/json");
914                                         response.setStatus(HttpServletResponse.SC_OK);
915                                         loggingContext.transactionEnded();
916                                         PolicyLogger.audit("Transaction Ended Successfully");
917                                         im.endTransaction();
918                                         return;
919                                 }
920                                 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
921                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
922                                 loggingContext.transactionEnded();
923                                 PolicyLogger.audit("Transaction Failed - See Error.log");
924                                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
925                                 im.endTransaction();
926                                 return;
927                         }
928                         loggingContext.setServiceName("PAP.getPolicy");
929                         // Get the PDP's Group
930                         OnapPDPGroup group = null;
931                         try {
932                             group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
933                         } catch (PAPException e) {
934                             LOGGER.error(e);
935                         }
936                         if (group == null) {
937                                 String message = "No group associated with pdp " + pdp.getId();
938                                 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
939                                 loggingContext.transactionEnded();
940                                 PolicyLogger.audit("Transaction Failed - See Error.log");
941                                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
942                                 im.endTransaction();
943                                 return;
944                         }
945                         // Which policy do they want?
946                         String policyId = request.getParameter("id");
947                         if (policyId == null) {
948                                 String message = "Did not specify an id for the policy";
949                                 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
950                                 loggingContext.transactionEnded();
951                                 PolicyLogger.audit("Transaction Failed - See Error.log");
952                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
953                                 im.endTransaction();
954                                 return;
955                         }
956                         PDPPolicy policy = group.getPolicy(policyId);
957                         if (policy == null) {
958                                 String message = "Unknown policy: " + policyId;
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                         try{
967                     LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
968                             + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
969                         } catch (PAPException| IOException e){
970                             LOGGER.error(e);
971                         }
972                         try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
973                                 // Send the policy back
974                                 IOUtils.copy(is, os);
975                                 response.setStatus(HttpServletResponse.SC_OK);
976                                 loggingContext.transactionEnded();
977                                 auditLogger.info("Success");
978                                 PolicyLogger.audit("Transaction Ended Successfully");
979                         } catch (IOException e) {
980                                 String message = "Failed to open policy id " + policyId;
981                                 LOGGER.debug(e);
982                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
983                                 loggingContext.transactionEnded();
984                                 PolicyLogger.audit("Transaction Failed - See Error.log");
985                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
986                         }
987                 }  catch (PAPException e) {
988                         LOGGER.debug(e);
989                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
990                         loggingContext.transactionEnded();
991                         PolicyLogger.audit("Transaction Failed - See Error.log");
992                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
993                         im.endTransaction();
994                         return;
995                 }
996                 loggingContext.transactionEnded();
997                 PolicyLogger.audit("Transaction Ended");
998                 im.endTransaction();
999         }
1000         
1001         /**
1002          * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
1003          */
1004         protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1005                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1006                 loggingContext.transactionStarted();
1007                 loggingContext.setServiceName("PAP.put");
1008                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1009                         UUID requestID = UUID.randomUUID();
1010                         loggingContext.setRequestID(requestID.toString());
1011                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
1012                 } else {
1013                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
1014                 }
1015                 try {
1016                         loggingContext.metricStarted();
1017                         im.startTransaction();
1018                         loggingContext.metricEnded();
1019                         PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
1020                 } catch(AdministrativeStateException e) {
1021                     String message = "PUT interface called for PAP " + papResourceName + 
1022                             " but it has an Administrative state of " + im.getStateManager().getAdminState() +
1023                             "\n Exception Message: " + e.getMessage();
1024                     logMessage(e, message, loggingContext, response);
1025                     return;
1026                 } catch(StandbyStatusException e) {
1027                     String message = "PUT interface called for PAP " + papResourceName + 
1028                             " but it has a Standby Status of " + im.getStateManager().getStandbyStatus() +
1029                             "\n Exception Message: " + e.getMessage();
1030                     logMessage(e, message, loggingContext, response);
1031                     return;
1032                 } catch (IntegrityMonitorException e) {
1033                     String message = "PUT interface called for PAP " + papResourceName +
1034                             " but an exception occurred" +
1035                             "\n Exception Message: " + e.getMessage();
1036                     logMessage(e, message, loggingContext, response);
1037                     return;
1038                 }
1039
1040                 loggingContext.metricStarted();
1041                 XACMLRest.dumpRequest(request);
1042                 loggingContext.metricEnded();
1043                 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1044                 //need to check if request is from the API or Admin console
1045                 String apiflag = request.getParameter("apiflag");
1046                 //This would occur if a PolicyDBDao notification was received
1047                 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1048                 if(policyDBDaoRequestUrl != null){
1049                         LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
1050                         String policyDBDaoRequestEntityId = request.getParameter("entityid");
1051                         String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1052                         String policyDBDaoRequestExtraData = request.getParameter("extradata");
1053                         if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1054                                 setResponseError(response,400, "entityid or entitytype not supplied");
1055                                 loggingContext.transactionEnded();
1056                                 PolicyLogger.audit("Transaction Ended Successfully");
1057                                 im.endTransaction();
1058                                 return;
1059                         }
1060                         loggingContext.metricStarted(); 
1061                         LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1062                         policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1063                         loggingContext.metricEnded();
1064                         PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1065                         response.setStatus(200);
1066                         loggingContext.transactionEnded();
1067                         PolicyLogger.audit("Transaction Ended Successfully");
1068                         im.endTransaction();
1069                         return;
1070                 }
1071                 /*
1072                  * Request for ImportService 
1073                  */
1074                 String importService = request.getParameter("importService");
1075                 if (importService != null) {
1076                         if(authorizeRequest(request)){
1077                                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1078                                 try{
1079                                         loggingContext.metricStarted(); 
1080                                     apiRequestHandler.doPut(request, response, importService);
1081                                         loggingContext.metricEnded();
1082                                         PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1083                                 }catch(IOException e){
1084                                     LOGGER.error(e);
1085                                 }
1086                                 im.endTransaction();
1087                                 return;
1088                         } else {
1089                                 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1090                                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1091                                 loggingContext.transactionEnded();
1092                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1093                                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1094                                 return;
1095                         }
1096                 }
1097                 //
1098                 // See if this is Admin Console registering itself with us
1099                 //
1100                 String acURLString = request.getParameter("adminConsoleURL");
1101                 if (acURLString != null) {
1102                         loggingContext.setServiceName("AC:PAP.register");
1103                         // remember this Admin Console for future updates
1104                         if ( ! adminConsoleURLStringList.contains(acURLString)) {
1105                                 adminConsoleURLStringList.add(acURLString);
1106                         }
1107                         if (LOGGER.isDebugEnabled()) {
1108                                 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1109                         }
1110                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1111                         loggingContext.transactionEnded();
1112                         auditLogger.info("Success");
1113                         PolicyLogger.audit("Transaction Ended Successfully");
1114                         im.endTransaction();
1115                         return;
1116                 }
1117                 /*
1118                  * This is to update the PDP Group with the policy/policies being pushed
1119                  * Part of a 2 step process to push policies to the PDP that can now be done 
1120                  * From both the Admin Console and the PolicyEngine API
1121                  */
1122                 String groupId = request.getParameter("groupId");
1123                 if (groupId != null) {
1124                         if(apiflag!=null){
1125                                 if(!authorizeRequest(request)){
1126                                         String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1127                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1128                                         loggingContext.transactionEnded();
1129                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1130                                         setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1131                                         return;
1132                                 }
1133                                 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1134                                     try{
1135                                         updateGroupsFromAPI(request, response, groupId, loggingContext);
1136                                     }catch(IOException e){
1137                                         LOGGER.error(e);
1138                                     }
1139                                         loggingContext.transactionEnded();
1140                                         PolicyLogger.audit("Transaction Ended Successfully");
1141                                         im.endTransaction();
1142                                         return;
1143                                 }
1144                         }
1145                         // this is from the Admin Console, so handle separately
1146                         try {
1147                                 loggingContext.metricEnded();
1148                             doACPut(request, response, groupId, loggingContext);
1149                                 loggingContext.metricEnded();
1150                                 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1151                         } catch (IOException e) {
1152                 LOGGER.error(e);
1153             }
1154                         loggingContext.transactionEnded();
1155                         PolicyLogger.audit("Transaction Ended Successfully");
1156                         im.endTransaction();
1157                         return;
1158                 }
1159                 //
1160                 // Request is for policy validation and creation
1161                 //
1162                 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1163                         // this request is from the Admin Console
1164                         SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1165                         try{
1166                                 loggingContext.metricStarted();
1167                             savePolicyHandler.doPolicyAPIPut(request, response);
1168                                 loggingContext.metricEnded();
1169                                 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1170                         } catch (IOException e) {
1171                 LOGGER.error(e);
1172             }
1173                         loggingContext.transactionEnded();
1174                         PolicyLogger.audit("Transaction Ended Successfully");
1175                         im.endTransaction();
1176                         return;
1177                 } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1178                         // this request is from the Policy Creation API 
1179                         if(authorizeRequest(request)){
1180                                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1181                                 try{
1182                                         loggingContext.metricStarted();
1183                                     apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1184                                         loggingContext.metricEnded();
1185                                         PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1186                     } catch (IOException e) {
1187                         LOGGER.error(e);
1188                     }
1189                                 loggingContext.transactionEnded();
1190                                 PolicyLogger.audit("Transaction Ended Successfully");
1191                                 im.endTransaction();
1192                                 return;
1193                         } else {
1194                                 String message = "PEP not Authorized for making this Request!!";
1195                                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1196                                 loggingContext.transactionEnded();
1197                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1198                                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1199                                 im.endTransaction();
1200                                 return;
1201                         }
1202                 }
1203                 // We do not expect anything from anywhere else.
1204                 // This method is here in case we ever need to support other operations.
1205                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1206                 loggingContext.transactionEnded();
1207                 PolicyLogger.audit("Transaction Failed - See Error.log");
1208                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1209                 loggingContext.transactionEnded();
1210                 PolicyLogger.audit("Transaction Failed - See error.log");
1211                 im.endTransaction();
1212         }
1213
1214         /**
1215          * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1216          */
1217         protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1218                 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1219                 loggingContext.transactionStarted();
1220                 loggingContext.setServiceName("PAP.delete");
1221                 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1222                         UUID requestID = UUID.randomUUID();
1223                         loggingContext.setRequestID(requestID.toString());
1224                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1225                 } else {
1226                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1227                 }
1228                 try {
1229                         loggingContext.metricStarted();
1230                         im.startTransaction();
1231                         loggingContext.metricEnded();
1232                         PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1233                 } catch (AdministrativeStateException ae){
1234                         String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1235                                         + " state of " + im.getStateManager().getAdminState()
1236                                         + "\n Exception Message: " + ae.getMessage();
1237                         LOGGER.info(message, ae);
1238                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1239                         loggingContext.transactionEnded();
1240                         PolicyLogger.audit("Transaction Failed - See Error.log");
1241                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1242                         return;
1243                 }catch (StandbyStatusException se) {
1244                         String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1245                                         + " of " + im.getStateManager().getStandbyStatus()
1246                                         + "\n Exception Message: " + se.getMessage();
1247                         LOGGER.info(message, se);
1248                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1249                         loggingContext.transactionEnded();
1250                         PolicyLogger.audit("Transaction Failed - See Error.log");
1251                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1252                         return;
1253                 } catch (IntegrityMonitorException e) {
1254                         String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
1255                                         + "\n Exception Message: " + e.getMessage();
1256                         LOGGER.info(message, e);
1257                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1258                         loggingContext.transactionEnded();
1259                         PolicyLogger.audit("Transaction Failed - See Error.log");
1260                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1261                         return;
1262                 }
1263                 loggingContext.metricStarted();
1264                 XACMLRest.dumpRequest(request);
1265                 loggingContext.metricEnded();
1266                 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1267                 String groupId = request.getParameter("groupId");
1268                 String apiflag = request.getParameter("apiflag");
1269                 if (groupId != null) {
1270                         // Is this from the Admin Console or API?
1271                         if(apiflag!=null) {
1272                                 if(!authorizeRequest(request)){
1273                                         String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1274                                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1275                                         loggingContext.transactionEnded();
1276                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1277                                         setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1278                                         return;
1279                                 }
1280                                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1281                                 try {
1282                                         loggingContext.metricStarted();
1283                                         apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1284                                         loggingContext.metricEnded();
1285                                         PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1286                                 } catch (Exception e) {
1287                                         LOGGER.error("Exception Occured"+e);
1288                                 }
1289                                 if(apiRequestHandler.getNewGroup()!=null){
1290                                         groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1291                                 }
1292                                 return;
1293                         }
1294                         // this is from the Admin Console, so handle separately
1295                         try{
1296                                 loggingContext.metricStarted();
1297                             doACDelete(request, response, groupId, loggingContext);
1298                                 loggingContext.metricEnded();
1299                                 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1300                         } catch (IOException e) {
1301                 LOGGER.error(e);
1302             }
1303                         loggingContext.transactionEnded();
1304                         PolicyLogger.audit("Transaction Ended Successfully");
1305                         im.endTransaction();
1306                         return;
1307                 }
1308                 //Catch anything that fell through
1309                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1310                 loggingContext.transactionEnded();
1311                 PolicyLogger.audit("Transaction Failed - See Error.log");
1312                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1313                 im.endTransaction();
1314         }
1315
1316         private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1317                 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1318                 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1319                 if (localRootPolicies == null || localReferencedPolicies == null) {
1320                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+"  ReferencedPolicies="+localReferencedPolicies);
1321                         return false;
1322                 }
1323                 // Compare the policies and pipconfig properties to the pdpProperties
1324                 try {
1325                         // the policy properties includes only xacml.rootPolicies and 
1326                         // xacml.referencedPolicies without any .url entries
1327                         Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1328                         Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1329                         if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1330                                         localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1331                                         pdpPipConfig.equals(pipconfig)) {
1332                                 // The PDP is current
1333                                 return true;
1334                         }
1335                 } catch (Exception e) {
1336                         // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1337                         // or if there are policies that do not have a corresponding ".url" property.
1338                         // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1339                         PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1340                 }
1341                 return false;
1342         }
1343
1344         private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1345                 String lists[] = new String[2];
1346                 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1347                 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1348                 for (String list : lists) {
1349                         if (list != null && list.isEmpty() == false) {
1350                                 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1351                                         String url = urlPath + "?id=" + id;
1352                                         LOGGER.info("Policy URL for " + id + ": " + url);
1353                                         policies.setProperty(id + ".url", url);
1354                                 }
1355                         }
1356                 }
1357         }
1358
1359         protected String getPDPID(HttpServletRequest request) {
1360                 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1361                 if (pdpURL == null || pdpURL.isEmpty()) {
1362                         // Should send back its port for identification
1363                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1364                         pdpURL = "";
1365                 }
1366                 return pdpURL;
1367         }
1368
1369         protected String getPDPJMX(HttpServletRequest request) {
1370                 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1371                 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1372                         // Should send back its port for identification
1373                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1374                         return null;
1375                 }
1376                 return pdpJMMX;
1377         }
1378         
1379         /**
1380          * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1381          * 
1382          * @param request
1383          * @param response
1384          * @param groupId
1385          * @param loggingContext 
1386          * @throws ServletException
1387          * @throws IOException
1388          */
1389         public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1390                 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1391                 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1392                 try {
1393                         // for PUT operations the group may or may not need to exist before the operation can be done
1394                         StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1395                         
1396                         // get the request input stream content into a String
1397                         String json = null;
1398                         java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1399                         scanner.useDelimiter("\\A");
1400                         json =  scanner.hasNext() ? scanner.next() : "";
1401                         scanner.close();
1402
1403                         PolicyLogger.info("pushPolicy request from API: " + json);
1404                         
1405                         // convert Object sent as JSON into local object
1406                         StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1407                         
1408                         //Get the current policies from the Group and Add the new one
1409                         Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1410                         currentPoliciesInGroup = group.getPolicies();
1411                         //If the selected policy is in the group we must remove the old version of it
1412                         LOGGER.info("Removing old version of the policy");
1413                         for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
1414                                 if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
1415                                         group.removePolicy(existingPolicy);
1416                                         LOGGER.info("Removing policy: " + existingPolicy);
1417                                         break;
1418                                 }
1419                         }
1420                         
1421                         // Assume that this is an update of an existing PDP Group
1422                         loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1423                         try{
1424                                 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1425                         } catch(Exception e){
1426                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1427                                                 +"group="+group.getId());
1428                                 throw new PAPException(e.getMessage()); 
1429                         }
1430                         
1431                         LOGGER.info("Calling updatGroup() with new group");
1432                         papEngine.updateGroup(group);
1433                         String policyId = "empty";
1434                         if(policy !=null && policy.getId() != null){
1435                                 policyId = policy.getId();
1436                         }
1437                         if(!policyId.matches(REGEX) ){
1438                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1439                                 response.addHeader("error",ADD_GROUP_ERROR);
1440                                 response.addHeader("message", "Policy Id is not valid");
1441                                 return;
1442                         }
1443                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1444                         response.addHeader("operation", "push");
1445                         response.addHeader("policyId", policyId);
1446                         response.addHeader("groupId", groupId);
1447                         
1448                         LOGGER.info("Group '" + group.getId() + "' updated");
1449                         
1450                         loggingContext.metricStarted();
1451                         acPutTransaction.commitTransaction();
1452                         loggingContext.metricEnded();
1453                         PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1454                         loggingContext.metricStarted();
1455                         notifyAC();
1456                         loggingContext.metricEnded();
1457                         PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1458
1459                         // Group changed, which might include changing the policies     
1460                         groupChanged(group, loggingContext);
1461                         loggingContext.transactionEnded();
1462                         LOGGER.info("Success");
1463
1464                         if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1465                                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1466                                 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1467                                         LOGGER.debug("Precheck Successful.");
1468                                 }
1469                         }
1470
1471                         PolicyLogger.audit("Transaction Ended Successfully");
1472                         return;
1473                 } catch (PAPException e) {
1474                         acPutTransaction.rollbackTransaction();
1475                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1476                         loggingContext.transactionEnded();
1477                         PolicyLogger.audit("Transaction Failed - See Error.log");
1478                         String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1479                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1480                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1481                         response.addHeader("error",ADD_GROUP_ERROR);
1482                         response.addHeader("message", message);
1483                         return;
1484                 }
1485         }
1486
1487         /**
1488          * Requests from the Admin Console for operations not on single specific objects
1489          * 
1490          * @param request
1491          * @param response
1492          * @param groupId
1493          * @param loggingContext
1494          * @throws ServletException
1495          * @throws IOException
1496          */
1497         private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1498                 PolicyDBDaoTransaction doACPostTransaction = null;
1499                 try {
1500                         String groupName = request.getParameter("groupName");
1501                         String groupDescription = request.getParameter("groupDescription");
1502                         String apiflag = request.getParameter("apiflag");
1503                         if (groupName != null && groupDescription != null) {
1504                                 // Args:              group=<groupId> groupName=<name> groupDescription=<description>            <= create a new group
1505                                 loggingContext.setServiceName("AC:PAP.createGroup");
1506                                 String unescapedName = null;
1507                                 String unescapedDescription = null;
1508                                 try{
1509                                     unescapedName = URLDecoder.decode(groupName, "UTF-8");
1510                                     unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1511                                 } catch (UnsupportedEncodingException e) {
1512                                     LOGGER.error(e);
1513                                 }
1514                                 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1515                                 try {                                   
1516                                         newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1517                                         papEngine.newGroup(unescapedName, unescapedDescription);
1518                                         loggingContext.metricStarted();
1519                                         newGroupTransaction.commitTransaction();
1520                                         loggingContext.metricEnded();
1521                                         PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1522                                 } catch (Exception e) {
1523                                         newGroupTransaction.rollbackTransaction();
1524                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1525                                         loggingContext.transactionEnded();
1526                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1527                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1528                                         return;
1529                                 }
1530                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1531                                 if (LOGGER.isDebugEnabled()) {
1532                                         LOGGER.debug("New Group '" + groupId + "' created");
1533                                 }
1534                                 // tell the Admin Consoles there is a change
1535                                 loggingContext.metricStarted();
1536                                 notifyAC();
1537                                 loggingContext.metricEnded();
1538                                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1539                                 // new group by definition has no PDPs, so no need to notify them of changes
1540                                 loggingContext.transactionEnded();
1541                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1542                                 auditLogger.info("Success");
1543                                 PolicyLogger.audit("Transaction Ended Successfully");
1544                                 return;
1545                         }
1546                         // for all remaining POST operations the group must exist before the operation can be done
1547                         OnapPDPGroup group = null;
1548                         try{
1549                             group = papEngine.getGroup(groupId);
1550                         } catch (PAPException e){
1551                             LOGGER.error(e);
1552                         }
1553                         if (group == null) {
1554                                 String message = "Unknown groupId '" + groupId + "'";
1555                                 //for fixing Header Manipulation of Fortify issue
1556                                 if(!message.matches(REGEX)){
1557                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1558                                         response.addHeader("error",ADD_GROUP_ERROR);
1559                                         response.addHeader("message", "GroupId Id is not valid");
1560                                         return;
1561                                 }
1562                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1563                                 loggingContext.transactionEnded();
1564                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1565                                 if (apiflag!=null){
1566                                         response.addHeader("error", "unknownGroupId");
1567                                         response.addHeader("operation", "push");
1568                                         response.addHeader("message", message);
1569                                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1570                                 } else {
1571                                         setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1572                                 }
1573                                 return;
1574                         }
1575                         
1576                         // If the request contains a policyId then we know we are pushing the policy to PDP
1577                         if (request.getParameter("policyId") != null) {
1578                                 
1579                                 if(apiflag!=null){
1580                                         loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1581                                         LOGGER.info("PushPolicy Request From The API");
1582                                 } else {
1583                                         loggingContext.setServiceName("AC:PAP.postPolicy");
1584                                         LOGGER.info("PushPolicy Request From The AC");
1585                                 }
1586                                 
1587                                 String policyId = request.getParameter("policyId");
1588                                 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1589                                 StdPDPGroup updatedGroup = null;
1590                                 try {
1591                                         //Copying the policy to the file system and updating groups in database
1592                                         LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
1593                                         updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1594                                         loggingContext.metricStarted();
1595                                         addPolicyToGroupTransaction.commitTransaction();
1596                                         loggingContext.metricEnded();
1597                                         PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1598                                         LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
1599                                         
1600                                 } catch (Exception e) {
1601                                         addPolicyToGroupTransaction.rollbackTransaction();
1602                                         String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1603                                         //for fixing Header Manipulation of Fortify issue
1604                                         if(!message.matches(REGEX)){
1605                                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1606                                                 response.addHeader("error",ADD_GROUP_ERROR);
1607                                                 response.addHeader("message", "Policy Id is not valid");
1608                                                 return;
1609                                         }
1610                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1611                                         loggingContext.transactionEnded();
1612                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1613                                         if (apiflag!=null){
1614                                                 response.addHeader("error", "policyCopyError");
1615                                                 response.addHeader("message", message);
1616                                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1617                                         } else {
1618                                                 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1619                                         }
1620                                         return;
1621                                 }
1622                                 
1623                                 if(apiflag != null){
1624                                         /*
1625                                          * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
1626                                          * The GUI does this from the POLICY-SDK-APP code.
1627                                          */
1628                                         
1629                                         // Get new transaction to perform updateGroup()
1630                                         PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1631                                         try {
1632                                                 // get the request content into a String and read the inputStream into a buffer
1633                                                 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1634                                                 scanner.useDelimiter("\\A");
1635                                                 String json =  scanner.hasNext() ? scanner.next() : "";
1636                                                 scanner.close();
1637                                                 
1638                                                 // convert Object sent as JSON into local object
1639                                                 ObjectMapper mapper = new ObjectMapper();
1640                                                 Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1641                                                 StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1642                                                 
1643                                                 LOGGER.info("Request JSON Payload: " + json);
1644
1645                                                 // Assume that this is an update of an existing PDP Group
1646                                                 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1647                                                 try{
1648                                                         acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
1649                                                 } catch(Exception e){
1650                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
1651                                                                         + e);
1652                                                         throw new PAPException(e.getMessage()); 
1653                                                 }
1654                                                 
1655                                                 LOGGER.info("Calling updatGroup() with new group");
1656                                                 papEngine.updateGroup(updatedGroup);
1657                                                 
1658                                                 LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
1659                                                 
1660                                                 // Commit transaction to send notification to other PAPs
1661                                                 loggingContext.metricStarted();
1662                                                 acPutTransaction.commitTransaction();
1663                                                 loggingContext.metricEnded();
1664                                                 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1665                                                 loggingContext.metricStarted();
1666                                                 
1667                                                 notifyAC();
1668                                                 loggingContext.metricEnded();
1669                                                 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1670                                                 
1671                                                 // Group changed to send notification to PDPs, which might include changing the policies        
1672                                                 groupChanged(updatedGroup,loggingContext);
1673                                                 loggingContext.transactionEnded();
1674                                                 LOGGER.info("Success");
1675
1676                                                 if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1677                                                         PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1678                                                         if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1679                                                                 LOGGER.debug("Precheck Successful.");
1680                                                         }
1681                                                 }
1682                                                 
1683                                                 //delete temporary policy file from the bin directory
1684                                                 Files.deleteIfExists(Paths.get(policy.getId()));
1685                                                         
1686                                         } catch (Exception e) {
1687                                                 acPutTransaction.rollbackTransaction();
1688                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1689                                                 loggingContext.transactionEnded();
1690                                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1691                                                 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
1692                                                 LOGGER.error(message);
1693                                                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1694                                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1695                                                 response.addHeader("error",ADD_GROUP_ERROR);
1696                                                 response.addHeader("message", message);
1697                                                 return;
1698                                         }
1699                                 }
1700                                 
1701                                 // policy file copied ok and the Group was updated on the PDP
1702                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1703                                 response.addHeader("operation", "push");
1704                                 response.addHeader("policyId", policyId);
1705                                 response.addHeader("groupId", groupId);
1706                                 
1707                                 LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1708                                 loggingContext.transactionEnded();
1709                                 auditLogger.info("Success");
1710                                 LOGGER.info("Transaction Ended Successfully");
1711                                 
1712                                 return;
1713                         } else if (request.getParameter("default") != null) {
1714                                 // Args:       group=<groupId> default=true               <= make default
1715                                 // change the current default group to be the one identified in the request.
1716                                 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1717                                 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1718                                 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1719                                 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1720                                 try {
1721                                         setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1722                                         papEngine.setDefaultGroup(group);
1723                                         loggingContext.metricStarted();
1724                                         setDefaultGroupTransaction.commitTransaction();
1725                                         loggingContext.metricEnded();
1726                                         PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1727                                 } catch (Exception e) {
1728                                         setDefaultGroupTransaction.rollbackTransaction();
1729                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1730                                         loggingContext.transactionEnded();
1731                                         PolicyLogger.audit("Transaction Failed - See Error.log");
1732                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1733                                         return;
1734                                 }
1735                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1736                                 if (LOGGER.isDebugEnabled()) {
1737                                         LOGGER.debug("Group '" + groupId + "' set to be default");
1738                                 }
1739                                 // Notify the Admin Consoles that something changed
1740                                 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1741                                 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1742                                 loggingContext.metricStarted();
1743                                 notifyAC();
1744                                 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1745                                 loggingContext.metricEnded();
1746                                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1747                                 loggingContext.transactionEnded();
1748                                 auditLogger.info("Success");
1749                                 LOGGER.info("Transaction Ended Successfully");
1750                                 return;
1751                         } else if (request.getParameter("pdpId") != null) {
1752                                 doACPostTransaction = policyDBDao.getNewTransaction();
1753                                 // Args:       group=<groupId> pdpId=<pdpId>               <= move PDP to group
1754                                 loggingContext.setServiceName("AC:PAP.movePDP");
1755                                 String pdpId = request.getParameter("pdpId");
1756                                 OnapPDP pdp = papEngine.getPDP(pdpId);
1757                                 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1758                                 try{
1759                                         doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1760                                 }catch(Exception e){    
1761                                         doACPostTransaction.rollbackTransaction();
1762                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", 
1763                                                         " Error while moving pdp in the database: "
1764                                                                         +"pdp="+pdp.getId()+",to group="+group.getId());
1765                                         throw new PAPException(e.getMessage());
1766                                 }
1767                                 papEngine.movePDP((OnapPDP) pdp, group);
1768                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1769                                 if (LOGGER.isDebugEnabled()) {
1770                                         LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1771                                 }
1772                                 // update the status of both the original group and the new one
1773                                 ((StdPDPGroup)originalGroup).resetStatus();
1774                                 ((StdPDPGroup)group).resetStatus();
1775                                 // Notify the Admin Consoles that something changed
1776                                 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1777                                 loggingContext.metricStarted();
1778                                 notifyAC();
1779                                 loggingContext.metricEnded();
1780                                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1781                                 // Need to notify the PDP that it's config may have changed
1782                                 pdpChanged(pdp, loggingContext);
1783                                 loggingContext.metricStarted();
1784                                 doACPostTransaction.commitTransaction();
1785                                 loggingContext.metricEnded();
1786                                 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1787                                 loggingContext.transactionEnded();
1788                                 auditLogger.info("Success");
1789                                 PolicyLogger.audit("Transaction Ended Successfully");
1790                                 return;
1791                         }
1792                 } catch (PAPException e) {
1793                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1794                         loggingContext.transactionEnded();
1795                         PolicyLogger.audit("Transaction Failed - See Error.log");
1796                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1797                         return;
1798                 }
1799         }
1800
1801         /**
1802          * Requests from the Admin Console to GET info about the Groups and PDPs
1803          * 
1804          * @param request
1805          * @param response
1806          * @param groupId
1807          * @param loggingContext 
1808          * @throws ServletException
1809          * @throws IOException
1810          */
1811         private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1812                 try {
1813                         String parameterDefault = request.getParameter("default");
1814                         String pdpId = request.getParameter("pdpId");
1815                         String pdpGroup = request.getParameter("getPDPGroup");
1816                         if ("".equals(groupId)) {
1817                                 // request IS from AC but does not identify a group by name
1818                                 if (parameterDefault != null) {
1819                                         // Request is for the Default group (whatever its id)
1820                                         loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1821                                         OnapPDPGroup group = papEngine.getDefaultGroup();
1822                                         // convert response object to JSON and include in the response
1823                                         mapperWriteValue(new ObjectMapper(), response,  group);
1824                                         if (LOGGER.isDebugEnabled()) {
1825                                                 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1826                                         }
1827                                         response.setStatus(HttpServletResponse.SC_OK);
1828                                         response.setHeader("content-type", "application/json");
1829                                         try{
1830                         response.getOutputStream().close();
1831                     } catch (IOException e){
1832                         LOGGER.error(e);
1833                     }
1834                                         loggingContext.transactionEnded();
1835                                         auditLogger.info("Success");
1836                                         PolicyLogger.audit("Transaction Ended Successfully");
1837                                         return;
1838                                 } else if (pdpId != null) {
1839                                         // Request is related to a PDP
1840                                         if (pdpGroup == null) {
1841                                                 // Request is for the (unspecified) group containing a given PDP
1842                                                 loggingContext.setServiceName("AC:PAP.getPDP");
1843                                                 OnapPDP pdp = null;
1844                                                 try{
1845                                                     pdp = papEngine.getPDP(pdpId);
1846                                                 }catch(PAPException e){
1847                                                     LOGGER.error(e);
1848                                                 }
1849                                                 // convert response object to JSON and include in the response
1850                                                 mapperWriteValue(new ObjectMapper(), response,  pdp);
1851                                                 if (LOGGER.isDebugEnabled()) {
1852                                                         LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1853                                                 }
1854                                                 response.setStatus(HttpServletResponse.SC_OK);
1855                                                 response.setHeader("content-type", "application/json");
1856                                                 try{
1857                             response.getOutputStream().close();
1858                         } catch (IOException e){
1859                             LOGGER.error(e);
1860                         }
1861                                                 loggingContext.transactionEnded();
1862                                                 auditLogger.info("Success");
1863                                                 PolicyLogger.audit("Transaction Ended Successfully");
1864                                                 return;
1865                                         } else {
1866                                                 // Request is for the group containing a given PDP
1867                                                 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1868                                                 OnapPDPGroup group =null;
1869                                                 try{
1870                                                     OnapPDP pdp = papEngine.getPDP(pdpId);
1871                                 group = papEngine.getPDPGroup((OnapPDP) pdp);
1872                                                 }catch(PAPException e){
1873                                                     LOGGER.error(e);
1874                                                 }
1875                                                 // convert response object to JSON and include in the response
1876                                                 mapperWriteValue(new ObjectMapper(), response,  group);
1877                                                 if (LOGGER.isDebugEnabled()) {
1878                                                         LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1879                                                 }
1880                                                 response.setStatus(HttpServletResponse.SC_OK);
1881                                                 response.setHeader("content-type", "application/json");
1882                                                 try{
1883                                 response.getOutputStream().close();
1884                             } catch (IOException e){
1885                                 LOGGER.error(e);
1886                             }
1887                                                 loggingContext.transactionEnded();
1888                                                 auditLogger.info("Success");
1889                                                 PolicyLogger.audit("Transaction Ended Successfully");
1890                                                 return;
1891                                         }
1892                                 } else {
1893                                         // request is for top-level properties about all groups
1894                                         loggingContext.setServiceName("AC:PAP.getAllGroups");
1895                                         Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
1896                                         // convert response object to JSON and include in the response
1897                                         mapperWriteValue(new ObjectMapper(), response,  groups);
1898                                         if (LOGGER.isDebugEnabled()) {
1899                                                 LOGGER.debug("GET All groups req");
1900                                         }
1901                                         response.setStatus(HttpServletResponse.SC_OK);
1902                                         response.setHeader("content-type", "application/json");
1903                                         try{
1904                             response.getOutputStream().close();
1905                         } catch (IOException e){
1906                             LOGGER.error(e);
1907                         }
1908                                         loggingContext.transactionEnded();
1909                                         auditLogger.info("Success");
1910                                         PolicyLogger.audit("Transaction Ended Successfully");
1911                                         return;
1912                                 }
1913                         }
1914                         // for all other GET operations the group must exist before the operation can be done
1915                         OnapPDPGroup group = null;
1916                         try{
1917                             group = papEngine.getGroup(groupId);
1918                         } catch(PAPException e){
1919                             LOGGER.error(e);
1920                         }
1921                         if (group == null) {
1922                                 String message = "Unknown groupId '" + groupId + "'";
1923                                 //for fixing Header Manipulation of Fortify issue
1924                                 if(!message.matches(REGEX)){
1925                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1926                                         response.addHeader("error",ADD_GROUP_ERROR);
1927                                         response.addHeader("message", "Group Id is not valid");
1928                                         return;
1929                                 }
1930                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1931                                 loggingContext.transactionEnded();
1932                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1933                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1934                                 return;
1935                         }
1936                         // Figure out which request this is based on the parameters
1937                         String policyId = request.getParameter("policyId");
1938                         if (policyId != null) {
1939                                 // retrieve a policy
1940                                 loggingContext.setServiceName("AC:PAP.getPolicy");
1941                                 // convert response object to JSON and include in the response
1942                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1943                                 loggingContext.transactionEnded();
1944                                 PolicyLogger.audit("Transaction Failed - See Error.log");
1945                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1946                         } else {
1947                                 // No other parameters, so return the identified Group
1948                                 loggingContext.setServiceName("AC:PAP.getGroup");
1949                                 // convert response object to JSON and include in the response
1950                                 mapperWriteValue(new ObjectMapper(), response,  group);
1951                                 if (LOGGER.isDebugEnabled()) {
1952                                         LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1953                                 }
1954                                 response.setStatus(HttpServletResponse.SC_OK);
1955                                 response.setHeader("content-type", "application/json");
1956                                 try{
1957                                     response.getOutputStream().close();
1958                                 } catch (IOException e){
1959                                     LOGGER.error(e);
1960                                 }
1961                                 loggingContext.transactionEnded();
1962                                 auditLogger.info("Success");
1963                                 PolicyLogger.audit("Transaction Ended Successfully");
1964                                 return;
1965                         }
1966                         // Currently there are no other GET calls from the AC.
1967                         // 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.
1968                         // Other GETs that could be called:
1969                         //                              Specific Group  (groupId=<groupId>)
1970                         //                              A Policy                (groupId=<groupId> policyId=<policyId>)
1971                         //                              A PDP                   (groupId=<groupId> pdpId=<pdpId>)
1972                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1973                         loggingContext.transactionEnded();
1974                         PolicyLogger.audit("Transaction Failed - See Error.log");
1975                         setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1976                 } catch (PAPException e) {
1977                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1978                         loggingContext.transactionEnded();
1979                         PolicyLogger.audit("Transaction Failed - See Error.log");
1980                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1981                         return;
1982                 }
1983         }
1984         
1985         /**
1986          * Requests from the Admin Console to create new items or update existing ones
1987          * 
1988          * @param request
1989          * @param response
1990          * @param groupId
1991          * @param loggingContext 
1992          * @throws ServletException
1993          * @throws IOException
1994          */
1995         private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1996                 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1997                 try {
1998                         // for PUT operations the group may or may not need to exist before the operation can be done
1999                         OnapPDPGroup group = papEngine.getGroup(groupId);
2000                         // determine the operation needed based on the parameters in the request
2001                         // for remaining operations the group must exist before the operation can be done
2002                         if (group == null) {
2003                                 String message = "Unknown groupId '" + groupId + "'";
2004                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2005                                 loggingContext.transactionEnded();
2006                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2007                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
2008                                 return;
2009                         }
2010                         if (request.getParameter("policy") != null) {
2011                                 //        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)
2012                                 loggingContext.setServiceName("AC:PAP.putPolicy");
2013                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!!  ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
2014                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2015                                 loggingContext.transactionEnded();
2016                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2017                                 auditLogger.info("Success");
2018                                 PolicyLogger.audit("Transaction Ended Successfully");
2019                                 return;
2020                         } else if (request.getParameter("pdpId") != null) {
2021                                 // ARGS:        group=<groupId> pdpId=<pdpId/URL>          <= create a new PDP or Update an Existing one
2022                                 String pdpId = request.getParameter("pdpId");
2023                                 if (papEngine.getPDP(pdpId) == null) {
2024                                         loggingContext.setServiceName("AC:PAP.createPDP");
2025                                 } else {
2026                                         loggingContext.setServiceName("AC:PAP.updatePDP");
2027                                 }
2028                                 // get the request content into a String
2029                                 String json = null;
2030                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2031                                 try{
2032                                     Scanner scanner = new Scanner(request.getInputStream());
2033                                     scanner.useDelimiter("\\A");
2034                         json =  scanner.hasNext() ? scanner.next() : "";
2035                         scanner.close();
2036                                 }catch(IOException e){
2037                                     LOGGER.error(e);
2038                                 }
2039                                 LOGGER.info("JSON request from AC: " + json);
2040                                 // convert Object sent as JSON into local object
2041                                 ObjectMapper mapper = new ObjectMapper();
2042                                 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
2043                                 if (pdpId == null ||
2044                                                 objectFromJSON == null ||
2045                                                 ! (objectFromJSON instanceof StdPDP) ||
2046                                                 ((StdPDP)objectFromJSON).getId() == null ||
2047                                                 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
2048                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
2049                                         loggingContext.transactionEnded();
2050                                         PolicyLogger.audit("Transaction Failed - See Error.log");
2051                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
2052                                 }
2053                                 StdPDP pdp = (StdPDP) objectFromJSON;
2054                                 if(pdp != null){
2055                                     OnapPDP oPDP = null;
2056                                     try{
2057                                         oPDP = papEngine.getPDP(pdpId);
2058                                     }catch (PAPException e){
2059                                         LOGGER.error(e);
2060                                     }
2061                                         if (oPDP == null) {
2062                                                 // this is a request to create a new PDP object
2063                                                 try{
2064                                                         acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), 
2065                                                                         pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
2066                                                 } catch(Exception e){
2067                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2068                                                                         +"pdp="+ (pdp.getId()) +",to group="+group.getId());
2069                                                         throw new PAPException(e.getMessage());
2070                                                 }
2071                                                 try{
2072                                                     papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
2073                                                 }catch(PAPException e){
2074                                                     LOGGER.error(e);
2075                                                 }
2076                                         } else {
2077                                                 try{
2078                                                         acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
2079                                                 } catch(Exception e){
2080                                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
2081                                                                         +"pdp="+ pdp.getId());
2082                                                         throw new PAPException(e.getMessage());
2083                                                 }
2084                                                 // this is a request to update the pdp
2085                                                 try{
2086                                                     papEngine.updatePDP(pdp);
2087                                                 }catch(PAPException e){
2088                             LOGGER.error(e);
2089                         }
2090                                         }
2091                                         response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2092                                         if (LOGGER.isDebugEnabled()) {
2093                                                 LOGGER.debug("PDP '" + pdpId + "' created/updated");
2094                                         }
2095                                         // adjust the group's state including the new PDP
2096                                         ((StdPDPGroup)group).resetStatus();
2097                                         // tell the Admin Consoles there is a change
2098                                         loggingContext.metricStarted();
2099                                         notifyAC();
2100                                         loggingContext.metricEnded();
2101                                         PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2102                                         // this might affect the PDP, so notify it of the change
2103                                         pdpChanged(pdp, loggingContext);
2104                                         loggingContext.metricStarted();
2105                                         acPutTransaction.commitTransaction();
2106                                         loggingContext.metricEnded();
2107                                         PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2108                                         loggingContext.transactionEnded();
2109                                         auditLogger.info("Success");
2110                                         PolicyLogger.audit("Transaction Ended Successfully");
2111                                         return;
2112                                 }else{
2113                                         try{
2114                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2115                                                                 +"pdp=null" + ",to group="+group.getId());
2116                                                 throw new PAPException("PDP is null");
2117                                         } catch(Exception e){
2118                                                 throw new PAPException("PDP is null" + e.getMessage() +e);
2119                                         }
2120                                 }
2121                         } else if (request.getParameter("pipId") != null) {
2122                                 //                group=<groupId> pipId=<pipEngineId> contents=pip properties              <= add a PIP to pip config, or replace it if it already exists (lenient operation) 
2123                                 loggingContext.setServiceName("AC:PAP.putPIP");
2124                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2125                                 loggingContext.transactionEnded();
2126                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2127                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2128                                 return;
2129                         } else {
2130                                 // Assume that this is an update of an existing PDP Group
2131                                 // ARGS:        group=<groupId>         <= Update an Existing Group
2132                                 loggingContext.setServiceName("AC:PAP.updateGroup");
2133                                 // get the request content into a String
2134                                 String json = null;
2135                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2136                 try{
2137                     Scanner scanner = new Scanner(request.getInputStream());
2138                     scanner.useDelimiter("\\A");
2139                     json =  scanner.hasNext() ? scanner.next() : "";
2140                     scanner.close();
2141                 }catch(IOException e){
2142                     LOGGER.error(e);
2143                 }
2144                                 LOGGER.info("JSON request from AC: " + json);
2145                                 // convert Object sent as JSON into local object
2146                                 ObjectMapper mapper = new ObjectMapper();
2147                                 Object objectFromJSON  = mapper.readValue(json, StdPDPGroup.class);
2148                                 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
2149                                                 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
2150                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
2151                                         loggingContext.transactionEnded();
2152                                         PolicyLogger.audit("Transaction Failed - See Error.log");
2153                                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
2154                                 }
2155                                 // The Path on the PAP side is not carried on the RESTful interface with the AC
2156                                 // (because it is local to the PAP)
2157                                 // so we need to fill that in before submitting the group for update
2158                                 if(objectFromJSON != null){
2159                                         ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
2160                                 }
2161                                 try{
2162                                         if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
2163                                                 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
2164                                         } else {
2165                                                 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
2166                                         }
2167                                 } catch(Exception e){
2168                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
2169                                                         +"group="+group.getId());
2170                                         LOGGER.error(e);
2171                                         throw new PAPException(e.getMessage());
2172                                 }
2173                                 
2174                                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();  
2175                                 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;        
2176                                 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {               
2177                                         LOGGER.debug("Precheck Successful.");
2178                                 }
2179                                 try{
2180                                     papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2181                                 }catch(PAPException e){
2182                                     LOGGER.error(e);
2183                                 }
2184                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2185                                 if (LOGGER.isDebugEnabled()) {
2186                                         LOGGER.debug("Group '" + group.getId() + "' updated");
2187                                 }
2188                                 loggingContext.metricStarted();
2189                                 acPutTransaction.commitTransaction();
2190                                 loggingContext.metricEnded();
2191                                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2192                                 // tell the Admin Consoles there is a change
2193                                 loggingContext.metricStarted();
2194                                 notifyAC();
2195                                 loggingContext.metricEnded();
2196                                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2197                                 // Group changed, which might include changing the policies
2198                                 groupChanged(group, loggingContext);
2199                                 loggingContext.transactionEnded();
2200                                 auditLogger.info("Success");
2201                                 PolicyLogger.audit("Transaction Ended Successfully");
2202                                 return;
2203                         }
2204                 } catch (PAPException e) {
2205                         LOGGER.debug(e);
2206                         acPutTransaction.rollbackTransaction();
2207                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2208                         loggingContext.transactionEnded();
2209                         PolicyLogger.audit("Transaction Failed - See Error.log");
2210                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2211                         return;
2212                 } catch (IOException | JsonException e) {
2213                     LOGGER.debug(e);
2214                     acPutTransaction.rollbackTransaction();
2215                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2216                     loggingContext.transactionEnded();
2217                     PolicyLogger.audit("Transaction Failed - See Error.log");
2218                     setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2219                     return;
2220                 }
2221         }
2222         
2223         /**
2224          * Requests from the Admin Console to delete/remove items
2225          * 
2226          * @param request
2227          * @param response
2228          * @param groupId
2229          * @param loggingContext 
2230          * @throws ServletException
2231          * @throws IOException
2232          */
2233         private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2234                 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2235                 try {
2236                         // for all DELETE operations the group must exist before the operation can be done
2237                         loggingContext.setServiceName("AC:PAP.delete");
2238                         OnapPDPGroup group = papEngine.getGroup(groupId);
2239                         if (group == null) {
2240                                 String message = "Unknown groupId '" + groupId + "'";
2241                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2242                                 loggingContext.transactionEnded();
2243                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2244                                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2245                                 return;
2246                         }
2247                         // determine the operation needed based on the parameters in the request
2248                         if (request.getParameter("policy") != null) {
2249                                 //        group=<groupId> policy=<policyId>  [delete=<true|false>]       <= delete policy file from group
2250                                 loggingContext.setServiceName("AC:PAP.deletePolicy");
2251                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2252                                 loggingContext.transactionEnded();
2253                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2254                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2255                                 return;
2256                         } else if (request.getParameter("pdpId") != null) {
2257                                 // ARGS:        group=<groupId> pdpId=<pdpId>                  <= delete PDP 
2258                                 String pdpId = request.getParameter("pdpId");
2259                                 OnapPDP pdp = papEngine.getPDP(pdpId);
2260                                 try{
2261                                         removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2262                                 } catch(Exception e){
2263                                         throw new PAPException(e);
2264                                 }
2265                                 try{
2266                         papEngine.removePDP((OnapPDP) pdp);
2267                                 }catch(PAPException e){
2268                     LOGGER.error(e);
2269                 }
2270                                 // adjust the status of the group, which may have changed when we removed this PDP
2271                                 ((StdPDPGroup)group).resetStatus();
2272                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2273                                 loggingContext.metricStarted();
2274                                 notifyAC();
2275                                 loggingContext.metricEnded();
2276                                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2277                                 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2278                                 pdpChanged(pdp, loggingContext);
2279                                 loggingContext.metricStarted();
2280                                 removePdpOrGroupTransaction.commitTransaction();
2281                                 loggingContext.metricEnded();
2282                                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2283                                 loggingContext.transactionEnded();
2284                                 auditLogger.info("Success");
2285                                 PolicyLogger.audit("Transaction Ended Successfully");
2286                                 return;
2287                         } else if (request.getParameter("pipId") != null) {
2288                                 //        group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2289                                 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2290                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2291                                 loggingContext.transactionEnded();
2292                                 PolicyLogger.audit("Transaction Failed - See Error.log");
2293                                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2294                                 return;
2295                         } else {
2296                                 // ARGS:      group=<groupId> movePDPsToGroupId=<movePDPsToGroupId>            <= delete a group and move all its PDPs to the given group
2297                                 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2298                                 OnapPDPGroup moveToGroup = null;
2299                                 if (moveToGroupId != null) {
2300                                     try{
2301                                         moveToGroup = papEngine.getGroup(moveToGroupId);
2302                                     }catch(PAPException e){
2303                             LOGGER.error(e);
2304                         }
2305                                 }
2306                                 // get list of PDPs in the group being deleted so we can notify them that they got changed
2307                                 Set<OnapPDP> movedPDPs = new HashSet<>();
2308                                 movedPDPs.addAll(group.getOnapPdps());
2309                                 // do the move/remove
2310                                 try{
2311                                         removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2312                                 } catch(Exception e){
2313                                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2314                                         throw new PAPException(e.getMessage());
2315                                 }
2316                                 try{
2317                                     papEngine.removeGroup(group, moveToGroup);
2318                                 }catch(PAPException e){
2319                     LOGGER.error(e);
2320                 }
2321                                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2322                                 loggingContext.metricStarted();
2323                                 notifyAC();
2324                                 loggingContext.metricEnded();
2325                                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2326                                 // notify any PDPs in the removed set that their config may have changed
2327                                 for (OnapPDP pdp : movedPDPs) {
2328                                         pdpChanged(pdp, loggingContext);
2329                                 }
2330                                 loggingContext.metricStarted();
2331                                 removePdpOrGroupTransaction.commitTransaction();
2332                                 loggingContext.metricEnded();
2333                                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2334                                 loggingContext.transactionEnded();
2335                                 auditLogger.info("Success");
2336                                 PolicyLogger.audit("Transaction Ended Successfully");
2337                                 return;
2338                         }
2339                 } catch (PAPException e) {
2340                         removePdpOrGroupTransaction.rollbackTransaction();
2341                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2342                         loggingContext.transactionEnded();
2343                         PolicyLogger.audit("Transaction Failed - See Error.log");
2344                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2345                         return;
2346                 }
2347         }
2348         
2349         /**
2350          * Heartbeat thread - periodically check on PDPs' status
2351          * 
2352          * Heartbeat with all known PDPs.
2353          * 
2354          * Implementation note:
2355          * 
2356          * The PDPs are contacted Sequentially, not in Parallel.
2357          * 
2358          * If we did this in parallel using multiple threads we would simultaneously use
2359          *              - 1 thread and
2360          *              - 1 connection
2361          * for EACH PDP.
2362          * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2363          * when user changes occur.
2364          * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2365          * 
2366          * The Sequential operation does a heartbeat request to each PDP one at a time.
2367          * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2368          * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2369          * it could take a long time to cycle through all of the PDPs.
2370          * That means that this may not notice a PDP being down in a predictable time.
2371          */
2372         private class Heartbeat implements Runnable {
2373                 private PAPPolicyEngine papEngine;
2374                 private Set<OnapPDP> pdps = new HashSet<>();
2375                 private int heartbeatInterval;
2376                 private int heartbeatTimeout;
2377
2378                 public volatile boolean isRunning = false;
2379
2380                 public synchronized boolean isRunning() {
2381                         return this.isRunning;
2382                 }
2383
2384                 public synchronized void terminate() {
2385                         this.isRunning = false;
2386                 }
2387
2388                 public Heartbeat(PAPPolicyEngine papEngine2) {
2389                         papEngine = papEngine2;
2390                         this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2391                         this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2392                 }
2393
2394                 @Override
2395                 public void run() {
2396                         // Set ourselves as running
2397                         synchronized(this) {
2398                                 this.isRunning = true;
2399                         }
2400                         HashMap<String, URL> idToURLMap = new HashMap<>();
2401                         try {
2402                                 while (this.isRunning()) {
2403                                         // Wait the given time
2404                                         Thread.sleep(heartbeatInterval);
2405                                         // get the list of PDPs (may have changed since last time)
2406                                         pdps.clear();
2407                                         synchronized(papEngine) {
2408                                                 try {
2409                                                         for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2410                                                                 for (OnapPDP p : g.getOnapPdps()) {
2411                                                                         pdps.add(p);
2412                                                                 }
2413                                                         }
2414                                                 } catch (PAPException e) {
2415                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2416                                                 }
2417                                         }
2418                                         // Check for shutdown
2419                                         if (this.isRunning() == false) {
2420                                                 LOGGER.info("isRunning is false, getting out of loop.");
2421                                                 break;
2422                                         }
2423                                         // try to get the summary status from each PDP
2424                                         boolean changeSeen = false;
2425                                         for (OnapPDP pdp : pdps) {
2426                                                 // Check for shutdown
2427                                                 if (this.isRunning() == false) {
2428                                                         LOGGER.info("isRunning is false, getting out of loop.");
2429                                                         break;
2430                                                 }
2431                                                 // the id of the PDP is its url (though we add a query parameter)
2432                                                 URL pdpURL = idToURLMap.get(pdp.getId());
2433                                                 if (pdpURL == null) {
2434                                                         // haven't seen this PDP before
2435                                                         String fullURLString = null;
2436                                                         try {
2437                                                                 // Check PDP ID
2438                                                                 if(CheckPDP.validateID(pdp.getId())){
2439                                                                         fullURLString = pdp.getId() + "?type=hb";
2440                                                                         pdpURL = new URL(fullURLString);
2441                                                                         idToURLMap.put(pdp.getId(), pdpURL);
2442                                                                 }
2443                                                         } catch (MalformedURLException e) {
2444                                                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2445                                                                 continue;
2446                                                         }
2447                                                 }
2448                                                 // Do a GET with type HeartBeat
2449                                                 String newStatus = "";
2450                                                 HttpURLConnection connection = null;
2451                                                 try {
2452                                                         // Open up the connection
2453                                                         if(pdpURL != null){
2454                                                                 connection = (HttpURLConnection)pdpURL.openConnection();
2455                                                                 // Setup our method and headers
2456                                                                 connection.setRequestMethod("GET");
2457                                                                 connection.setConnectTimeout(heartbeatTimeout);
2458                                                                 // Authentication
2459                                                                 String encoding = CheckPDP.getEncoding(pdp.getId());
2460                                                                 if(encoding !=null){
2461                                                                         connection.setRequestProperty("Authorization", "Basic " + encoding);
2462                                                                 }
2463                                                                 // Do the connect
2464                                                                 connection.connect();
2465                                                                 if (connection.getResponseCode() == 204) {
2466                                                                         newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2467                                                                         if (LOGGER.isDebugEnabled()) {
2468                                                                                 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2469                                                                         }
2470                                                                 } else {
2471                                                                         // anything else is an unexpected result
2472                                                                         newStatus = PDPStatus.Status.UNKNOWN.toString();
2473                                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2474                                                                 }       
2475                                                         }
2476                                                 } catch (UnknownHostException e) {
2477                                                         newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2478                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2479                                                 } catch (SocketTimeoutException e) {
2480                                                         newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2481                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2482                                                 } catch (ConnectException e) {
2483                                                         newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2484                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2485                                                 } catch (Exception e) {
2486                                                         newStatus = PDPStatus.Status.UNKNOWN.toString();
2487                                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2488                                                 } finally {
2489                                                         // cleanup the connection
2490                                                         if(connection != null)
2491                                                                 connection.disconnect();
2492                                                 }
2493                                                 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2494                                                         if (LOGGER.isDebugEnabled()) {
2495                                                                 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"'  new Status='" + newStatus + "'");
2496                                                         }
2497                                                         try {
2498                                                                 setPDPSummaryStatus(pdp, newStatus);
2499                                                         } catch (PAPException e) {
2500                                                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2501                                                         }
2502                                                         changeSeen = true;
2503                                                 }
2504                                         }
2505                                         // Check for shutdown
2506                                         if (this.isRunning() == false) {
2507                                                 LOGGER.info("isRunning is false, getting out of loop.");
2508                                                 break;
2509                                         }
2510                                         // if any of the PDPs changed state, tell the ACs to update
2511                                         if (changeSeen) {
2512                                                 notifyAC();
2513                                         }
2514                                 }
2515                         } catch (InterruptedException e) {
2516                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted.  Shutting down");
2517                                 this.terminate();
2518                                 Thread.currentThread().interrupt();
2519                         }
2520                 }
2521         }
2522
2523         /*
2524          * HELPER to change Group status when PDP status is changed
2525          * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2526          */
2527         private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2528                 setPDPSummaryStatus(pdp, newStatus.toString());
2529         }
2530
2531         private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2532                 synchronized(papEngine) {
2533                         StdPDPStatus status = new StdPDPStatus();
2534                         status.setStatus(PDPStatus.Status.valueOf(newStatus));
2535                         ((StdPDP)pdp).setStatus(status);
2536                         // now adjust the group
2537                         StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2538                         // if the PDP was just deleted it may transiently exist but not be in a group
2539                         if (group != null) {
2540                                 group.resetStatus();
2541                         }
2542                 }
2543         }
2544
2545         /*
2546          * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2547          * in the PDP group directories
2548          */
2549         @Override
2550         public void changed() {
2551                 // all PDPs in all groups need to be updated/sync'd
2552                 Set<OnapPDPGroup> groups;
2553                 try {
2554                         groups = papEngine.getOnapPDPGroups();
2555                 } catch (PAPException e) {
2556                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2557                         throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2558                 }
2559                 for (OnapPDPGroup group : groups) {
2560                         groupChanged(group);
2561                 }
2562         }
2563         
2564         public void changed(ONAPLoggingContext loggingContext) {
2565                 // all PDPs in all groups need to be updated/sync'd
2566                 Set<OnapPDPGroup> groups;
2567                 try {
2568                         groups = papEngine.getOnapPDPGroups();
2569                 } catch (PAPException e) {
2570                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2571                         throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2572                 }
2573                 for (OnapPDPGroup group : groups) {
2574                         groupChanged(group, loggingContext);
2575                 }
2576         }
2577         
2578         @Override
2579         public void groupChanged(OnapPDPGroup group) {
2580                 // all PDPs within one group need to be updated/sync'd
2581                 for (OnapPDP pdp : group.getOnapPdps()) {
2582                         pdpChanged(pdp);
2583                 }
2584         }
2585
2586         public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
2587                 // all PDPs within one group need to be updated/sync'd
2588                 for (OnapPDP pdp : group.getOnapPdps()) {
2589                         pdpChanged(pdp, loggingContext);
2590                 }
2591         }
2592
2593         @Override
2594          public void pdpChanged(OnapPDP pdp) {
2595                 // kick off a thread to do an event notification for each PDP.
2596                 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2597                 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2598                 Thread t = new Thread(new UpdatePDPThread(pdp));
2599                 if(CheckPDP.validateID(pdp.getId())){
2600                         t.start();
2601                 }
2602         }
2603         
2604          public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2605                 // kick off a thread to do an event notification for each PDP.
2606                 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2607                 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2608                 Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
2609                 if(CheckPDP.validateID(pdp.getId())){
2610                         t.start();
2611                 }
2612         }
2613
2614         private class UpdatePDPThread implements Runnable {
2615                 private OnapPDP pdp;
2616                 private String requestId;
2617                 private ONAPLoggingContext loggingContext;
2618
2619                 public UpdatePDPThread(OnapPDP pdp) {
2620                         this.pdp = pdp;
2621                 }
2622
2623                 public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2624                         this.pdp = pdp;
2625                         if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
2626                                         this.requestId = loggingContext.getRequestID();
2627                         }
2628                         this.loggingContext = loggingContext;
2629                 }
2630
2631                 public void run() {
2632                         // send the current configuration to one PDP
2633                         HttpURLConnection connection = null;
2634                         // get a new logging context for the thread
2635                         try {
2636                                 if (this.loggingContext == null) {
2637                                      loggingContext = new ONAPLoggingContext(baseLoggingContext);
2638                                 } 
2639                         } catch (Exception e) {
2640                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2641                             // Since this is a server-side error, it probably does not reflect a problem on the client,
2642                             // so do not change the PDP status.
2643                             return;
2644                 }
2645                         try {
2646                                 loggingContext.setServiceName("PAP:PDP.putConfig");
2647                                 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2648                                 if ((requestId == null) || (requestId == "")) {
2649                                         UUID requestID = UUID.randomUUID();
2650                                         loggingContext.setRequestID(requestID.toString());
2651                                         PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one:  " + loggingContext.getRequestID());
2652                                 } else {
2653                                         loggingContext.setRequestID(requestId);
2654                                         PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread):  " + loggingContext.getRequestID());
2655                                 }
2656                                 loggingContext.transactionStarted();
2657                                 // the Id of the PDP is its URL
2658                                 if (LOGGER.isDebugEnabled()) {
2659                                         LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2660                                 }
2661                                 //TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
2662                                 //TODO          (need to change "cache=", implying getting some input saying which to change)
2663                                 URL url = new URL(pdp.getId() + "?cache=all");
2664                                 // Open up the connection
2665                                 connection = (HttpURLConnection)url.openConnection();
2666                                 // Setup our method and headers
2667                                 connection.setRequestMethod("PUT");
2668                                 // Authentication
2669                                 String encoding = CheckPDP.getEncoding(pdp.getId());
2670                                 if(encoding !=null){
2671                                         connection.setRequestProperty("Authorization", "Basic " + encoding);
2672                                 }
2673                                 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2674                                 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2675                                 connection.setInstanceFollowRedirects(true);
2676                                 connection.setDoOutput(true);
2677                                 try (OutputStream os = connection.getOutputStream()) {
2678                                         OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2679                                         // if the PDP was just deleted, there is no group, but we want to send an update anyway
2680                                         if (group == null) {
2681                                                 // create blank properties files
2682                                                 Properties policyProperties = new Properties();
2683                                                 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2684                                                 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2685                                                 policyProperties.store(os, "");
2686                                                 Properties pipProps = new Properties();
2687                                                 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2688                                                 pipProps.store(os, "");
2689                                         } else {
2690                                                 // send properties from the current group
2691                                                 group.getPolicyProperties().store(os, "");
2692                                                 Properties policyLocations = new Properties();
2693                                                 for (PDPPolicy policy : group.getPolicies()) {
2694                                                         policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2695                                                 }
2696                                                 policyLocations.store(os, "");
2697                                                 group.getPipConfigProperties().store(os, "");
2698                                         }
2699                                 } catch (Exception e) {
2700                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2701                                         // Since this is a server-side error, it probably does not reflect a problem on the client,
2702                                         // so do not change the PDP status.
2703                                         return;
2704                                 }
2705                                 // Do the connect
2706                                 loggingContext.metricStarted();
2707                                 connection.connect();
2708                                 loggingContext.metricEnded();
2709                                 PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
2710                                 if (connection.getResponseCode() == 204) {
2711                                         LOGGER.info("Success. We are configured correctly.");
2712                                         loggingContext.transactionEnded();
2713                                         auditLogger.info("Success. PDP is configured correctly.");
2714                                         PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2715                                         setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2716                                 } else if (connection.getResponseCode() == 200) {
2717                                         LOGGER.info("Success. PDP needs to update its configuration.");
2718                                         loggingContext.transactionEnded();
2719                                         auditLogger.info("Success. PDP needs to update its configuration.");
2720                                         PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2721                                         setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2722                                 } else {
2723                                         LOGGER.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2724                                         loggingContext.transactionEnded();
2725                                         auditLogger.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2726                                         PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2727                                         setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2728                                 }
2729                         } catch (Exception e) {
2730                                 LOGGER.debug(e);
2731                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2732                                 loggingContext.transactionEnded();
2733                                 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2734                                 try {
2735                                         setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2736                                 } catch (PAPException e1) {
2737                                         LOGGER.debug(e1);
2738                                         PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2739                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2740                                 }
2741                         } finally {
2742                                 // cleanup the connection
2743                                 if(connection != null){
2744                                         connection.disconnect();        
2745                                 }
2746                                 // tell the AC to update it's status info
2747                                 notifyAC();
2748                         }
2749                 }
2750         }
2751
2752         /*
2753          * RESTful Interface from PAP to ACs notifying them of changes
2754          */
2755         private void notifyAC() {
2756                 // kick off a thread to do one event notification for all registered ACs
2757                 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2758                 // as part of processing this message on their end.
2759                 Thread t = new Thread(new NotifyACThread());
2760                 t.start();
2761         }
2762
2763         private class NotifyACThread implements Runnable {
2764                 public void run() {
2765                         List<String> disconnectedACs = new ArrayList<>();
2766                         // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2767                         // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2768                         for (String acURL : adminConsoleURLStringList) {
2769                                 HttpURLConnection connection = null;
2770                                 try {
2771                                         acURL += "?PAPNotification=true";
2772                                         //TODO - Currently we just tell AC that "Something changed" without being specific.  Do we want to tell it which group/pdp changed?
2773                                         //TODO - If so, put correct parameters into the Query string here
2774                                         acURL += "&objectType=all" + "&action=update";
2775                                         if (LOGGER.isDebugEnabled()) {
2776                                                 LOGGER.debug("creating url for id '" + acURL + "'");
2777                                         }
2778                                         //TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
2779                                         //TODO          (need to change "cache=", implying getting some input saying which to change)
2780                                         URL url = new URL(acURL );
2781                                         // Open up the connection
2782                                         connection = (HttpURLConnection)url.openConnection();
2783                                         // Setup our method and headers
2784                                         connection.setRequestMethod("PUT");
2785                                         connection.setRequestProperty("Content-Type", "text/x-java-properties");
2786                                         // Adding this in. It seems the HttpUrlConnection class does NOT
2787                                         // properly forward our headers for POST re-direction. It does so
2788                                         // for a GET re-direction.
2789                                         // So we need to handle this ourselves.
2790                                         //TODO - is this needed for a PUT?  seems better to leave in for now?
2791                                         connection.setInstanceFollowRedirects(false);
2792                                         // Do not include any data in the PUT because this is just a
2793                                         // notification to the AC.
2794                                         // The AC will use GETs back to the PAP to get what it needs
2795                                         // to fill in the screens.
2796                                         // Do the connect
2797                                         connection.connect();
2798                                         if (connection.getResponseCode() == 204) {
2799                                                 LOGGER.info("Success. We updated correctly.");
2800                                         } else {
2801                                                 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2802                                         }
2803
2804                                 } catch (Exception e) {
2805                                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2806                                         disconnectedACs.add(acURL);
2807                                 } finally {
2808                                         // cleanup the connection
2809                                         if(connection != null)
2810                                                 connection.disconnect();
2811                                 }
2812                         }
2813                         // remove any ACs that are no longer connected
2814                         if (!disconnectedACs.isEmpty()) {
2815                                 adminConsoleURLStringList.removeAll(disconnectedACs);
2816                         }
2817                 }
2818         }
2819
2820         private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2821                 LOGGER.info("Test request received");
2822                 try {
2823                         im.evaluateSanity();
2824                         //If we make it this far, all is well
2825                         String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2826                         LOGGER.info(message);
2827                         loggingContext.transactionEnded();
2828                         PolicyLogger.audit("Transaction Failed - See Error.log");
2829                         response.setStatus(HttpServletResponse.SC_OK);
2830                         return;
2831                 }catch (ForwardProgressException e){
2832                     String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
2833                             + " Exception Message: " + e.getMessage();
2834                     logMessage(e, message, loggingContext, response);
2835                     return;
2836                 }catch (AdministrativeStateException e){
2837                     String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED."
2838                             + " Exception Message: " + e.getMessage();
2839                     logMessage(e, message, loggingContext, response);
2840                     return;
2841                 }catch (StandbyStatusException e){
2842                     String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE."
2843                             + " Exception Message: " + e.getMessage();
2844                     logMessage(e, message, loggingContext, response);
2845                     return;
2846                 }catch (Exception e) {
2847                         //A subsystem is not making progress, is locked, standby or is not responding
2848                         String eMsg = e.getMessage();
2849                         if(eMsg == null){
2850                                 eMsg = "No Exception Message";
2851                         }
2852                         String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2853                                         + " Exception Message: " + eMsg;
2854                         LOGGER.info(message, e);
2855                         PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2856                         loggingContext.transactionEnded();
2857                         PolicyLogger.audit("Transaction Failed - See Error.log");
2858                         //Get the specific list of subsystems that failed
2859                         String ssFailureList = null;
2860                         for(String failedSS : papDependencyGroupsFlatArray){
2861                                 if(eMsg.contains(failedSS)){
2862                                         if(ssFailureList == null){
2863                                                 ssFailureList = failedSS;
2864                                         }else{
2865                                                 ssFailureList = ssFailureList.concat(","+failedSS);
2866                                         }
2867                                 }
2868                         }
2869                         if(ssFailureList == null){
2870                                 ssFailureList = "UnknownSubSystem";
2871                         }
2872                         response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2873                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2874                         return;
2875                 }
2876         }
2877
2878         /*
2879          * Authorizing the PEP Requests. 
2880          */
2881         private boolean authorizeRequest(HttpServletRequest request) { 
2882                 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2883                 // Check if the Client is Authorized. 
2884                 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2885                         return true;
2886                 }else{
2887                         return false;
2888                 }
2889         }
2890
2891         private static void loadWebapps() throws PAPException{
2892                 if(actionHome == null || configHome == null){
2893                         Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2894                         //Sanity Check
2895                         if (webappsPath == null) {
2896                                 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2897                                 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2898                         }
2899                         Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2900                         Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2901                         if (Files.notExists(webappsPathConfig)) {
2902                                 try {
2903                                         Files.createDirectories(webappsPathConfig);
2904                                 } catch (IOException e) {
2905                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2906                                                         + webappsPathConfig.toAbsolutePath().toString());
2907                                 }
2908                         }
2909                         if (Files.notExists(webappsPathAction)) {
2910                                 try {
2911                                         Files.createDirectories(webappsPathAction);
2912                                 } catch (IOException e) {
2913                                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2914                                                         + webappsPathAction.toAbsolutePath().toString(), e);
2915                                 }
2916                         }
2917                         actionHome = webappsPathAction.toString();
2918                         configHome = webappsPathConfig.toString();
2919                 }
2920         }
2921
2922         public static String getConfigHome(){
2923                 try {
2924                         loadWebapps();
2925                 } catch (PAPException e) {
2926                         LOGGER.debug(e);
2927                         return null;
2928                 }
2929                 return configHome;
2930         }
2931         
2932         private static void setConfigHome(){
2933             configHome = getConfigHome();
2934         }
2935
2936         public static String getActionHome(){
2937                 try {
2938                         loadWebapps();
2939                 } catch (PAPException e) {
2940                         LOGGER.debug(e);
2941                         return null;
2942                 }
2943                 return actionHome;
2944         }
2945         
2946         private static void setActionHome(){
2947             actionHome = getActionHome();
2948         }
2949
2950         public static EntityManagerFactory getEmf() {
2951                 return emf;
2952         }
2953         
2954         public IntegrityAudit getIa() {
2955                 return ia;
2956         }
2957         
2958         public static String getPDPFile(){
2959                 return XACMLPapServlet.pdpFile;
2960         }
2961         
2962         public static String getPersistenceUnit(){
2963                 return PERSISTENCE_UNIT;
2964         }
2965         
2966         public static PAPPolicyEngine getPAPEngine(){
2967                 return papEngine;
2968         }
2969         
2970         public static PolicyDBDaoTransaction getDbDaoTransaction(){
2971                 return policyDBDao.getNewTransaction();
2972         }
2973         public static String getPapDbDriver() {
2974                 return papDbDriver;
2975         }
2976
2977         public static void setPapDbDriver(String papDbDriver) {
2978                 XACMLPapServlet.papDbDriver = papDbDriver;
2979         }
2980
2981         public static String getPapDbUrl() {
2982                 return papDbUrl;
2983         }
2984
2985         public static void setPapDbUrl(String papDbUrl) {
2986                 XACMLPapServlet.papDbUrl = papDbUrl;
2987         }
2988
2989         public static String getPapDbUser() {
2990                 return papDbUser;
2991         }
2992
2993         public static void setPapDbUser(String papDbUser) {
2994                 XACMLPapServlet.papDbUser = papDbUser;
2995         }
2996
2997         public static String getPapDbPassword() {
2998                 return papDbPassword;
2999         }
3000
3001         public static void setPapDbPassword(String papDbPassword) {
3002                 XACMLPapServlet.papDbPassword = papDbPassword;
3003         }
3004
3005         public static String getMsOnapName() {
3006                 return msOnapName;
3007         }
3008
3009         public static void setMsOnapName(String msOnapName) {
3010                 XACMLPapServlet.msOnapName = msOnapName;
3011         }
3012
3013         public static String getMsPolicyName() {
3014                 return msPolicyName;
3015         }
3016
3017         public static void setMsPolicyName(String msPolicyName) {
3018                 XACMLPapServlet.msPolicyName = msPolicyName;
3019         }
3020         
3021         private void logMessage(Exception e, String message, ONAPLoggingContext loggingContext, HttpServletResponse response) {
3022             LOGGER.info(message, e);
3023             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
3024             loggingContext.transactionEnded();
3025             PolicyLogger.audit("Transaction Failed - See Error.log");
3026             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
3027         }
3028 }