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