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