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