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