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