32b1eb7705841b165da58ea268e30080a3d2887c
[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-2019 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 com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.att.research.xacml.api.pap.PDPStatus;
26 import com.att.research.xacml.util.FactoryException;
27 import com.att.research.xacml.util.XACMLProperties;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.google.common.base.Splitter;
30
31 import java.io.File;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.net.InetAddress;
37 import java.net.UnknownHostException;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.util.List;
42 import java.util.Properties;
43 import java.util.Set;
44 import java.util.UUID;
45 import java.util.concurrent.CopyOnWriteArrayList;
46
47 import javax.persistence.PersistenceException;
48 import javax.servlet.Servlet;
49 import javax.servlet.ServletConfig;
50 import javax.servlet.ServletException;
51 import javax.servlet.annotation.WebInitParam;
52 import javax.servlet.annotation.WebServlet;
53 import javax.servlet.http.HttpServlet;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56
57 import org.apache.commons.io.IOUtils;
58 import org.onap.policy.common.ia.IntegrityAudit;
59 import org.onap.policy.common.im.AdministrativeStateException;
60 import org.onap.policy.common.im.ForwardProgressException;
61 import org.onap.policy.common.im.IntegrityMonitor;
62 import org.onap.policy.common.im.IntegrityMonitorException;
63 import org.onap.policy.common.im.IntegrityMonitorProperties;
64 import org.onap.policy.common.im.StandbyStatusException;
65 import org.onap.policy.common.logging.OnapLoggingContext;
66 import org.onap.policy.common.logging.OnapLoggingUtils;
67 import org.onap.policy.common.logging.eelf.MessageCodes;
68 import org.onap.policy.common.logging.eelf.PolicyLogger;
69 import org.onap.policy.common.logging.flexlogger.FlexLogger;
70 import org.onap.policy.common.logging.flexlogger.Logger;
71 import org.onap.policy.pap.xacml.rest.components.HandleIncomingNotifications;
72 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
73 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
74 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
75 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
76 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
77 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
78 import org.onap.policy.rest.XacmlRest;
79 import org.onap.policy.rest.XacmlRestProperties;
80 import org.onap.policy.rest.dao.PolicyDBException;
81 import org.onap.policy.utils.PeCryptoUtils;
82 import org.onap.policy.utils.PolicyUtils;
83 import org.onap.policy.xacml.api.XACMLErrorConstants;
84 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
85 import org.onap.policy.xacml.api.pap.OnapPDP;
86 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
87 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
88 import org.onap.policy.xacml.std.pap.StdPDP;
89 import org.onap.policy.xacml.std.pap.StdPDPGroup;
90 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
91 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
92 import org.onap.policy.xacml.std.pap.StdPDPStatus;
93
94 /**
95  * Servlet implementation class XacmlPapServlet.
96  */
97 @WebServlet(
98         description = "Implements the XACML PAP RESTful API.",
99         urlPatterns = {"/"},
100         loadOnStartup = 1,
101         initParams = {@WebInitParam(
102                 name = "XACML_PROPERTIES_NAME",
103                 value = "xacml.pap.properties",
104                 description = "The location of the properties file holding configuration information.")})
105 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
106     private static final long serialVersionUID = 1L;
107     private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
108     // audit (transaction) LOGGER
109     private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
110     // Persistence Unit for JPA
111     private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
112     private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
113     // Client Headers.
114     private static final String ENVIRONMENT_HEADER = "Environment";
115     private static final String ADD_GROUP_ERROR = "addGroupError";
116     private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
117
118     private static final String REGEX = "[0-9a-zA-Z._ ]*";
119
120     /*
121      * List of Admin Console URLs. Used to send notifications when configuration changes.
122      *
123      * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom
124      * changed but often read, so the costs of this approach make sense.
125      */
126     private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
127
128     private static String configHome;
129     private static String actionHome;
130     /*
131      * This PAP instance's own URL. Need this when creating URLs to send to the PDPs so they can GET
132      * the Policy files from this process.
133      */
134     private static String papUrl = null;
135     // The heartbeat thread.
136     private static Heartbeat heartbeat = null;
137     private static Thread heartbeatThread = null;
138     private static PolicyDBDao policyDbDao;
139     /*
140      * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
141      */
142     private static PAPPolicyEngine papEngine = null;
143     /*
144      * These are the parameters needed for DB access from the PAP
145      */
146     private static int papIntegrityAuditPeriodSeconds = -1;
147     private static String papDbDriver = null;
148     private static String papDbUrl = null;
149     private static String papDbUser = null;
150     private static String papDbPd = null;
151     private static String papResourceName = null;
152     private static String[] papDependencyGroupsFlatArray = null;
153     private static String environment = null;
154     private static String pdpFile = null;
155
156     private transient IntegrityMonitor im;
157     private transient IntegrityAudit ia;
158
159     // MicroService Model Properties
160     private static String msOnapName;
161     private static String msPolicyName;
162     /*
163      * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
164      * this servlet starts. Its configurable by the admin.
165      */
166     private static transient Thread initiateThread = null;
167     private transient OnapLoggingContext baseLoggingContext = null;
168     private static final String GROUPID = "groupId";
169
170     /**
171      * @see HttpServlet#HttpServlet()
172      */
173     public XACMLPapServlet() {
174         super();
175     }
176
177     /**
178      * @see Servlet#init(ServletConfig)
179      */
180     @Override
181     public void init(ServletConfig config) throws ServletException {
182         try {
183             // Logging
184             baseLoggingContext = new OnapLoggingContext();
185             // fixed data that will be the same in all logging output goes here
186             try {
187                 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
188                 baseLoggingContext.setServer(hostname);
189             } catch (UnknownHostException e) {
190                 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
191             }
192
193             // Initialize
194             XacmlRest.xacmlInit(config);
195             // Load the properties
196             XacmlRest.loadXacmlProperties(null, null);
197             /*
198              * Retrieve the property values
199              */
200             setCommonProperties();
201             String papSiteName = XACMLProperties.getProperty(XacmlRestProperties.PAP_SITE_NAME);
202             if (papSiteName == null) {
203                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
204                         " ERROR: Bad papSiteName property entry");
205                 throw new PAPException("papSiteName is null");
206             }
207             String papNodeType = XACMLProperties.getProperty(XacmlRestProperties.PAP_NODE_TYPE);
208             if (papNodeType == null) {
209                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
210                         " ERROR: Bad papNodeType property entry");
211                 throw new PAPException("papNodeType is null");
212             }
213             // Integer will throw an exception of anything is missing or
214             // unrecognized
215             int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT));
216             int papTransTimeout =
217                     Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT));
218             int papAuditTimeout =
219                     Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
220             // Boolean will default to false if anything is missing or
221             // unrecognized
222             boolean papAuditFlag =
223                     Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
224             boolean papFileSystemAudit =
225                     Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_FLAG));
226             String papDependencyGroups = XACMLProperties.getProperty(XacmlRestProperties.PAP_DEPENDENCY_GROUPS);
227             if (papDependencyGroups == null) {
228                 throw new PAPException("papDependencyGroups is null");
229             }
230             setPAPDependencyGroups(papDependencyGroups);
231             // Integer will throw an exception of anything is missing or
232             // unrecognized
233             int fpMonitorInterval =
234                     Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
235             int failedCounterThreshold =
236                     Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
237             int testTransInterval =
238                     Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
239             int writeFpcInterval =
240                     Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
241             LOGGER.debug("\n\n\n**************************************" + "\n*************************************"
242                     + "\n" + "\n   papDbDriver = " + papDbDriver + "\n   papDbUrl = " + papDbUrl + "\n   papDbUser = "
243                     + papDbUser + "\n   papTransWait = " + papTransWait + "\n   papTransTimeout = " + papTransTimeout
244                     + "\n   papAuditTimeout = " + papAuditTimeout + "\n   papAuditFlag = " + papAuditFlag
245                     + "\n   papFileSystemAudit = " + papFileSystemAudit + "\n   papResourceName = " + papResourceName
246                     + "\n       fpMonitorInterval = " + fpMonitorInterval + "\n failedCounterThreshold = "
247                     + failedCounterThreshold + "\n      testTransInterval = " + testTransInterval + "\n writeFpcInterval = "
248                     + writeFpcInterval + "\n    papSiteName = " + papSiteName + "\n     papNodeType = " + papNodeType
249                     + "\n       papDependencyGroupsList = " + papDependencyGroups + "\n   papIntegrityAuditPeriodSeconds = "
250                     + papIntegrityAuditPeriodSeconds + "\n\n*************************************"
251                     + "\n**************************************");
252             // Pull custom persistence settings
253             Properties properties;
254             try {
255                 properties = XACMLProperties.getProperties();
256                 LOGGER.debug("\n\n\n**************************************" + "\n**************************************"
257                         + "\n\n" + "properties = " + properties + "\n\n**************************************");
258             } catch (IOException e) {
259                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet",
260                         " Error loading properties with: " + "XACMLProperties.getProperties()");
261                 throw new ServletException(e.getMessage(), e.getCause());
262             }
263             // Create an IntegrityMonitor
264             if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) {
265                 properties.setProperty(PERSISTENCE_JDBC_PWD,
266                         PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
267             }
268             im = IntegrityMonitor.getInstance(papResourceName, properties);
269             // Create an IntegrityAudit
270             ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
271             ia.startAuditThread();
272             // we are about to call the PDPs and give them their configuration.
273             // To do that we need to have the URL of this PAP so we can
274             // construct the Policy file URLs
275             setPapUrl(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL));
276             // Create the policyDBDao
277             setPolicyDbDao();
278             // Load our PAP engine, first create a factory
279             ONAPPapEngineFactory factory = ONAPPapEngineFactory
280                     .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
281             // The factory knows how to go about creating a PAP Engine
282             setPAPEngine(factory.newEngine());
283             if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
284                 createDefaultGroupOnInit();
285             }
286             policyDbDao.setPapEngine(XACMLPapServlet.papEngine);
287             if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) {
288                 /*
289                  * Auditing the local File System groups to be in sync with the Database
290                  */
291
292                 // get an AuditTransaction to lock out all other transactions
293                 PolicyDBDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction();
294
295                 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
296                 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
297                 // get the current filesystem group and update from the database
298                 // if needed
299                 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
300                 StdPDPGroup updatedGroup = policyDbDao.auditLocalFileSystem(group);
301                 if (updatedGroup != null) {
302                     papEngine.updateGroup(updatedGroup);
303                 }
304                 LOGGER.info("PapServlet:  updated group is " + papEngine.getDefaultGroup().toString());
305
306                 // sync up the config data from DB to file system
307                 LOGGER.info("PapServlet:  Sync config data from DB to file system");
308                 policyDbDao.synchronizeConfigDataInFileSystem();
309
310                 // release the transaction lock
311                 auditTrans.close();
312             }
313
314             // Configurable - have the PAP servlet initiate sending the latest
315             // PDP policy/pip configuration
316             // to all its known PDP nodes.
317             if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
318                 startInitiateThreadService(new Thread(this));
319             }
320             // After startup, the PAP does Heartbeat's to each of the PDPs
321             // periodically
322             startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine));
323         } catch (FactoryException | PAPException e) {
324             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
325             throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e);
326         } catch (Exception e) {
327             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
328                     " Failed to create engine - unexpected error");
329             throw new ServletException(
330                     XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e);
331         }
332
333     }
334
335     private void createDefaultGroupOnInit() {
336         PolicyDBDaoTransaction addNewGroup = null;
337         try {
338             addNewGroup = policyDbDao.getNewTransaction();
339             OnapPDPGroup group = papEngine.getDefaultGroup();
340             addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
341             addNewGroup.commitTransaction();
342             addNewGroup = policyDbDao.getNewTransaction();
343             addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
344             addNewGroup.commitTransaction();
345         } catch (Exception e) {
346             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
347                     " Error creating new default group in the database");
348             if (addNewGroup != null) {
349                 addNewGroup.rollbackTransaction();
350             }
351         }
352     }
353
354     private static void startInitiateThreadService(Thread thread) {
355         initiateThread = thread;
356         initiateThread.start();
357     }
358
359     private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) {
360         try {
361             mapper.writeValue(response.getOutputStream(), value);
362         } catch (Exception e) {
363             LOGGER.error(e);
364         }
365     }
366
367     private static void startHeartBeatService(Heartbeat heartbeat) {
368         XACMLPapServlet.heartbeat = heartbeat;
369         XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
370         XACMLPapServlet.heartbeatThread.start();
371     }
372
373     private static void setPolicyDbDao() throws ServletException {
374         try {
375             policyDbDao = PolicyDBDao.getPolicyDBDaoInstance();
376         } catch (Exception e) {
377             throw new ServletException("Unable to Create Policy DBDao Instance", e);
378         }
379     }
380
381     public static PolicyDBDao getPolicyDbDao() {
382         return policyDbDao;
383     }
384
385     private static void setPapUrl(String papUrl) {
386         XACMLPapServlet.papUrl = papUrl;
387     }
388
389     public static String getPapUrl() {
390         return papUrl;
391     }
392
393     private static void setPAPEngine(PAPPolicyEngine newEngine) {
394         XACMLPapServlet.papEngine = newEngine;
395     }
396
397     private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
398         try {
399             // Now we have flattened the array into a simple comma-separated list
400             papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
401             // clean up the entries
402             for (int i = 0; i < papDependencyGroupsFlatArray.length; i++) {
403                 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
404             }
405             try {
406                 if (XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) {
407                     papIntegrityAuditPeriodSeconds = Integer.parseInt(
408                             XACMLProperties.getProperty(XacmlRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
409                 }
410             } catch (Exception e) {
411                 String msg = "integrity_audit_period_seconds ";
412                 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
413                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
414                         " ERROR: " + msg + "Bad property entry");
415                 throw e;
416             }
417         } catch (Exception e) {
418             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
419             throw new PAPException(e);
420         }
421     }
422
423     private static void setCommonProperties() throws PAPException {
424         setConfigHome();
425         setActionHome();
426         papDbDriver = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_DRIVER);
427         if (papDbDriver == null) {
428             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
429                     " 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",
442                     " ERROR: Bad papDbUser property entry");
443             throw new PAPException("papDbUser is null");
444         }
445         setPapDbUser(papDbUser);
446         PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
447         papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_PASSWORD));
448         if (papDbPd == null) {
449             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
450                     " ERROR: Bad papDbPassword property entry");
451             throw new PAPException("papDbPassword is null");
452         }
453         setPapDbPassword(papDbPd);
454         papResourceName = XACMLProperties.getProperty(XacmlRestProperties.PAP_RESOURCE_NAME);
455         if (papResourceName == null) {
456             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
457                     " ERROR: Bad papResourceName property entry");
458             throw new PAPException("papResourceName is null");
459         }
460         environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
461         // Micro Service Properties
462         msOnapName = XACMLProperties.getProperty("xacml.policy.msOnapName");
463         setMsOnapName(msOnapName);
464         msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName");
465         setMsPolicyName(msPolicyName);
466         // PDPId File location
467         XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE);
468         if (XACMLPapServlet.pdpFile == null) {
469             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
470                     + XacmlRestProperties.PROP_PDP_IDFILE);
471             throw new PAPException("The PDP Id Authentication File Property :" + XacmlRestProperties.PROP_PDP_IDFILE
472                     + " is not Valid. ");
473         }
474     }
475
476     /**
477      * Thread used only during PAP startup to initiate change messages to all known PDPs. This must
478      * be on a separate thread so that any GET requests from the PDPs during this update can be
479      * serviced.
480      */
481     @Override
482     public void run() {
483         // send the current configuration to all the PDPs that we know about
484         changed();
485     }
486
487     /**
488      * @see Servlet#destroy()
489      *      <p>
490      *      Depending on how this servlet is run, we may or may not care about cleaning up the
491      *      resources. For now we assume that we do care.
492      */
493     @Override
494     public void destroy() {
495         // Make sure our threads are destroyed
496         if (XACMLPapServlet.heartbeatThread != null) {
497             // stop the heartbeat
498             try {
499                 if (XACMLPapServlet.heartbeat != null) {
500                     XACMLPapServlet.heartbeat.terminate();
501                 }
502                 XACMLPapServlet.heartbeatThread.interrupt();
503                 XACMLPapServlet.heartbeatThread.join();
504             } catch (InterruptedException e) {
505                 XACMLPapServlet.heartbeatThread.interrupt();
506                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
507             }
508         }
509         if (initiateThread != null) {
510             try {
511                 initiateThread.interrupt();
512                 initiateThread.join();
513             } catch (InterruptedException e) {
514                 initiateThread.interrupt();
515                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
516             }
517         }
518     }
519
520     private ConsoleAndApiService getAcServiceInstance() {
521         return new ConsoleAndApiService();
522     }
523
524     /**
525      * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make
526      * changes in the PDP Groups.
527      *
528      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
529      */
530     @Override
531     protected void doPost(HttpServletRequest request, HttpServletResponse response)
532             throws ServletException, IOException {
533         OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
534         setLoggingContext(loggingContext, "doPost", "PAP.post");
535         PolicyDBDaoTransaction pdpTransaction = null;
536         try {
537             loggingContext.metricStarted();
538             im.startTransaction();
539             loggingContext.metricEnded();
540             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
541         } catch (AdministrativeStateException ae) {
542             String message = "POST interface called for PAP " + papResourceName
543                     + " but it has an Administrative state of " + im.getStateManager().getAdminState()
544                     + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION;
545             LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
546             loggingContext.metricEnded();
547             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
548             loggingContext.transactionEnded();
549             PolicyLogger.audit("Transaction Failed - See Error.log");
550             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
551             return;
552         } catch (IntegrityMonitorException ime) {
553             String message =
554                     "POST interface called for PAP " + papResourceName + " but it has an Administrative state of "
555                             + im.getStateManager().getAdminState() + " and a Standby Status of "
556                             + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
557             LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime);
558             loggingContext.metricEnded();
559             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
560             loggingContext.transactionEnded();
561             PolicyLogger.audit("Transaction Failed - See Error.log");
562             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
563             return;
564         }
565         try {
566             loggingContext.metricStarted();
567             XacmlRest.dumpRequest(request);
568             loggingContext.metricEnded();
569             PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
570             // since getParameter reads the content string, explicitly get the
571             // content before doing that.
572             // Simply getting the inputStream seems to protect it against being
573             // consumed by getParameter.
574             request.getInputStream();
575             String groupId = request.getParameter(GROUPID);
576             String apiflag = request.getParameter("apiflag");
577             if (groupId != null) {
578                 // Is this from the Admin Console or API?
579                 if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
580                     // this is from the API so we need to check the client
581                     // credentials before processing the request
582                     if (!authorizeRequest(request)) {
583                         String message = "PEP not Authorized for making this Request!!";
584                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
585                         loggingContext.transactionEnded();
586                         PolicyLogger.audit("Transaction Failed - See Error.log");
587                         setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
588                         im.endTransaction();
589                         return;
590                     }
591                 }
592                 loggingContext.metricStarted();
593                 getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine);
594                 loggingContext.metricEnded();
595                 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
596                 loggingContext.transactionEnded();
597                 PolicyLogger.audit("Transaction Ended Successfully");
598                 im.endTransaction();
599                 return;
600             }
601             // Request is from a PDP asking for its config.
602             loggingContext.setServiceName("PDP:PAP.register");
603             // Get the PDP's ID
604             String id = this.getPDPID(request);
605             String jmxport = this.getPDPJMX(request);
606             LOGGER.info("Request(doPost) from PDP coming up: " + id);
607             // Get the PDP Object
608             OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
609             // Is it known?
610             if (pdp == null) {
611                 LOGGER.info("Unknown PDP: " + id);
612                 // Check PDP ID
613                 if (CheckPDP.validateID(id)) {
614                     pdpTransaction = policyDbDao.getNewTransaction();
615                     try {
616                         pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id,
617                                 "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
618                         XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id,
619                                 "Registered on first startup", Integer.parseInt(jmxport));
620                     } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException
621                             | PersistenceException | PolicyDBException e) {
622                         pdpTransaction.rollbackTransaction();
623                         String message = "Failed to create new PDP for id: " + id;
624                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
625                         loggingContext.transactionEnded();
626                         PolicyLogger.audit("Transaction Failed - See Error.log");
627                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
628                         im.endTransaction();
629                         return;
630                     }
631                     // get the PDP we just created
632                     try {
633                         pdp = XACMLPapServlet.papEngine.getPDP(id);
634                     } catch (PAPException e) {
635                         LOGGER.error(e);
636                     }
637                     if (pdp == null) {
638                         if (pdpTransaction != null) {
639                             pdpTransaction.rollbackTransaction();
640                         }
641                         String message = "Failed to create new PDP for id: " + id;
642                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
643                         loggingContext.transactionEnded();
644                         PolicyLogger.audit("Transaction Failed - See Error.log");
645                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
646                         im.endTransaction();
647                         return;
648                     }
649                 } else {
650                     String message = "PDP is Unauthorized to Connect to PAP: " + id;
651                     loggingContext.transactionEnded();
652                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
653                     setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
654                             "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
655                     PolicyLogger.audit("Transaction Failed - See Error.log");
656                     im.endTransaction();
657                     return;
658                 }
659                 try {
660                     loggingContext.metricStarted();
661                     pdpTransaction.commitTransaction();
662                     loggingContext.metricEnded();
663                     PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
664                 } catch (Exception e) {
665                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
666                             "Could not commit transaction to put pdp in the database");
667                 }
668             }
669             if (jmxport != null && !"".equals(jmxport)) {
670                 try {
671                     ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
672                 } catch (NumberFormatException e) {
673                     LOGGER.error(e);
674                 }
675             }
676             // Get the PDP's Group
677             OnapPDPGroup group = null;
678             try {
679                 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
680             } catch (PAPException e) {
681                 LOGGER.error(e);
682             }
683             if (group == null) {
684                 PolicyLogger.error(
685                         MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
686                 loggingContext.transactionEnded();
687                 PolicyLogger.audit("Transaction Failed - See Error.log");
688                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
689                         "PDP not associated with any group, even the default");
690                 im.endTransaction();
691                 return;
692             }
693             // Determine what group the PDP node is in and get
694             // its policy/pip properties.
695             Properties policies = group.getPolicyProperties();
696             Properties pipconfig = group.getPipConfigProperties();
697             // Get the current policy/pip configuration that the PDP has
698             Properties pdpProperties = new Properties();
699             try {
700                 pdpProperties.load(request.getInputStream());
701             } catch (IOException e) {
702                 LOGGER.error(e);
703             }
704             LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
705             LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
706             LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
707             // Validate the node's properties
708             boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
709             // Send back current configuration
710             if (!isCurrent) {
711                 // Tell the PDP we are sending back the current policies/pip
712                 // config
713                 LOGGER.info("PDP configuration NOT current.");
714                 if (policies != null) {
715                     // Put URL's into the properties in case the PDP needs to
716                     // retrieve them.
717                     this.populatePolicyURL(request.getRequestURL(), policies);
718                     // Copy the properties to the output stream
719                     try {
720                         policies.store(response.getOutputStream(), "");
721                     } catch (IOException e) {
722                         LOGGER.error(e);
723                     }
724                 }
725                 if (pipconfig != null) {
726                     // Copy the properties to the output stream
727                     try {
728                         pipconfig.store(response.getOutputStream(), "");
729                     } catch (IOException e) {
730                         LOGGER.error(e);
731                     }
732                 }
733                 // We are good - and we are sending them information
734                 response.setStatus(HttpServletResponse.SC_OK);
735                 try {
736                     setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
737                 } catch (PAPException e) {
738                     LOGGER.error(e);
739                 }
740             } else {
741                 // Tell them they are good
742                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
743                 try {
744                     setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
745                 } catch (PAPException e) {
746                     LOGGER.error(e);
747                 }
748             }
749             auditLogger.info("Success");
750             PolicyLogger.audit("Transaction Ended Successfully");
751         } catch (PAPException | IOException | NumberFormatException e) {
752             if (pdpTransaction != null) {
753                 pdpTransaction.rollbackTransaction();
754             }
755             LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
756             loggingContext.transactionEnded();
757             PolicyLogger.audit("Transaction Failed - See Error.log");
758             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
759             im.endTransaction();
760             return;
761         }
762         // Catch anything that fell through
763         loggingContext.transactionEnded();
764         PolicyLogger.audit("Transaction Ended");
765         im.endTransaction();
766     }
767
768     private void setResponseError(HttpServletResponse response, int responseCode, String message) {
769         try {
770             if (message != null && !message.isEmpty()) {
771                 response.sendError(responseCode, message);
772             }
773         } catch (IOException e) {
774             LOGGER.error("Error setting Error response Header ", e);
775         }
776     }
777
778     /**
779      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
780      */
781     @Override
782     protected void doGet(HttpServletRequest request, HttpServletResponse response)
783             throws ServletException, IOException {
784         OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
785         setLoggingContext(loggingContext, "doGet", "PAP.get");
786         loggingContext.metricStarted();
787         XacmlRest.dumpRequest(request);
788         loggingContext.metricEnded();
789         PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
790         String pathInfo = request.getRequestURI();
791         LOGGER.info("path info: " + pathInfo);
792         if (pathInfo != null && "/pap/test".equals(pathInfo)) {
793             // DO NOT do a im.startTransaction for the test request
794             try {
795                 testService(loggingContext, response);
796             } catch (IOException e) {
797                 LOGGER.debug(e);
798             }
799             return;
800         }
801         // This im.startTransaction() covers all other Get transactions
802         try {
803             loggingContext.metricStarted();
804             im.startTransaction();
805             loggingContext.metricEnded();
806             PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
807         } catch (IntegrityMonitorException ime) {
808             String message =
809                     "GET interface called for PAP " + papResourceName + " but it has an Administrative state of "
810                             + im.getStateManager().getAdminState() + " and a Standby Status of "
811                             + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
812             LOGGER.info(message, ime);
813             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
814             loggingContext.transactionEnded();
815             PolicyLogger.audit("Transaction Failed - See Error.log");
816             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
817             return;
818         }
819         // Request from the API to get the gitPath
820         String apiflag = request.getParameter("apiflag");
821         if (apiflag != null) {
822             if (authorizeRequest(request)) {
823                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
824                 try {
825                     loggingContext.metricStarted();
826                     apiRequestHandler.doGet(request, response, apiflag);
827                     loggingContext.metricEnded();
828                     PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
829                 } catch (IOException e) {
830                     LOGGER.error(e);
831                 }
832                 loggingContext.transactionEnded();
833                 PolicyLogger.audit("Transaction Ended Successfully");
834                 im.endTransaction();
835                 return;
836             } else {
837                 String message =
838                         "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
839                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
840                 loggingContext.transactionEnded();
841                 PolicyLogger.audit("Transaction Failed - See Error.log");
842                 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
843                 im.endTransaction();
844                 return;
845             }
846         }
847         // Is this from the Admin Console?
848         String groupId = request.getParameter(GROUPID);
849         if (groupId != null) {
850             // this is from the Admin Console, so handle separately
851             try {
852                 loggingContext.metricStarted();
853                 getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine);
854                 loggingContext.metricEnded();
855                 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
856             } catch (IOException e) {
857                 LOGGER.error(e);
858             }
859             loggingContext.transactionEnded();
860             PolicyLogger.audit("Transaction Ended Successfully");
861             im.endTransaction();
862             return;
863         }
864         // Get the PDP's ID
865         String id = this.getPDPID(request);
866         LOGGER.info("doGet from: " + id);
867         // Get the PDP Object
868         OnapPDP pdp = null;
869         try {
870             pdp = XACMLPapServlet.papEngine.getPDP(id);
871         } catch (PAPException e) {
872             LOGGER.error(e);
873         }
874         // Is it known?
875         if (pdp == null) {
876             // Check if request came from localhost
877             if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) {
878                 // Return status information - basically all the groups
879                 loggingContext.setServiceName("PAP.getGroups");
880                 Set<OnapPDPGroup> groups = null;
881                 try {
882                     groups = papEngine.getOnapPDPGroups();
883                 } catch (PAPException e) {
884                     LOGGER.debug(e);
885                     PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
886                     loggingContext.transactionEnded();
887                     PolicyLogger.audit("Transaction Failed - See Error.log");
888                     setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
889                     im.endTransaction();
890                     return;
891                 }
892                 // convert response object to JSON and include in the response
893                 mapperWriteValue(new ObjectMapper(), response, groups);
894                 response.setHeader("content-type", "application/json");
895                 response.setStatus(HttpServletResponse.SC_OK);
896                 loggingContext.transactionEnded();
897                 PolicyLogger.audit("Transaction Ended Successfully");
898                 im.endTransaction();
899                 return;
900             }
901             String message =
902                     "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
903             PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
904             loggingContext.transactionEnded();
905             PolicyLogger.audit("Transaction Failed - See Error.log");
906             setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
907             im.endTransaction();
908             return;
909         }
910         loggingContext.setServiceName("PAP.getPolicy");
911         // Get the PDP's Group
912         OnapPDPGroup group = null;
913         try {
914             group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
915         } catch (PAPException e) {
916             LOGGER.error(e);
917         }
918         if (group == null) {
919             String message = "No group associated with pdp " + pdp.getId();
920             LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
921             loggingContext.transactionEnded();
922             PolicyLogger.audit("Transaction Failed - See Error.log");
923             setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
924             im.endTransaction();
925             return;
926         }
927         // Which policy do they want?
928         String policyId = request.getParameter("id");
929         if (policyId == null) {
930             String message = "Did not specify an id for the policy";
931             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
932             loggingContext.transactionEnded();
933             PolicyLogger.audit("Transaction Failed - See Error.log");
934             setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
935             im.endTransaction();
936             return;
937         }
938         PDPPolicy policy = group.getPolicy(policyId);
939         if (policy == null) {
940             String message = "Unknown policy: " + policyId;
941             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
942             loggingContext.transactionEnded();
943             PolicyLogger.audit("Transaction Failed - See Error.log");
944             setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
945             im.endTransaction();
946             return;
947         }
948         try {
949             LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : "
950                     + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
951         } catch (PAPException | IOException e) {
952             LOGGER.error(e);
953         }
954         try (InputStream is =
955                 new FileInputStream(((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId);
956                 OutputStream os = response.getOutputStream()) {
957             // Send the policy back
958             IOUtils.copy(is, os);
959             response.setStatus(HttpServletResponse.SC_OK);
960             loggingContext.transactionEnded();
961             auditLogger.info("Success");
962             PolicyLogger.audit("Transaction Ended Successfully");
963         } catch (IOException e) {
964             String message = "Failed to open policy id " + policyId;
965             LOGGER.debug(e);
966             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
967             loggingContext.transactionEnded();
968             PolicyLogger.audit("Transaction Failed - See Error.log");
969             setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
970         }
971         loggingContext.transactionEnded();
972         PolicyLogger.audit("Transaction Ended");
973         im.endTransaction();
974     }
975
976     /**
977      * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
978      */
979     @Override
980     protected void doPut(HttpServletRequest request, HttpServletResponse response)
981             throws ServletException, IOException {
982         OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
983         setLoggingContext(loggingContext, "doPut", "PAP.put");
984         try {
985             loggingContext.metricStarted();
986             im.startTransaction();
987             loggingContext.metricEnded();
988             PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
989         } catch (IntegrityMonitorException e) {
990             String message =
991                     "PUT interface called for PAP " + papResourceName + " but it has an Administrative state of "
992                             + im.getStateManager().getAdminState() + " and a Standby Status of "
993                             + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + e.getMessage();
994             LOGGER.info(message, e);
995             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
996             loggingContext.transactionEnded();
997             PolicyLogger.audit("Transaction Failed - See Error.log");
998             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
999             return;
1000         }
1001
1002         loggingContext.metricStarted();
1003         // need to check if request is from the API or Admin console
1004         String apiflag = request.getParameter("apiflag");
1005         // For Debug purposes
1006         if (!"api".equals(apiflag) && PolicyLogger.isDebugEnabled()) {
1007             XacmlRest.dumpRequest(request);
1008             PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1009         }
1010         loggingContext.metricEnded();
1011
1012         // This would occur if a PolicyDBDao notification was received
1013         String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1014         if (policyDBDaoRequestUrl != null) {
1015             LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received.");
1016             String policyDBDaoRequestEntityId = request.getParameter("entityid");
1017             String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1018             String policyDBDaoRequestExtraData = request.getParameter("extradata");
1019             if (policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null) {
1020                 setResponseError(response, 400, "entityid or entitytype not supplied");
1021                 loggingContext.transactionEnded();
1022                 PolicyLogger.audit("Transaction Ended Successfully");
1023                 im.endTransaction();
1024                 return;
1025             }
1026             loggingContext.metricStarted();
1027             LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1028             HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications();
1029             handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl,
1030                     policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this);
1031             loggingContext.metricEnded();
1032             PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1033             response.setStatus(200);
1034             loggingContext.transactionEnded();
1035             PolicyLogger.audit("Transaction Ended Successfully");
1036             im.endTransaction();
1037             return;
1038         }
1039         /*
1040          * Request for ImportService
1041          */
1042         String importService = request.getParameter("importService");
1043         if (importService != null) {
1044             if (authorizeRequest(request)) {
1045                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1046                 try {
1047                     loggingContext.metricStarted();
1048                     apiRequestHandler.doPut(request, response, importService);
1049                     loggingContext.metricEnded();
1050                     PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1051                 } catch (IOException e) {
1052                     LOGGER.error(e);
1053                 }
1054                 im.endTransaction();
1055                 return;
1056             } else {
1057                 String message =
1058                         "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1059                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message);
1060                 loggingContext.transactionEnded();
1061                 PolicyLogger.audit("Transaction Failed - See Error.log");
1062                 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1063                 return;
1064             }
1065         }
1066         //
1067         // See if this is Admin Console registering itself with us
1068         //
1069         String acURLString = request.getParameter("adminConsoleURL");
1070         if (acURLString != null) {
1071             loggingContext.setServiceName("AC:PAP.register");
1072             // remember this Admin Console for future updates
1073             if (!adminConsoleURLStringList.contains(acURLString)) {
1074                 adminConsoleURLStringList.add(acURLString);
1075             }
1076             if (LOGGER.isDebugEnabled()) {
1077                 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1078             }
1079             response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1080             loggingContext.transactionEnded();
1081             auditLogger.info("Success");
1082             PolicyLogger.audit("Transaction Ended Successfully");
1083             im.endTransaction();
1084             return;
1085         }
1086         /*
1087          * This is to update the PDP Group with the policy/policies being pushed Part of a 2 step
1088          * process to push policies to the PDP that can now be done From both the Admin Console and
1089          * the PolicyEngine API
1090          */
1091         String groupId = request.getParameter(GROUPID);
1092         if (groupId != null) {
1093             if (apiflag != null) {
1094                 if (!authorizeRequest(request)) {
1095                     String message =
1096                             "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1097                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1098                     loggingContext.transactionEnded();
1099                     PolicyLogger.audit("Transaction Failed - See Error.log");
1100                     setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1101                     return;
1102                 }
1103                 if (apiflag.equalsIgnoreCase("addPolicyToGroup")) {
1104                     try {
1105                         updateGroupsFromAPI(request, response, groupId, loggingContext);
1106                     } catch (IOException e) {
1107                         LOGGER.error(e);
1108                     }
1109                     loggingContext.transactionEnded();
1110                     PolicyLogger.audit("Transaction Ended Successfully");
1111                     im.endTransaction();
1112                     return;
1113                 }
1114             }
1115             // this is from the Admin Console, so handle separately
1116             try {
1117                 loggingContext.metricEnded();
1118                 getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine);
1119                 loggingContext.metricEnded();
1120                 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1121             } catch (IOException e) {
1122                 LOGGER.error(e);
1123             }
1124             loggingContext.transactionEnded();
1125             PolicyLogger.audit("Transaction Ended Successfully");
1126             im.endTransaction();
1127             return;
1128         }
1129         //
1130         // Request is for policy validation and creation
1131         //
1132         if (apiflag != null && apiflag.equalsIgnoreCase("admin")) {
1133             // this request is from the Admin Console
1134             SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1135             try {
1136                 loggingContext.metricStarted();
1137                 savePolicyHandler.doPolicyAPIPut(request, response);
1138                 loggingContext.metricEnded();
1139                 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1140             } catch (IOException e) {
1141                 LOGGER.error(e);
1142             }
1143             loggingContext.transactionEnded();
1144             PolicyLogger.audit("Transaction Ended Successfully");
1145             im.endTransaction();
1146             return;
1147         } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1148             // this request is from the Policy Creation API
1149             if (authorizeRequest(request)) {
1150                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1151                 try {
1152                     loggingContext.metricStarted();
1153                     apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1154                     loggingContext.metricEnded();
1155                     PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1156                 } catch (IOException e) {
1157                     LOGGER.error(e);
1158                 }
1159                 loggingContext.transactionEnded();
1160                 PolicyLogger.audit("Transaction Ended Successfully");
1161                 im.endTransaction();
1162                 return;
1163             } else {
1164                 String message = "PEP not Authorized for making this Request!!";
1165                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1166                 loggingContext.transactionEnded();
1167                 PolicyLogger.audit("Transaction Failed - See Error.log");
1168                 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1169                 im.endTransaction();
1170                 return;
1171             }
1172         }
1173         // We do not expect anything from anywhere else.
1174         // This method is here in case we ever need to support other operations.
1175         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1176         loggingContext.transactionEnded();
1177         PolicyLogger.audit("Transaction Failed - See Error.log");
1178         setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1179         loggingContext.transactionEnded();
1180         PolicyLogger.audit("Transaction Failed - See error.log");
1181         im.endTransaction();
1182     }
1183
1184     /**
1185      * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1186      */
1187     @Override
1188     protected void doDelete(HttpServletRequest request, HttpServletResponse response)
1189             throws ServletException, IOException {
1190         OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1191         setLoggingContext(loggingContext, "doDelete", "PAP.delete");
1192         try {
1193             loggingContext.metricStarted();
1194             im.startTransaction();
1195             loggingContext.metricEnded();
1196             PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1197         } catch (IntegrityMonitorException ime) {
1198             String message =
1199                     "DELETE interface called for PAP " + papResourceName + " but it has an Administrative state of "
1200                             + im.getStateManager().getAdminState() + " and a Standby Status of "
1201                             + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
1202             LOGGER.info(message, ime);
1203             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1204             loggingContext.transactionEnded();
1205             PolicyLogger.audit("Transaction Failed - See Error.log");
1206             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1207             return;
1208         }
1209         loggingContext.metricStarted();
1210         XacmlRest.dumpRequest(request);
1211         loggingContext.metricEnded();
1212         PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1213         String groupId = request.getParameter(GROUPID);
1214         String apiflag = request.getParameter("apiflag");
1215         if (groupId != null) {
1216             // Is this from the Admin Console or API?
1217             if (apiflag != null) {
1218                 if (!authorizeRequest(request)) {
1219                     String message =
1220                             "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1221                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1222                     loggingContext.transactionEnded();
1223                     PolicyLogger.audit("Transaction Failed - See Error.log");
1224                     setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1225                     return;
1226                 }
1227                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1228                 try {
1229                     loggingContext.metricStarted();
1230                     apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1231                     loggingContext.metricEnded();
1232                     PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1233                 } catch (Exception e) {
1234                     LOGGER.error("Exception Occured" + e);
1235                 }
1236                 if (apiRequestHandler.getNewGroup() != null) {
1237                     groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1238                 }
1239                 return;
1240             }
1241             // this is from the Admin Console, so handle separately
1242             try {
1243                 loggingContext.metricStarted();
1244                 getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine);
1245                 loggingContext.metricEnded();
1246                 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1247             } catch (IOException e) {
1248                 LOGGER.error(e);
1249             }
1250             loggingContext.transactionEnded();
1251             PolicyLogger.audit("Transaction Ended Successfully");
1252             im.endTransaction();
1253             return;
1254         }
1255         // Catch anything that fell through
1256         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1257         loggingContext.transactionEnded();
1258         PolicyLogger.audit("Transaction Failed - See Error.log");
1259         setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1260         im.endTransaction();
1261     }
1262
1263     private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1264         String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1265         String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1266         if (localRootPolicies == null || localReferencedPolicies == null) {
1267             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="
1268                     + localRootPolicies + "  ReferencedPolicies=" + localReferencedPolicies);
1269             return false;
1270         }
1271         // Compare the policies and pipconfig properties to the pdpProperties
1272         try {
1273             // the policy properties includes only xacml.rootPolicies and
1274             // xacml.referencedPolicies without any .url entries
1275             Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1276             Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1277             if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES))
1278                     && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES))
1279                     && pdpPipConfig.equals(pipconfig)) {
1280                 // The PDP is current
1281                 return true;
1282             }
1283         } catch (Exception e) {
1284             // we get here if the PDP did not include either xacml.rootPolicies
1285             // or xacml.pip.engines,
1286             // or if there are policies that do not have a corresponding ".url"
1287             // property.
1288             // Either of these cases means that the PDP is not up-to-date, so
1289             // just drop-through to return false.
1290             PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1291         }
1292         return false;
1293     }
1294
1295     private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1296         String lists[] = new String[2];
1297         lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1298         lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1299         for (String list : lists) {
1300             if (list != null && list.isEmpty() == false) {
1301                 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1302                     String url = urlPath + "?id=" + id;
1303                     LOGGER.info("Policy URL for " + id + ": " + url);
1304                     policies.setProperty(id + ".url", url);
1305                 }
1306             }
1307         }
1308     }
1309
1310     protected String getPDPID(HttpServletRequest request) {
1311         String pdpURL = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID);
1312         if (pdpURL == null || pdpURL.isEmpty()) {
1313             // Should send back its port for identification
1314             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1315             pdpURL = "";
1316         }
1317         return pdpURL;
1318     }
1319
1320     protected String getPDPJMX(HttpServletRequest request) {
1321         String pdpJMMX = request.getHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1322         if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1323             // Should send back its port for identification
1324             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE
1325                     + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1326             return null;
1327         }
1328         return pdpJMMX;
1329     }
1330
1331     /**
1332      * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1333      *
1334      * @param request
1335      * @param response
1336      * @param groupId
1337      * @param loggingContext
1338      * @throws ServletException
1339      * @throws IOException
1340      */
1341     public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId,
1342             OnapLoggingContext loggingContext) throws IOException {
1343         PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction();
1344         PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1345         try {
1346             String userId = request.getParameter("userId");
1347             // for PUT operations the group may or may not need to exist before
1348             // the operation can be done
1349             StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1350
1351             // get the request input stream content into a String
1352             String json = null;
1353             java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1354             scanner.useDelimiter("\\A");
1355             json = scanner.hasNext() ? scanner.next() : "";
1356             scanner.close();
1357
1358             PolicyLogger.info("pushPolicy request from API: " + json);
1359
1360             // convert Object sent as JSON into local object
1361             StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1362
1363             // Get the current policies from the Group and Add the new one
1364             // If the selected policy is in the group we must remove the old
1365             // version of it
1366             LOGGER.info("Removing old version of the policy");
1367             for (PDPPolicy existingPolicy : group.getPolicies()) {
1368                 if (existingPolicy.getName().equals(policy.getName())
1369                         && !existingPolicy.getId().equals(policy.getId())) {
1370                     group.removePolicy(existingPolicy);
1371                     LOGGER.info("Removing policy: " + existingPolicy);
1372                     break;
1373                 }
1374             }
1375
1376             // Assume that this is an update of an existing PDP Group
1377             loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1378             try {
1379                 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut", userId);
1380             } catch (Exception e) {
1381                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1382                         " Error while updating group in the database: " + "group=" + group.getId());
1383                 throw new PAPException(e.getMessage());
1384             }
1385
1386             LOGGER.info("Calling updatGroup() with new group");
1387             papEngine.updateGroup(group);
1388             String policyId = "empty";
1389             if (policy != null && policy.getId() != null) {
1390                 policyId = policy.getId();
1391             }
1392             if (!policyId.matches(REGEX)) {
1393                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1394                 response.addHeader("error", ADD_GROUP_ERROR);
1395                 response.addHeader("message", "Policy Id is not valid");
1396                 return;
1397             }
1398             response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1399             response.addHeader("operation", "push");
1400             response.addHeader("policyId", policyId);
1401             response.addHeader(GROUPID, groupId);
1402
1403             LOGGER.info("Group '" + group.getId() + "' updated");
1404
1405             loggingContext.metricStarted();
1406             acPutTransaction.commitTransaction();
1407             loggingContext.metricEnded();
1408             PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1409
1410             // Group changed, which might include changing the policies
1411             groupChanged(group, loggingContext);
1412             loggingContext.transactionEnded();
1413             LOGGER.info("Success");
1414
1415             if (policy != null
1416                     && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1417                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1418                 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1419                     LOGGER.debug("Precheck Successful.");
1420                 }
1421             }
1422
1423             PolicyLogger.audit("Transaction Ended Successfully");
1424             return;
1425         } catch (PAPException e) {
1426             acPutTransaction.rollbackTransaction();
1427             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1428             loggingContext.transactionEnded();
1429             PolicyLogger.audit("Transaction Failed - See Error.log");
1430             String message = XACMLErrorConstants.ERROR_PROCESS_FLOW
1431                     + "Exception in request to update group from API - See Error.log on on the PAP.";
1432             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1433             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1434             response.addHeader("error", ADD_GROUP_ERROR);
1435             response.addHeader("message", message);
1436             return;
1437         }
1438     }
1439
1440     /*
1441      * HELPER to change Group status when PDP status is changed (Must NOT be called from a method
1442      * that is synchronized on the papEngine or it may deadlock)
1443      */
1444     public void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
1445         setPDPSummaryStatus(pdp, newStatus.toString());
1446     }
1447
1448     public void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
1449         synchronized (papEngine) {
1450             StdPDPStatus status = new StdPDPStatus();
1451             status.setStatus(PDPStatus.Status.valueOf(newStatus));
1452             ((StdPDP) pdp).setStatus(status);
1453             // now adjust the group
1454             StdPDPGroup group = (StdPDPGroup) papEngine.getPDPGroup(pdp);
1455             // if the PDP was just deleted it may transiently exist but not be
1456             // in a group
1457             if (group != null) {
1458                 group.resetStatus();
1459             }
1460         }
1461     }
1462
1463     /*
1464      * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine in
1465      * the PDP group directories
1466      */
1467     @Override
1468     public void changed() {
1469         // all PDPs in all groups need to be updated/sync'd
1470         Set<OnapPDPGroup> groups;
1471         try {
1472             groups = papEngine.getOnapPDPGroups();
1473         } catch (PAPException e) {
1474             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
1475             throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1476         }
1477         for (OnapPDPGroup group : groups) {
1478             groupChanged(group);
1479         }
1480     }
1481
1482     public void changed(OnapLoggingContext loggingContext) {
1483         // all PDPs in all groups need to be updated/sync'd
1484         Set<OnapPDPGroup> groups;
1485         try {
1486             groups = papEngine.getOnapPDPGroups();
1487         } catch (PAPException e) {
1488             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
1489             throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1490         }
1491         for (OnapPDPGroup group : groups) {
1492             groupChanged(group, loggingContext);
1493         }
1494     }
1495
1496     @Override
1497     public void groupChanged(OnapPDPGroup group) {
1498         // all PDPs within one group need to be updated/sync'd
1499         for (OnapPDP pdp : group.getOnapPdps()) {
1500             pdpChanged(pdp, getPdpDataByGroup(group));
1501         }
1502     }
1503
1504     public void groupChanged(OnapPDPGroup group, OnapLoggingContext loggingContext) {
1505         // all PDPs within one group need to be updated/sync'd
1506         for (OnapPDP pdp : group.getOnapPdps()) {
1507             pdpChanged(pdp, loggingContext, getPdpDataByGroup(group));
1508         }
1509     }
1510
1511     @Override
1512     public void pdpChanged(OnapPDP pdp) {
1513         // kick off a thread to do an event notification for each PDP.
1514         // This needs to be on a separate thread so that PDPs that do not
1515         // respond (down, non-existent, etc)
1516         // do not block the PSP response to the AC, which would freeze the GUI
1517         // until all PDPs sequentially respond or time-out.
1518         Thread t = new Thread(new UpdatePdpThread(pdp, getPdpDataByPdpId(pdp)));
1519         if (CheckPDP.validateID(pdp.getId())) {
1520             t.start();
1521         }
1522     }
1523
1524     public void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext) {
1525         // kick off a thread to do an event notification for each PDP.
1526         // This needs to be on a separate thread so that PDPs that do not
1527         // respond (down, non-existent, etc)
1528         // do not block the PSP response to the AC, which would freeze the GUI
1529         // until all PDPs sequentially respond or time-out.
1530         Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, getPdpDataByPdpId(pdp)));
1531         if (CheckPDP.validateID(pdp.getId())) {
1532             t.start();
1533         }
1534     }
1535
1536     private void pdpChanged(OnapPDP pdp, List<Properties> pdpDataByGroup) {
1537         Thread t = new Thread(new UpdatePdpThread(pdp, pdpDataByGroup));
1538         if (CheckPDP.validateID(pdp.getId())) {
1539             t.start();
1540         }
1541     }
1542
1543     private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> pdpDataByGroup) {
1544         Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup));
1545         if (CheckPDP.validateID(pdp.getId())) {
1546             t.start();
1547         }
1548     }
1549
1550     private List<Properties> getPdpDataByGroup(OnapPDPGroup group) {
1551         DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1552         return dataToNotify.setPolicyConfigProperties(group);
1553     }
1554
1555     private List<Properties> getPdpDataByPdpId(OnapPDP pdp) {
1556         DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1557         return dataToNotify.setPolicyConfigProperties(pdp, papEngine);
1558     }
1559
1560     private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) throws IOException {
1561         LOGGER.info("Test request received");
1562         try {
1563             im.evaluateSanity();
1564             // If we make it this far, all is well
1565             String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
1566             LOGGER.info(message);
1567             loggingContext.transactionEnded();
1568             PolicyLogger.audit("Transaction Failed - See Error.log");
1569             response.setStatus(HttpServletResponse.SC_OK);
1570             return;
1571         } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) {
1572             String submsg;
1573             if (e instanceof ForwardProgressException) {
1574                 submsg = " is not making forward progress.";
1575             } else if (e instanceof AdministrativeStateException) {
1576                 submsg = " Administrative State is LOCKED.";
1577             } else {
1578                 submsg = " Standby Status is NOT PROVIDING SERVICE.";
1579             }
1580
1581             String message = "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: "
1582                     + e.getMessage();
1583             LOGGER.info(message, e);
1584             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1585             loggingContext.transactionEnded();
1586             PolicyLogger.audit("Transaction Failed - See Error.log");
1587             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1588             return;
1589         } catch (Exception e) {
1590             // A subsystem is not making progress, is locked, standby or is not
1591             // responding
1592             String eMsg = e.getMessage();
1593             if (eMsg == null) {
1594                 eMsg = "No Exception Message";
1595             }
1596             String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
1597                     + " Exception Message: " + eMsg;
1598             LOGGER.info(message, e);
1599             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1600             loggingContext.transactionEnded();
1601             PolicyLogger.audit("Transaction Failed - See Error.log");
1602             // Get the specific list of subsystems that failed
1603             String ssFailureList = null;
1604             for (String failedSS : papDependencyGroupsFlatArray) {
1605                 if (eMsg.contains(failedSS)) {
1606                     if (ssFailureList == null) {
1607                         ssFailureList = failedSS;
1608                     } else {
1609                         ssFailureList = ssFailureList.concat("," + failedSS);
1610                     }
1611                 }
1612             }
1613             if (ssFailureList == null) {
1614                 ssFailureList = "UnknownSubSystem";
1615             }
1616             response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
1617             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1618             return;
1619         }
1620     }
1621
1622     private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, String serviceName) {
1623         loggingContext.transactionStarted();
1624         loggingContext.setServiceName(serviceName);
1625         if (loggingContext.getRequestId() == null || "".equals(loggingContext.getRequestId())) {
1626             UUID requestID = UUID.randomUUID();
1627             loggingContext.setRequestId(requestID.toString());
1628             PolicyLogger.info(
1629                     "requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one");
1630         } else {
1631             PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')");
1632         }
1633     }
1634
1635     /*
1636      * Authorizing the PEP Requests.
1637      */
1638     private boolean authorizeRequest(HttpServletRequest request) {
1639         String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
1640         // Check if the Client is Authorized.
1641         return clientCredentials != null && clientCredentials.equalsIgnoreCase(environment);
1642     }
1643
1644     private static void loadWebapps() throws PAPException {
1645         if (actionHome == null || configHome == null) {
1646             Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS));
1647             // Sanity Check
1648             if (webappsPath == null) {
1649                 PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
1650                 throw new PAPException(
1651                         "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
1652             }
1653             Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config");
1654             Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action");
1655             if (Files.notExists(webappsPathConfig)) {
1656                 try {
1657                     Files.createDirectories(webappsPathConfig);
1658                 } catch (IOException e) {
1659                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1660                             "Failed to create config directory: " + webappsPathConfig.toAbsolutePath().toString());
1661                 }
1662             }
1663             if (Files.notExists(webappsPathAction)) {
1664                 try {
1665                     Files.createDirectories(webappsPathAction);
1666                 } catch (IOException e) {
1667                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
1668                             + webappsPathAction.toAbsolutePath().toString(), e);
1669                 }
1670             }
1671             actionHome = webappsPathAction.toString();
1672             configHome = webappsPathConfig.toString();
1673         }
1674     }
1675
1676     public static String getConfigHome() {
1677         try {
1678             loadWebapps();
1679         } catch (PAPException e) {
1680             LOGGER.debug(e);
1681             return null;
1682         }
1683         return configHome;
1684     }
1685
1686     private static void setConfigHome() {
1687         configHome = getConfigHome();
1688     }
1689
1690     public static String getActionHome() {
1691         try {
1692             loadWebapps();
1693         } catch (PAPException e) {
1694             LOGGER.debug(e);
1695             return null;
1696         }
1697         return actionHome;
1698     }
1699
1700     private static void setActionHome() {
1701         actionHome = getActionHome();
1702     }
1703
1704     public IntegrityAudit getIa() {
1705         return ia;
1706     }
1707
1708     public static String getPDPFile() {
1709         return XACMLPapServlet.pdpFile;
1710     }
1711
1712     public static String getPersistenceUnit() {
1713         return PERSISTENCE_UNIT;
1714     }
1715
1716     public static PAPPolicyEngine getPAPEngine() {
1717         return papEngine;
1718     }
1719
1720     public static PolicyDBDaoTransaction getDbDaoTransaction() {
1721         return policyDbDao.getNewTransaction();
1722     }
1723
1724     public static String getPapDbDriver() {
1725         return papDbDriver;
1726     }
1727
1728     public static void setPapDbDriver(String papDbDriver) {
1729         XACMLPapServlet.papDbDriver = papDbDriver;
1730     }
1731
1732     public static String getPapDbUrl() {
1733         return papDbUrl;
1734     }
1735
1736     public static void setPapDbUrl(String papDbUrl) {
1737         XACMLPapServlet.papDbUrl = papDbUrl;
1738     }
1739
1740     public static String getPapDbUser() {
1741         return papDbUser;
1742     }
1743
1744     public static void setPapDbUser(String papDbUser) {
1745         XACMLPapServlet.papDbUser = papDbUser;
1746     }
1747
1748     public static String getPapDbPassword() {
1749         return papDbPd;
1750     }
1751
1752     public static void setPapDbPassword(String papDbPassword) {
1753         XACMLPapServlet.papDbPd = papDbPassword;
1754     }
1755
1756     public static String getMsOnapName() {
1757         return msOnapName;
1758     }
1759
1760     public static void setMsOnapName(String msOnapName) {
1761         XACMLPapServlet.msOnapName = msOnapName;
1762     }
1763
1764     public static String getMsPolicyName() {
1765         return msPolicyName;
1766     }
1767
1768     public static void setMsPolicyName(String msPolicyName) {
1769         XACMLPapServlet.msPolicyName = msPolicyName;
1770     }
1771
1772     public OnapLoggingContext getBaseLoggingContext() {
1773         return baseLoggingContext;
1774     }
1775
1776     public void setBaseLoggingContext(OnapLoggingContext baseLoggingContext) {
1777         this.baseLoggingContext = baseLoggingContext;
1778     }
1779 }