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