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