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