Modify ONAP PAP REST classes basic checkstyle
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.UnsupportedEncodingException;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.InetAddress;
32 import java.net.MalformedURLException;
33 import java.net.SocketTimeoutException;
34 import java.net.URL;
35 import java.net.URLDecoder;
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.ArrayList;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.Properties;
45 import java.util.Scanner;
46 import java.util.Set;
47 import java.util.UUID;
48 import java.util.concurrent.CopyOnWriteArrayList;
49
50 import javax.persistence.EntityManagerFactory;
51 import javax.persistence.Persistence;
52 import javax.persistence.PersistenceException;
53 import javax.servlet.Servlet;
54 import javax.servlet.ServletConfig;
55 import javax.servlet.ServletException;
56 import javax.servlet.annotation.WebInitParam;
57 import javax.servlet.annotation.WebServlet;
58 import javax.servlet.http.HttpServlet;
59 import javax.servlet.http.HttpServletRequest;
60 import javax.servlet.http.HttpServletResponse;
61
62 import org.apache.commons.io.IOUtils;
63 import org.onap.policy.common.ia.IntegrityAudit;
64 import org.onap.policy.common.im.AdministrativeStateException;
65 import org.onap.policy.common.im.ForwardProgressException;
66 import org.onap.policy.common.im.IntegrityMonitor;
67 import org.onap.policy.common.im.IntegrityMonitorException;
68 import org.onap.policy.common.im.IntegrityMonitorProperties;
69 import org.onap.policy.common.im.StandbyStatusException;
70 import org.onap.policy.common.logging.ONAPLoggingContext;
71 import org.onap.policy.common.logging.ONAPLoggingUtils;
72 import org.onap.policy.common.logging.eelf.MessageCodes;
73 import org.onap.policy.common.logging.eelf.PolicyLogger;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
77 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
78 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
79 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
80 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
81 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
82 import org.onap.policy.rest.XACMLRest;
83 import org.onap.policy.rest.XACMLRestProperties;
84 import org.onap.policy.rest.dao.PolicyDBException;
85 import org.onap.policy.utils.CryptoUtils;
86 import org.onap.policy.utils.PolicyUtils;
87 import org.onap.policy.xacml.api.XACMLErrorConstants;
88 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
89 import org.onap.policy.xacml.api.pap.OnapPDP;
90 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
91 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
92 import org.onap.policy.xacml.std.pap.StdPDP;
93 import org.onap.policy.xacml.std.pap.StdPDPGroup;
94 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
95 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
96 import org.onap.policy.xacml.std.pap.StdPDPStatus;
97
98 import com.att.research.xacml.api.pap.PAPException;
99 import com.att.research.xacml.api.pap.PDPPolicy;
100 import com.att.research.xacml.api.pap.PDPStatus;
101 import com.att.research.xacml.util.FactoryException;
102 import com.att.research.xacml.util.XACMLProperties;
103 import com.fasterxml.jackson.databind.ObjectMapper;
104 import com.google.common.base.Splitter;
105
106 /**
107  * Servlet implementation class XacmlPapServlet
108  */
109 @WebServlet(
110         description = "Implements the XACML PAP RESTful API.",
111         urlPatterns = { "/" },
112         loadOnStartup=1,
113         initParams = {
114             @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
115         })
116 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
117     private static final long serialVersionUID = 1L;
118     private static final Logger LOGGER  = FlexLogger.getLogger(XACMLPapServlet.class);
119     // audit (transaction) LOGGER
120     private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
121     //Persistence Unit for JPA
122     private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
123     private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
124     // Client Headers.
125     private static final String ENVIRONMENT_HEADER = "Environment";
126     private static final String ADD_GROUP_ERROR = "addGroupError";
127     private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
128
129     private static final String REGEX = "[0-9a-zA-Z._ ]*";
130
131     /*
132      * List of Admin Console URLs.
133      * Used to send notifications when configuration changes.
134      *
135      * The CopyOnWriteArrayList *should* protect from concurrency errors.
136      * This list is seldom changed but often read, so the costs of this approach make sense.
137      */
138     private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
139
140     private static String configHome;
141     private static String actionHome;
142     /*
143      * This PAP instance's own URL.
144      * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
145      */
146     private static String papURL = null;
147     // The heartbeat thread.
148     private static Heartbeat heartbeat = null;
149     private static Thread heartbeatThread = null;
150     //The entity manager factory for JPA access
151     private static EntityManagerFactory emf;
152     private static PolicyDBDao policyDBDao;
153     /*
154      * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
155      */
156     private static PAPPolicyEngine papEngine = null;
157     /*
158      * These are the parameters needed for DB access from the PAP
159      */
160     private static int papIntegrityAuditPeriodSeconds = -1;
161     private static String papDbDriver = null;
162     private static String papDbUrl = null;
163     private static String papDbUser = null;
164     private static String papDbPassword = null;
165     private static String papResourceName = null;
166     private static String[] papDependencyGroupsFlatArray = null;
167     private static String environment = null;
168     private static String pdpFile = null;
169
170     private transient IntegrityMonitor im;
171     private transient IntegrityAudit ia;
172
173     //MicroService Model Properties
174     private static String msOnapName;
175     private static String msPolicyName;
176     /*
177      * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
178      * this servlet starts. Its configurable by the admin.
179      */
180     private static transient Thread initiateThread = null;
181     private transient ONAPLoggingContext baseLoggingContext = null;
182
183     /**
184      * @see HttpServlet#HttpServlet()
185      */
186     public XACMLPapServlet() {
187         super();
188     }
189
190     /**
191      * @see Servlet#init(ServletConfig)
192      */
193     public void init(ServletConfig config) throws ServletException {
194         try {
195             // Logging
196             baseLoggingContext = new ONAPLoggingContext();
197             // fixed data that will be the same in all logging output goes here
198             try {
199                 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
200                 baseLoggingContext.setServer(hostname);
201             } catch (UnknownHostException e) {
202                 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
203             }
204             // Initialize
205             XACMLRest.xacmlInit(config);
206             // Load the properties
207             XACMLRest.loadXacmlProperties(null, null);
208             /*
209              * Retrieve the property values
210              */
211             setCommonProperties();
212             String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
213             if(papSiteName == null){
214                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
215                 throw new PAPException("papSiteName is null");
216             }
217             String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
218             if(papNodeType == null){
219                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
220                 throw new PAPException("papNodeType is null");
221             }
222             //Integer will throw an exception of anything is missing or unrecognized
223             int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
224             int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
225             int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
226             //Boolean will default to false if anything is missing or unrecognized
227             boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
228             boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
229             String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
230             if(papDependencyGroups == null){
231                 throw new PAPException("papDependencyGroups is null");
232             }
233             setPAPDependencyGroups(papDependencyGroups);
234             //Integer will throw an exception of anything is missing or unrecognized
235             int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
236             int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
237             int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
238             int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
239             LOGGER.debug("\n\n\n**************************************"
240                     + "\n*************************************"
241                     + "\n"
242                     + "\n   papDbDriver = " + papDbDriver
243                     + "\n   papDbUrl = " + papDbUrl
244                     + "\n   papDbUser = " + papDbUser
245                     + "\n   papTransWait = " + papTransWait
246                     + "\n   papTransTimeout = " + papTransTimeout
247                     + "\n   papAuditTimeout = " + papAuditTimeout
248                     + "\n   papAuditFlag = " + papAuditFlag
249                     + "\n   papFileSystemAudit = " + papFileSystemAudit
250                     + "\n       papResourceName = " + papResourceName
251                     + "\n       fpMonitorInterval = " + fpMonitorInterval
252                     + "\n       failedCounterThreshold = " + failedCounterThreshold
253                     + "\n       testTransInterval = " + testTransInterval
254                     + "\n       writeFpcInterval = " + writeFpcInterval
255                     + "\n       papSiteName = " + papSiteName
256                     + "\n       papNodeType = " + papNodeType
257                     + "\n       papDependencyGroupsList = " + papDependencyGroups
258                     + "\n   papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
259                     + "\n\n*************************************"
260                     + "\n**************************************");
261             // Pull custom persistence settings
262             Properties properties;
263             try {
264                 properties = XACMLProperties.getProperties();
265                 LOGGER.debug("\n\n\n**************************************"
266                         + "\n**************************************"
267                         + "\n\n"
268                         + "properties = " + properties
269                         + "\n\n**************************************");
270             } catch (IOException e) {
271                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
272                         + "XACMLProperties.getProperties()");
273                 throw new ServletException(e.getMessage(), e.getCause());
274             }
275             // Create an IntegrityMonitor
276             if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
277                 properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
278             }
279             im = IntegrityMonitor.getInstance(papResourceName,properties);
280             // Create an IntegrityAudit
281             ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
282             ia.startAuditThread();
283             // Create the entity manager factory
284             setEMF(properties);
285             // we are about to call the PDPs and give them their configuration.
286             // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
287             setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
288             //Create the policyDBDao
289             setPolicyDBDao();
290             // Load our PAP engine, first create a factory
291             ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
292             // The factory knows how to go about creating a PAP Engine
293             setPAPEngine((PAPPolicyEngine) factory.newEngine());
294             PolicyDBDaoTransaction addNewGroup = null;
295             if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
296                 try {
297                     addNewGroup = policyDBDao.getNewTransaction();
298                     OnapPDPGroup group = papEngine.getDefaultGroup();
299                     addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
300                             "automaticallyAdded");
301                     addNewGroup.commitTransaction();
302                     addNewGroup = policyDBDao.getNewTransaction();
303                     addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
304                     addNewGroup.commitTransaction();
305                 } catch (Exception e) {
306                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
307                             " Error creating new default group in the database");
308                     if (addNewGroup != null) {
309                         addNewGroup.rollbackTransaction();
310                     }
311                 }
312             }
313             policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
314             if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
315                 /*
316                  * Auditing the local File System groups to be in sync with the Database
317                  */
318
319                 //get an AuditTransaction to lock out all other transactions
320                 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
321
322                 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
323                 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
324                 //get the current filesystem group and update from the database if needed
325                 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
326                 StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
327                 if(updatedGroup!=null) {
328                     papEngine.updateGroup(updatedGroup);
329                 }    
330                 LOGGER.info("PapServlet:  updated group is " + papEngine.getDefaultGroup().toString());
331                 
332                 //release the transaction lock
333                 auditTrans.close();
334             }
335
336             // Sanity check for URL.
337             if (XACMLPapServlet.papURL == null) {
338                 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
339             }
340             // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
341             // to all its known PDP nodes.
342             if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
343                 startInitiateThreadService(new Thread(this));
344             }
345             // After startup, the PAP does Heartbeat's to each of the PDPs periodically
346             startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
347
348         } catch (FactoryException | PAPException e) {
349             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
350             throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
351         } catch (Exception e) {
352             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
353             throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
354         }
355     }
356
357     private static void startInitiateThreadService(Thread thread) {
358         initiateThread = thread;
359         initiateThread.start();
360     }
361
362     private static void mapperWriteValue(ObjectMapper mapper,  HttpServletResponse response, Object value) {
363         try {
364             mapper.writeValue(response.getOutputStream(), value);
365         } catch (Exception e) {
366             LOGGER.error(e);
367         }
368     }
369
370     private static void startHeartBeatService(Heartbeat heartbeat) {
371         XACMLPapServlet.heartbeat = heartbeat;
372         XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
373         XACMLPapServlet.heartbeatThread.start();
374     }
375
376     private static void setPolicyDBDao() throws ServletException {
377         try {
378             policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
379         } catch (Exception e) {
380             throw new ServletException("Unable to Create Policy DBDao Instance",e);
381         }
382     }
383
384     private static void setEMF(Properties properties) throws ServletException {
385         emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
386         if (emf == null) {
387             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
388                     + PERSISTENCE_UNIT);
389             throw new ServletException("Unable to create Entity Manager Factory");
390         }
391     }
392
393     private static void setPAPURL(String papURL) {
394         XACMLPapServlet.papURL = papURL;
395     }
396
397     private static void setPAPEngine(PAPPolicyEngine newEngine) {
398         XACMLPapServlet.papEngine = newEngine;
399     }
400
401     private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
402         try{
403             //Now we have flattened the array into a simple comma-separated list
404             papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
405             //clean up the entries
406             for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
407                 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
408             }
409             try{
410                 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
411                     papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
412                 }
413             }catch(Exception e){
414                 String msg = "integrity_audit_period_seconds ";
415                 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
416                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
417                 throw e;
418             }
419         }catch(Exception e){
420             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
421             throw new PAPException(e);
422         }
423     }
424
425     private static void setCommonProperties() throws PAPException {
426         setConfigHome();
427         setActionHome();
428         papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
429         if(papDbDriver == null){
430             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
431             throw new PAPException("papDbDriver is null");
432         }
433         setPapDbDriver(papDbDriver);
434         papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
435         if(papDbUrl == null){
436             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
437             throw new PAPException("papDbUrl is null");
438         }
439         setPapDbUrl(papDbUrl);
440         papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
441         if(papDbUser == null){
442             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
443             throw new PAPException("papDbUser is null");
444         }
445         setPapDbUser(papDbUser);
446         papDbPassword = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""));
447         if(papDbPassword == null){
448             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
449             throw new PAPException("papDbPassword is null");
450         }
451         setPapDbPassword(papDbPassword);
452         papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
453         if(papResourceName == null){
454             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
455             throw new PAPException("papResourceName is null");
456         }
457         environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
458         //Micro Service Properties
459         msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
460         setMsOnapName(msOnapName);
461         msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
462         setMsPolicyName(msPolicyName);
463         // PDPId File location 
464         XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
465         if (XACMLPapServlet.pdpFile == null) {
466             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
467                 + XACMLRestProperties.PROP_PDP_IDFILE);
468             throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
469         }
470     }
471
472     /**
473      * Thread used only during PAP startup to initiate change messages to all known PDPs.
474      * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
475      */
476     @Override
477     public void run() {
478         // send the current configuration to all the PDPs that we know about
479         changed();
480     }
481
482     /**
483      * @see Servlet#destroy()
484      *
485      * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
486      * For now we assume that we do care.
487      */
488     @Override
489     public void destroy() {
490         // Make sure our threads are destroyed
491         if (XACMLPapServlet.heartbeatThread != null) {
492             // stop the heartbeat
493             try {
494                 if (XACMLPapServlet.heartbeat != null) {
495                     XACMLPapServlet.heartbeat.terminate();
496                 }
497                 XACMLPapServlet.heartbeatThread.interrupt();
498                 XACMLPapServlet.heartbeatThread.join();
499             } catch (InterruptedException e) {
500                 XACMLPapServlet.heartbeatThread.interrupt();
501                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
502             }
503         }
504         if (initiateThread != null) {
505             try {
506                 initiateThread.interrupt();
507                 initiateThread.join();
508             } catch (InterruptedException e) {
509                 initiateThread.interrupt();
510                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
511             }
512         }
513     }
514
515     /**
516      * Called by:
517      *  - PDP nodes to register themselves with the PAP, and
518      *  - Admin Console to make changes in the PDP Groups.
519      *
520      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
521      */
522     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
523         ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
524         loggingContext.transactionStarted();
525         loggingContext.setServiceName("PAP.post");
526         if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
527             UUID requestID = UUID.randomUUID();
528             loggingContext.setRequestID(requestID.toString());
529             PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
530         } else {
531             PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
532         }
533         PolicyDBDaoTransaction pdpTransaction = null;
534         loggingContext.metricStarted();
535         try {
536             im.startTransaction();
537             loggingContext.metricEnded();
538             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
539         } catch (AdministrativeStateException ae){
540             String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
541                     + " state of " + im.getStateManager().getAdminState()
542                     + "\n Exception Message: " +  PolicyUtils.CATCH_EXCEPTION;
543             LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
544             loggingContext.metricEnded();
545             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
546             loggingContext.transactionEnded();
547             PolicyLogger.audit("Transaction Failed - See Error.log");
548             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
549             return;
550         }catch (StandbyStatusException se) {
551             String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
552                     + " of " + im.getStateManager().getStandbyStatus()
553                     + "\n Exception Message: " + se.getMessage();
554             LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
555             loggingContext.metricEnded();
556             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
557             loggingContext.transactionEnded();
558             PolicyLogger.audit("Transaction Failed - See Error.log");
559             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
560             return;
561         } catch (IntegrityMonitorException e) {
562             String message = "POST interface called for PAP " + papResourceName + " but an exception occurred"
563                     + "\n Exception Message: " + e.getMessage();
564             LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e);
565             loggingContext.metricEnded();
566             PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
567             loggingContext.transactionEnded();
568             PolicyLogger.audit("Transaction Failed - See Error.log");
569             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
570             return;
571         }
572         try {
573             loggingContext.metricStarted();
574             XACMLRest.dumpRequest(request);
575             loggingContext.metricEnded();
576             PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
577             // since getParameter reads the content string, explicitly get the content before doing that.
578             // Simply getting the inputStream seems to protect it against being consumed by getParameter.
579             request.getInputStream();
580             String groupId = request.getParameter("groupId");
581             String apiflag = request.getParameter("apiflag");
582             if(groupId != null) {
583                 // Is this from the Admin Console or API?
584                 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
585                     // this is from the API so we need to check the client credentials before processing the request
586                     if(!authorizeRequest(request)){
587                         String message = "PEP not Authorized for making this Request!!";
588                         PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
589                         loggingContext.transactionEnded();
590                         PolicyLogger.audit("Transaction Failed - See Error.log");
591                         setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
592                         im.endTransaction();
593                         return;
594                     }
595                 }
596                 loggingContext.metricStarted();
597                 doACPost(request, response, groupId, loggingContext);
598                 loggingContext.metricEnded();
599                 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
600                 loggingContext.transactionEnded();
601                 PolicyLogger.audit("Transaction Ended Successfully");
602                 im.endTransaction();
603                 return;
604             }
605             // Request is from a PDP asking for its config.
606             loggingContext.setServiceName("PDP:PAP.register");
607             // Get the PDP's ID
608             String id = this.getPDPID(request);
609             String jmxport = this.getPDPJMX(request);
610             LOGGER.info("Request(doPost) from PDP coming up: " + id);
611             // Get the PDP Object
612             OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
613             // Is it known?
614             if (pdp == null) {
615                 LOGGER.info("Unknown PDP: " + id);
616                 // Check PDP ID
617                 if(CheckPDP.validateID(id)){
618                     pdpTransaction = policyDBDao.getNewTransaction();
619                     try {
620                         pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
621                         XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
622                     } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
623                         pdpTransaction.rollbackTransaction();
624                         String message = "Failed to create new PDP for id: " + id;
625                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
626                         loggingContext.transactionEnded();
627                         PolicyLogger.audit("Transaction Failed - See Error.log");
628                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
629                         im.endTransaction();
630                         return;
631                     }
632                     // get the PDP we just created
633                     try{
634                         pdp = XACMLPapServlet.papEngine.getPDP(id);
635                     }catch(PAPException e){
636                         LOGGER.error(e);
637                     }
638                     if (pdp == null) {
639                         if(pdpTransaction != null){
640                             pdpTransaction.rollbackTransaction();
641                         }
642                         String message = "Failed to create new PDP for id: " + id;
643                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
644                         loggingContext.transactionEnded();
645                         PolicyLogger.audit("Transaction Failed - See Error.log");
646                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
647                         im.endTransaction();
648                         return;
649                     }
650                 } else {
651                     String message = "PDP is Unauthorized to Connect to PAP: "+ id;
652                     loggingContext.transactionEnded();
653                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
654                     setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
655                     PolicyLogger.audit("Transaction Failed - See Error.log");
656                     im.endTransaction();
657                     return;
658                 }
659                 try{
660                     loggingContext.metricStarted();
661                     pdpTransaction.commitTransaction();
662                     loggingContext.metricEnded();
663                     PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
664                 } catch(Exception e){
665                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
666                 }
667             }
668             if (jmxport != null && jmxport != ""){
669                 try{
670                     ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
671                 }catch(NumberFormatException e){
672                     LOGGER.error(e);
673                 }
674             }
675             // Get the PDP's Group
676             OnapPDPGroup group =null;
677             try{
678                 group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
679             }catch(PAPException e){
680                 LOGGER.error(e);
681             }
682             if (group == null) {
683                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
684                 loggingContext.transactionEnded();
685                 PolicyLogger.audit("Transaction Failed - See Error.log");
686                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
687                 im.endTransaction();
688                 return;
689             }
690             // Determine what group the PDP node is in and get
691             // its policy/pip properties.
692             Properties policies = group.getPolicyProperties();
693             Properties pipconfig = group.getPipConfigProperties();
694             // Get the current policy/pip configuration that the PDP has
695             Properties pdpProperties = new Properties();
696             try{
697                 pdpProperties.load(request.getInputStream());
698             }catch(IOException e){
699                 LOGGER.error(e);
700             }
701             LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
702             LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
703             LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
704             // Validate the node's properties
705             boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
706             // Send back current configuration
707             if (isCurrent == false) {
708                 // Tell the PDP we are sending back the current policies/pip config
709                 LOGGER.info("PDP configuration NOT current.");
710                 if (policies != null) {
711                     // Put URL's into the properties in case the PDP needs to
712                     // retrieve them.
713                     this.populatePolicyURL(request.getRequestURL(), policies);
714                     // Copy the properties to the output stream
715                     try{
716                         policies.store(response.getOutputStream(), "");
717                     }catch(IOException e){
718                         LOGGER.error(e);
719                     }
720                 }
721                 if (pipconfig != null) {
722                     // Copy the properties to the output stream
723                     try{
724                         pipconfig.store(response.getOutputStream(), "");
725                     }catch(IOException e){
726                         LOGGER.error(e);
727                     }
728                 }
729                 // We are good - and we are sending them information
730                 response.setStatus(HttpServletResponse.SC_OK);
731                 try{
732                     setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
733                 }catch(PAPException e){
734                     LOGGER.error(e);
735                 }
736             } else {
737                 // Tell them they are good
738                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
739                 try{
740                     setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
741                 }catch(PAPException e){
742                     LOGGER.error(e);
743                 }
744             }
745             // tell the AC that something changed
746             loggingContext.metricStarted();
747             notifyAC();
748             loggingContext.metricEnded();
749             PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
750             loggingContext.transactionEnded();
751             auditLogger.info("Success");
752             PolicyLogger.audit("Transaction Ended Successfully");
753         } catch (PAPException | IOException | NumberFormatException e) {
754             if(pdpTransaction != null){
755                 pdpTransaction.rollbackTransaction();
756             }
757             LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
758             loggingContext.transactionEnded();
759             PolicyLogger.audit("Transaction Failed - See Error.log");
760             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
761             im.endTransaction();
762             return;
763         }
764         //Catch anything that fell through
765         loggingContext.transactionEnded();
766         PolicyLogger.audit("Transaction Ended");
767         im.endTransaction();
768     }
769
770     private void setResponseError(HttpServletResponse response,int responseCode, String message) {
771         try {
772             if(message != null && !message.isEmpty()){
773                    response.sendError(responseCode, message);
774             }
775         } catch (IOException e) {
776             LOGGER.error("Error setting Error response Header ", e);
777         }
778         return;
779     }
780
781     /**
782      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
783      */
784     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
785         ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
786         loggingContext.transactionStarted();
787         loggingContext.setServiceName("PAP.get");
788         if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
789             UUID requestID = UUID.randomUUID();
790             loggingContext.setRequestID(requestID.toString());
791             PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
792         } else {
793             PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
794         }
795             loggingContext.metricStarted();
796             XACMLRest.dumpRequest(request);
797             loggingContext.metricEnded();
798             PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
799             String pathInfo = request.getRequestURI();
800             LOGGER.info("path info: " + pathInfo);
801             if (pathInfo != null){
802                 //DO NOT do a im.startTransaction for the test request
803                 if (pathInfo.equals("/pap/test")) {
804                     try {
805                         testService(loggingContext, response);
806                     } catch (IOException e) {
807                         LOGGER.debug(e);
808                     }
809                     return;
810                 }
811             }
812             //This im.startTransaction() covers all other Get transactions
813             try {
814                 loggingContext.metricStarted();
815                 im.startTransaction();
816                 loggingContext.metricEnded();
817                 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
818             } catch (AdministrativeStateException ae){
819                 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
820                         + " state of " + im.getStateManager().getAdminState()
821                         + "\n Exception Message: " + ae.getMessage();
822                 LOGGER.info(message, ae);
823                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
824                 loggingContext.transactionEnded();
825                 PolicyLogger.audit("Transaction Failed - See Error.log");
826                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
827                 return;
828             }catch (StandbyStatusException se) {
829                 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
830                         + " of " + im.getStateManager().getStandbyStatus()
831                         + "\n Exception Message: " + se.getMessage();
832                 LOGGER.info(message, se);
833                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
834                 loggingContext.transactionEnded();
835                 PolicyLogger.audit("Transaction Failed - See Error.log");
836                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
837                 return;
838             } catch (IntegrityMonitorException e) {
839                 String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
840                         + "\n Exception Message: " + e.getMessage();
841                 LOGGER.info(message, e);
842                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
843                 loggingContext.transactionEnded();
844                 PolicyLogger.audit("Transaction Failed - See Error.log");
845                 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
846                 return;
847             }
848             // Request from the API to get the gitPath
849             String apiflag = request.getParameter("apiflag");
850             if (apiflag!=null) {
851                 if(authorizeRequest(request)){
852                     APIRequestHandler apiRequestHandler = new APIRequestHandler();
853                     try{
854                         loggingContext.metricStarted();
855                         apiRequestHandler.doGet(request,response, apiflag);
856                         loggingContext.metricEnded();
857                         PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
858                     }catch(IOException e){
859                         LOGGER.error(e);
860                     }
861                     loggingContext.transactionEnded();
862                     PolicyLogger.audit("Transaction Ended Successfully");
863                     im.endTransaction();
864                     return;
865                 } else {
866                     String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
867                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
868                     loggingContext.transactionEnded();
869                     PolicyLogger.audit("Transaction Failed - See Error.log");
870                     setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
871                     im.endTransaction();
872                     return;
873                 }
874             }
875             // Is this from the Admin Console?
876             String groupId = request.getParameter("groupId");
877             if (groupId != null) {
878                 // this is from the Admin Console, so handle separately
879                 try{
880                     loggingContext.metricStarted();
881                     doACGet(request, response, groupId, loggingContext);
882                     loggingContext.metricEnded();
883                     PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
884                 } catch(IOException e){
885                     LOGGER.error(e);
886                 }
887                 loggingContext.transactionEnded();
888                 PolicyLogger.audit("Transaction Ended Successfully");
889                 im.endTransaction();
890                 return;
891             }
892             // Get the PDP's ID
893             String id = this.getPDPID(request);
894             LOGGER.info("doGet from: " + id);
895             // Get the PDP Object
896             OnapPDP pdp = null;
897             try{
898                 pdp = XACMLPapServlet.papEngine.getPDP(id);
899             }catch(PAPException e){
900                 LOGGER.error(e);
901             }
902             // Is it known?
903             if (pdp == null) {
904                 // Check if request came from localhost
905                 if (request.getRemoteHost().equals("localhost") ||
906                         request.getRemoteHost().equals(request.getLocalAddr())) {
907                     // Return status information - basically all the groups
908                     loggingContext.setServiceName("PAP.getGroups");
909                     Set<OnapPDPGroup> groups = null;
910                     try {
911                         groups = papEngine.getOnapPDPGroups();
912                     } catch(PAPException e) {
913                         LOGGER.debug(e);
914                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
915                         loggingContext.transactionEnded();
916                         PolicyLogger.audit("Transaction Failed - See Error.log");
917                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
918                         im.endTransaction();
919                         return;
920                     }
921                     // convert response object to JSON and include in the response
922                     mapperWriteValue(new ObjectMapper(), response,  groups);
923                     response.setHeader("content-type", "application/json");
924                     response.setStatus(HttpServletResponse.SC_OK);
925                     loggingContext.transactionEnded();
926                     PolicyLogger.audit("Transaction Ended Successfully");
927                     im.endTransaction();
928                     return;
929                 }
930                 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
931                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
932                 loggingContext.transactionEnded();
933                 PolicyLogger.audit("Transaction Failed - See Error.log");
934                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
935                 im.endTransaction();
936                 return;
937             }
938             loggingContext.setServiceName("PAP.getPolicy");
939             // Get the PDP's Group
940             OnapPDPGroup group = null;
941             try {
942                 group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
943             } catch (PAPException e) {
944                 LOGGER.error(e);
945             }
946             if (group == null) {
947                 String message = "No group associated with pdp " + pdp.getId();
948                 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
949                 loggingContext.transactionEnded();
950                 PolicyLogger.audit("Transaction Failed - See Error.log");
951                 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
952                 im.endTransaction();
953                 return;
954             }
955             // Which policy do they want?
956             String policyId = request.getParameter("id");
957             if (policyId == null) {
958                 String message = "Did not specify an id for the policy";
959                 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
960                 loggingContext.transactionEnded();
961                 PolicyLogger.audit("Transaction Failed - See Error.log");
962                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
963                 im.endTransaction();
964                 return;
965             }
966             PDPPolicy policy = group.getPolicy(policyId);
967             if (policy == null) {
968                 String message = "Unknown policy: " + policyId;
969                 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
970                 loggingContext.transactionEnded();
971                 PolicyLogger.audit("Transaction Failed - See Error.log");
972                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
973                 im.endTransaction();
974                 return;
975             }
976             try{
977                 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
978                         + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
979             } catch (PAPException| IOException e){
980                 LOGGER.error(e);
981             }
982             try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
983                 // Send the policy back
984                 IOUtils.copy(is, os);
985                 response.setStatus(HttpServletResponse.SC_OK);
986                 loggingContext.transactionEnded();
987                 auditLogger.info("Success");
988                 PolicyLogger.audit("Transaction Ended Successfully");
989             } catch (IOException e) {
990                 String message = "Failed to open policy id " + policyId;
991                 LOGGER.debug(e);
992                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
993                 loggingContext.transactionEnded();
994                 PolicyLogger.audit("Transaction Failed - See Error.log");
995                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
996             }
997         loggingContext.transactionEnded();
998         PolicyLogger.audit("Transaction Ended");
999         im.endTransaction();
1000     }
1001
1002     /**
1003      * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
1004      */
1005     protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1006         ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1007         loggingContext.transactionStarted();
1008         loggingContext.setServiceName("PAP.put");
1009         if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1010             UUID requestID = UUID.randomUUID();
1011             loggingContext.setRequestID(requestID.toString());
1012             PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
1013         } else {
1014             PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
1015         }
1016         try {
1017             loggingContext.metricStarted();
1018             im.startTransaction();
1019             loggingContext.metricEnded();
1020             PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
1021         } catch (IntegrityMonitorException e) {
1022             String message = "PUT interface called for PAP " + papResourceName;
1023             if (e instanceof AdministrativeStateException) {
1024                 message += " but it has an Administrative state of "
1025                     + im.getStateManager().getAdminState();
1026             } else if (e instanceof StandbyStatusException) {
1027                 message += " but it has a Standby Status of "
1028                     + im.getStateManager().getStandbyStatus();
1029             } else {
1030                 message += " but an exception occurred";
1031
1032             }
1033             message += "\n Exception Message: " + e.getMessage();
1034
1035             LOGGER.info(message, e);
1036             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1037             loggingContext.transactionEnded();
1038             PolicyLogger.audit("Transaction Failed - See Error.log");
1039             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1040             return;
1041         }
1042
1043         loggingContext.metricStarted();
1044         XACMLRest.dumpRequest(request);
1045         loggingContext.metricEnded();
1046         PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1047         //need to check if request is from the API or Admin console
1048         String apiflag = request.getParameter("apiflag");
1049         //This would occur if a PolicyDBDao notification was received
1050         String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1051         if(policyDBDaoRequestUrl != null){
1052             LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
1053             String policyDBDaoRequestEntityId = request.getParameter("entityid");
1054             String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1055             String policyDBDaoRequestExtraData = request.getParameter("extradata");
1056             if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1057                 setResponseError(response,400, "entityid or entitytype not supplied");
1058                 loggingContext.transactionEnded();
1059                 PolicyLogger.audit("Transaction Ended Successfully");
1060                 im.endTransaction();
1061                 return;
1062             }
1063             loggingContext.metricStarted();
1064             LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1065             policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1066             loggingContext.metricEnded();
1067             PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1068             response.setStatus(200);
1069             loggingContext.transactionEnded();
1070             PolicyLogger.audit("Transaction Ended Successfully");
1071             im.endTransaction();
1072             return;
1073         }
1074         /*
1075          * Request for ImportService
1076          */
1077         String importService = request.getParameter("importService");
1078         if (importService != null) {
1079             if(authorizeRequest(request)){
1080                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1081                 try{
1082                     loggingContext.metricStarted();
1083                     apiRequestHandler.doPut(request, response, importService);
1084                     loggingContext.metricEnded();
1085                     PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1086                 }catch(IOException e){
1087                     LOGGER.error(e);
1088                 }
1089                 im.endTransaction();
1090                 return;
1091             } else {
1092                 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1093                 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1094                 loggingContext.transactionEnded();
1095                 PolicyLogger.audit("Transaction Failed - See Error.log");
1096                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1097                 return;
1098             }
1099         }
1100         //
1101         // See if this is Admin Console registering itself with us
1102         //
1103         String acURLString = request.getParameter("adminConsoleURL");
1104         if (acURLString != null) {
1105             loggingContext.setServiceName("AC:PAP.register");
1106             // remember this Admin Console for future updates
1107             if ( ! adminConsoleURLStringList.contains(acURLString)) {
1108                 adminConsoleURLStringList.add(acURLString);
1109             }
1110             if (LOGGER.isDebugEnabled()) {
1111                 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1112             }
1113             response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1114             loggingContext.transactionEnded();
1115             auditLogger.info("Success");
1116             PolicyLogger.audit("Transaction Ended Successfully");
1117             im.endTransaction();
1118             return;
1119         }
1120         /*
1121          * This is to update the PDP Group with the policy/policies being pushed
1122          * Part of a 2 step process to push policies to the PDP that can now be done
1123          * From both the Admin Console and the PolicyEngine API
1124          */
1125         String groupId = request.getParameter("groupId");
1126         if (groupId != null) {
1127             if(apiflag!=null){
1128                 if(!authorizeRequest(request)){
1129                     String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1130                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1131                     loggingContext.transactionEnded();
1132                     PolicyLogger.audit("Transaction Failed - See Error.log");
1133                     setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1134                     return;
1135                 }
1136                 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1137                     try{
1138                         updateGroupsFromAPI(request, response, groupId, loggingContext);
1139                     }catch(IOException e){
1140                         LOGGER.error(e);
1141                     }
1142                     loggingContext.transactionEnded();
1143                     PolicyLogger.audit("Transaction Ended Successfully");
1144                     im.endTransaction();
1145                     return;
1146                 }
1147             }
1148             // this is from the Admin Console, so handle separately
1149             try {
1150                 loggingContext.metricEnded();
1151                 doACPut(request, response, groupId, loggingContext);
1152                 loggingContext.metricEnded();
1153                 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1154             } catch (IOException e) {
1155                 LOGGER.error(e);
1156             }
1157             loggingContext.transactionEnded();
1158             PolicyLogger.audit("Transaction Ended Successfully");
1159             im.endTransaction();
1160             return;
1161         }
1162         //
1163         // Request is for policy validation and creation
1164         //
1165         if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1166             // this request is from the Admin Console
1167             SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1168             try{
1169                 loggingContext.metricStarted();
1170                 savePolicyHandler.doPolicyAPIPut(request, response);
1171                 loggingContext.metricEnded();
1172                 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1173             } catch (IOException e) {
1174                 LOGGER.error(e);
1175             }
1176             loggingContext.transactionEnded();
1177             PolicyLogger.audit("Transaction Ended Successfully");
1178             im.endTransaction();
1179             return;
1180         } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1181             // this request is from the Policy Creation API
1182             if(authorizeRequest(request)){
1183                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1184                 try{
1185                     loggingContext.metricStarted();
1186                     apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1187                     loggingContext.metricEnded();
1188                     PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1189                 } catch (IOException e) {
1190                     LOGGER.error(e);
1191                 }
1192                 loggingContext.transactionEnded();
1193                 PolicyLogger.audit("Transaction Ended Successfully");
1194                 im.endTransaction();
1195                 return;
1196             } else {
1197                 String message = "PEP not Authorized for making this Request!!";
1198                 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1199                 loggingContext.transactionEnded();
1200                 PolicyLogger.audit("Transaction Failed - See Error.log");
1201                 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1202                 im.endTransaction();
1203                 return;
1204             }
1205         }
1206         // We do not expect anything from anywhere else.
1207         // This method is here in case we ever need to support other operations.
1208         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1209         loggingContext.transactionEnded();
1210         PolicyLogger.audit("Transaction Failed - See Error.log");
1211         setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1212         loggingContext.transactionEnded();
1213         PolicyLogger.audit("Transaction Failed - See error.log");
1214         im.endTransaction();
1215     }
1216
1217     /**
1218      * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1219      */
1220     protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1221         ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1222         loggingContext.transactionStarted();
1223         loggingContext.setServiceName("PAP.delete");
1224         if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1225             UUID requestID = UUID.randomUUID();
1226             loggingContext.setRequestID(requestID.toString());
1227             PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1228         } else {
1229             PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1230         }
1231         try {
1232             loggingContext.metricStarted();
1233             im.startTransaction();
1234             loggingContext.metricEnded();
1235             PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1236         } catch (AdministrativeStateException ae){
1237             String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1238                     + " state of " + im.getStateManager().getAdminState()
1239                     + "\n Exception Message: " + ae.getMessage();
1240             LOGGER.info(message, ae);
1241             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1242             loggingContext.transactionEnded();
1243             PolicyLogger.audit("Transaction Failed - See Error.log");
1244             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1245             return;
1246         }catch (StandbyStatusException se) {
1247             String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1248                     + " of " + im.getStateManager().getStandbyStatus()
1249                     + "\n Exception Message: " + se.getMessage();
1250             LOGGER.info(message, se);
1251             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1252             loggingContext.transactionEnded();
1253             PolicyLogger.audit("Transaction Failed - See Error.log");
1254             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1255             return;
1256         } catch (IntegrityMonitorException e) {
1257             String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
1258                     + "\n Exception Message: " + e.getMessage();
1259             LOGGER.info(message, e);
1260             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1261             loggingContext.transactionEnded();
1262             PolicyLogger.audit("Transaction Failed - See Error.log");
1263             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1264             return;
1265         }
1266         loggingContext.metricStarted();
1267         XACMLRest.dumpRequest(request);
1268         loggingContext.metricEnded();
1269         PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1270         String groupId = request.getParameter("groupId");
1271         String apiflag = request.getParameter("apiflag");
1272         if (groupId != null) {
1273             // Is this from the Admin Console or API?
1274             if(apiflag!=null) {
1275                 if(!authorizeRequest(request)){
1276                     String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1277                     PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1278                     loggingContext.transactionEnded();
1279                     PolicyLogger.audit("Transaction Failed - See Error.log");
1280                     setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1281                     return;
1282                 }
1283                 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1284                 try {
1285                     loggingContext.metricStarted();
1286                     apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1287                     loggingContext.metricEnded();
1288                     PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1289                 } catch (Exception e) {
1290                     LOGGER.error("Exception Occured"+e);
1291                 }
1292                 if(apiRequestHandler.getNewGroup()!=null){
1293                     groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1294                 }
1295                 return;
1296             }
1297             // this is from the Admin Console, so handle separately
1298             try{
1299                 loggingContext.metricStarted();
1300                 doACDelete(request, response, groupId, loggingContext);
1301                 loggingContext.metricEnded();
1302                 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1303             } catch (IOException e) {
1304                 LOGGER.error(e);
1305             }
1306             loggingContext.transactionEnded();
1307             PolicyLogger.audit("Transaction Ended Successfully");
1308             im.endTransaction();
1309             return;
1310         }
1311         //Catch anything that fell through
1312         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1313         loggingContext.transactionEnded();
1314         PolicyLogger.audit("Transaction Failed - See Error.log");
1315         setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1316         im.endTransaction();
1317     }
1318
1319     private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1320         String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1321         String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1322         if (localRootPolicies == null || localReferencedPolicies == null) {
1323             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+"  ReferencedPolicies="+localReferencedPolicies);
1324             return false;
1325         }
1326         // Compare the policies and pipconfig properties to the pdpProperties
1327         try {
1328             // the policy properties includes only xacml.rootPolicies and
1329             // xacml.referencedPolicies without any .url entries
1330             Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1331             Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1332             if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1333                     localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1334                     pdpPipConfig.equals(pipconfig)) {
1335                 // The PDP is current
1336                 return true;
1337             }
1338         } catch (Exception e) {
1339             // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1340             // or if there are policies that do not have a corresponding ".url" property.
1341             // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1342             PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1343         }
1344         return false;
1345     }
1346
1347     private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1348         String lists[] = new String[2];
1349         lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1350         lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1351         for (String list : lists) {
1352             if (list != null && list.isEmpty() == false) {
1353                 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1354                     String url = urlPath + "?id=" + id;
1355                     LOGGER.info("Policy URL for " + id + ": " + url);
1356                     policies.setProperty(id + ".url", url);
1357                 }
1358             }
1359         }
1360     }
1361
1362     protected String getPDPID(HttpServletRequest request) {
1363         String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1364         if (pdpURL == null || pdpURL.isEmpty()) {
1365             // Should send back its port for identification
1366             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1367             pdpURL = "";
1368         }
1369         return pdpURL;
1370     }
1371
1372     protected String getPDPJMX(HttpServletRequest request) {
1373         String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1374         if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1375             // Should send back its port for identification
1376             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1377             return null;
1378         }
1379         return pdpJMMX;
1380     }
1381
1382     /**
1383      * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1384      *
1385      * @param request
1386      * @param response
1387      * @param groupId
1388      * @param loggingContext
1389      * @throws ServletException
1390      * @throws IOException
1391      */
1392     public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1393         PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1394         PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1395         try {
1396             // for PUT operations the group may or may not need to exist before the operation can be done
1397             StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1398
1399             // get the request input stream content into a String
1400             String json = null;
1401             java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1402             scanner.useDelimiter("\\A");
1403             json =  scanner.hasNext() ? scanner.next() : "";
1404             scanner.close();
1405
1406             PolicyLogger.info("pushPolicy request from API: " + json);
1407
1408             // convert Object sent as JSON into local object
1409             StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1410
1411             //Get the current policies from the Group and Add the new one
1412             Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1413             currentPoliciesInGroup = group.getPolicies();
1414             //If the selected policy is in the group we must remove the old version of it
1415             LOGGER.info("Removing old version of the policy");
1416             for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
1417                 if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
1418                     group.removePolicy(existingPolicy);
1419                     LOGGER.info("Removing policy: " + existingPolicy);
1420                     break;
1421                 }
1422             }
1423
1424             // Assume that this is an update of an existing PDP Group
1425             loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1426             try{
1427                 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1428             } catch(Exception e){
1429                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1430                         +"group="+group.getId());
1431                 throw new PAPException(e.getMessage());
1432             }
1433
1434             LOGGER.info("Calling updatGroup() with new group");
1435             papEngine.updateGroup(group);
1436             String policyId = "empty";
1437             if(policy !=null && policy.getId() != null){
1438                 policyId = policy.getId();
1439             }
1440             if(!policyId.matches(REGEX) ){
1441                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1442                 response.addHeader("error",ADD_GROUP_ERROR);
1443                 response.addHeader("message", "Policy Id is not valid");
1444                 return;
1445             }
1446             response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1447             response.addHeader("operation", "push");
1448             response.addHeader("policyId", policyId);
1449             response.addHeader("groupId", groupId);
1450
1451             LOGGER.info("Group '" + group.getId() + "' updated");
1452
1453             loggingContext.metricStarted();
1454             acPutTransaction.commitTransaction();
1455             loggingContext.metricEnded();
1456             PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1457             loggingContext.metricStarted();
1458             notifyAC();
1459             loggingContext.metricEnded();
1460             PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1461
1462             // Group changed, which might include changing the policies
1463             groupChanged(group, loggingContext);
1464             loggingContext.transactionEnded();
1465             LOGGER.info("Success");
1466
1467             if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1468                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1469                 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1470                     LOGGER.debug("Precheck Successful.");
1471                 }
1472             }
1473
1474             PolicyLogger.audit("Transaction Ended Successfully");
1475             return;
1476         } catch (PAPException e) {
1477             acPutTransaction.rollbackTransaction();
1478             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1479             loggingContext.transactionEnded();
1480             PolicyLogger.audit("Transaction Failed - See Error.log");
1481             String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1482             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1483             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1484             response.addHeader("error",ADD_GROUP_ERROR);
1485             response.addHeader("message", message);
1486             return;
1487         }
1488     }
1489
1490     /**
1491      * Requests from the Admin Console for operations not on single specific objects
1492      *
1493      * @param request
1494      * @param response
1495      * @param groupId
1496      * @param loggingContext
1497      * @throws ServletException
1498      * @throws IOException
1499      */
1500     private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1501         PolicyDBDaoTransaction doACPostTransaction = null;
1502         try {
1503             String groupName = request.getParameter("groupName");
1504             String groupDescription = request.getParameter("groupDescription");
1505             String apiflag = request.getParameter("apiflag");
1506             if (groupName != null && groupDescription != null) {
1507                 // Args:              group=<groupId> groupName=<name> groupDescription=<description>            <= create a new group
1508                 loggingContext.setServiceName("AC:PAP.createGroup");
1509                 String unescapedName = null;
1510                 String unescapedDescription = null;
1511                 try{
1512                     unescapedName = URLDecoder.decode(groupName, "UTF-8");
1513                     unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1514                 } catch (UnsupportedEncodingException e) {
1515                     LOGGER.error(e);
1516                 }
1517                 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1518                 try {
1519                     newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1520                     papEngine.newGroup(unescapedName, unescapedDescription);
1521                     loggingContext.metricStarted();
1522                     newGroupTransaction.commitTransaction();
1523                     loggingContext.metricEnded();
1524                     PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1525                 } catch (Exception e) {
1526                     newGroupTransaction.rollbackTransaction();
1527                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1528                     loggingContext.transactionEnded();
1529                     PolicyLogger.audit("Transaction Failed - See Error.log");
1530                     setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1531                     return;
1532                 }
1533                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1534                 if (LOGGER.isDebugEnabled()) {
1535                     LOGGER.debug("New Group '" + groupId + "' created");
1536                 }
1537                 // tell the Admin Consoles there is a change
1538                 loggingContext.metricStarted();
1539                 notifyAC();
1540                 loggingContext.metricEnded();
1541                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1542                 // new group by definition has no PDPs, so no need to notify them of changes
1543                 loggingContext.transactionEnded();
1544                 PolicyLogger.audit("Transaction Failed - See Error.log");
1545                 auditLogger.info("Success");
1546                 PolicyLogger.audit("Transaction Ended Successfully");
1547                 return;
1548             }
1549             // for all remaining POST operations the group must exist before the operation can be done
1550             OnapPDPGroup group = null;
1551             try{
1552                 group = papEngine.getGroup(groupId);
1553             } catch (PAPException e){
1554                 LOGGER.error(e);
1555             }
1556             if (group == null) {
1557                 String message = "Unknown groupId '" + groupId + "'";
1558                 //for fixing Header Manipulation of Fortify issue
1559                 if(!message.matches(REGEX)){
1560                     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1561                     response.addHeader("error",ADD_GROUP_ERROR);
1562                     response.addHeader("message", "GroupId Id is not valid");
1563                     return;
1564                 }
1565                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1566                 loggingContext.transactionEnded();
1567                 PolicyLogger.audit("Transaction Failed - See Error.log");
1568                 if (apiflag!=null){
1569                     response.addHeader("error", "unknownGroupId");
1570                     response.addHeader("operation", "push");
1571                     response.addHeader("message", message);
1572                     response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1573                 } else {
1574                     setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1575                 }
1576                 return;
1577             }
1578
1579             // If the request contains a policyId then we know we are pushing the policy to PDP
1580             if (request.getParameter("policyId") != null) {
1581
1582                 if(apiflag!=null){
1583                     loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1584                     LOGGER.info("PushPolicy Request From The API");
1585                 } else {
1586                     loggingContext.setServiceName("AC:PAP.postPolicy");
1587                     LOGGER.info("PushPolicy Request From The AC");
1588                 }
1589
1590                 String policyId = request.getParameter("policyId");
1591                 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1592                 StdPDPGroup updatedGroup = null;
1593                 try {
1594                     //Copying the policy to the file system and updating groups in database
1595                     LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
1596                     updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1597                     loggingContext.metricStarted();
1598                     addPolicyToGroupTransaction.commitTransaction();
1599                     loggingContext.metricEnded();
1600                     PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1601                     LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
1602
1603                 } catch (Exception e) {
1604                     addPolicyToGroupTransaction.rollbackTransaction();
1605                     String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1606                     //for fixing Header Manipulation of Fortify issue
1607                     if(!message.matches(REGEX)){
1608                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1609                         response.addHeader("error",ADD_GROUP_ERROR);
1610                         response.addHeader("message", "Policy Id is not valid");
1611                         return;
1612                     }
1613                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1614                     loggingContext.transactionEnded();
1615                     PolicyLogger.audit("Transaction Failed - See Error.log");
1616                     if (apiflag!=null){
1617                         response.addHeader("error", "policyCopyError");
1618                         response.addHeader("message", message);
1619                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1620                     } else {
1621                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1622                     }
1623                     return;
1624                 }
1625
1626                 if(apiflag != null){
1627                     /*
1628                      * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
1629                      * The GUI does this from the POLICY-SDK-APP code.
1630                      */
1631
1632                     // Get new transaction to perform updateGroup()
1633                     PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1634                     try {
1635                         // get the request content into a String and read the inputStream into a buffer
1636                         java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1637                         scanner.useDelimiter("\\A");
1638                         String json =  scanner.hasNext() ? scanner.next() : "";
1639                         scanner.close();
1640
1641                         // convert Object sent as JSON into local object
1642                         ObjectMapper mapper = new ObjectMapper();
1643                         Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1644                         StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1645
1646                         LOGGER.info("Request JSON Payload: " + json);
1647
1648                         // Assume that this is an update of an existing PDP Group
1649                         loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1650                         try{
1651                             acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
1652                         } catch(Exception e){
1653                             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
1654                                     + e);
1655                             throw new PAPException(e.getMessage());
1656                         }
1657
1658                         LOGGER.info("Calling updatGroup() with new group");
1659                         papEngine.updateGroup(updatedGroup);
1660
1661                         LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
1662
1663                         // Commit transaction to send notification to other PAPs
1664                         loggingContext.metricStarted();
1665                         acPutTransaction.commitTransaction();
1666                         loggingContext.metricEnded();
1667                         PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1668                         loggingContext.metricStarted();
1669
1670                         notifyAC();
1671                         loggingContext.metricEnded();
1672                         PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1673
1674                         // Group changed to send notification to PDPs, which might include changing the policies
1675                         groupChanged(updatedGroup,loggingContext);
1676                         loggingContext.transactionEnded();
1677                         LOGGER.info("Success");
1678
1679                         if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1680                             PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1681                             if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1682                                 LOGGER.debug("Precheck Successful.");
1683                             }
1684                         }
1685
1686                         //delete temporary policy file from the bin directory
1687                         Files.deleteIfExists(Paths.get(policy.getId()));
1688
1689                     } catch (Exception e) {
1690                         acPutTransaction.rollbackTransaction();
1691                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1692                         loggingContext.transactionEnded();
1693                         PolicyLogger.audit("Transaction Failed - See Error.log");
1694                         String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
1695                         LOGGER.error(message);
1696                         setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1697                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1698                         response.addHeader("error",ADD_GROUP_ERROR);
1699                         response.addHeader("message", message);
1700                         return;
1701                     }
1702                 }
1703
1704                 // policy file copied ok and the Group was updated on the PDP
1705                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1706                 response.addHeader("operation", "push");
1707                 response.addHeader("policyId", policyId);
1708                 response.addHeader("groupId", groupId);
1709
1710                 LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1711                 loggingContext.transactionEnded();
1712                 auditLogger.info("Success");
1713                 LOGGER.info("Transaction Ended Successfully");
1714
1715                 return;
1716             } else if (request.getParameter("default") != null) {
1717                 // Args:       group=<groupId> default=true               <= make default
1718                 // change the current default group to be the one identified in the request.
1719                 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1720                 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1721                 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1722                 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1723                 try {
1724                     setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1725                     papEngine.setDefaultGroup(group);
1726                     loggingContext.metricStarted();
1727                     setDefaultGroupTransaction.commitTransaction();
1728                     loggingContext.metricEnded();
1729                     PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1730                 } catch (Exception e) {
1731                     setDefaultGroupTransaction.rollbackTransaction();
1732                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1733                     loggingContext.transactionEnded();
1734                     PolicyLogger.audit("Transaction Failed - See Error.log");
1735                     setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1736                     return;
1737                 }
1738                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1739                 if (LOGGER.isDebugEnabled()) {
1740                     LOGGER.debug("Group '" + groupId + "' set to be default");
1741                 }
1742                 // Notify the Admin Consoles that something changed
1743                 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1744                 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1745                 loggingContext.metricStarted();
1746                 notifyAC();
1747                 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1748                 loggingContext.metricEnded();
1749                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1750                 loggingContext.transactionEnded();
1751                 auditLogger.info("Success");
1752                 LOGGER.info("Transaction Ended Successfully");
1753                 return;
1754             } else if (request.getParameter("pdpId") != null) {
1755                 doACPostTransaction = policyDBDao.getNewTransaction();
1756                 // Args:       group=<groupId> pdpId=<pdpId>               <= move PDP to group
1757                 loggingContext.setServiceName("AC:PAP.movePDP");
1758                 String pdpId = request.getParameter("pdpId");
1759                 OnapPDP pdp = papEngine.getPDP(pdpId);
1760                 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1761                 try{
1762                     doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1763                 }catch(Exception e){
1764                     doACPostTransaction.rollbackTransaction();
1765                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1766                             " Error while moving pdp in the database: "
1767                                     +"pdp="+pdp.getId()+",to group="+group.getId());
1768                     throw new PAPException(e.getMessage());
1769                 }
1770                 papEngine.movePDP((OnapPDP) pdp, group);
1771                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1772                 if (LOGGER.isDebugEnabled()) {
1773                     LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1774                 }
1775                 // update the status of both the original group and the new one
1776                 ((StdPDPGroup)originalGroup).resetStatus();
1777                 ((StdPDPGroup)group).resetStatus();
1778                 // Notify the Admin Consoles that something changed
1779                 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1780                 loggingContext.metricStarted();
1781                 notifyAC();
1782                 loggingContext.metricEnded();
1783                 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1784                 // Need to notify the PDP that it's config may have changed
1785                 pdpChanged(pdp, loggingContext);
1786                 loggingContext.metricStarted();
1787                 doACPostTransaction.commitTransaction();
1788                 loggingContext.metricEnded();
1789                 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1790                 loggingContext.transactionEnded();
1791                 auditLogger.info("Success");
1792                 PolicyLogger.audit("Transaction Ended Successfully");
1793                 return;
1794             }
1795         } catch (PAPException e) {
1796             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1797             loggingContext.transactionEnded();
1798             PolicyLogger.audit("Transaction Failed - See Error.log");
1799             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1800             return;
1801         }
1802     }
1803
1804     /**
1805      * Requests from the Admin Console to GET info about the Groups and PDPs
1806      *
1807      * @param request
1808      * @param response
1809      * @param groupId
1810      * @param loggingContext
1811      * @throws ServletException
1812      * @throws IOException
1813      */
1814     private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1815         try {
1816             String parameterDefault = request.getParameter("default");
1817             String pdpId = request.getParameter("pdpId");
1818             String pdpGroup = request.getParameter("getPDPGroup");
1819             if ("".equals(groupId)) {
1820                 // request IS from AC but does not identify a group by name
1821                 if (parameterDefault != null) {
1822                     // Request is for the Default group (whatever its id)
1823                     loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1824                     OnapPDPGroup group = papEngine.getDefaultGroup();
1825                     // convert response object to JSON and include in the response
1826                     mapperWriteValue(new ObjectMapper(), response,  group);
1827                     if (LOGGER.isDebugEnabled()) {
1828                         LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1829                     }
1830                     response.setStatus(HttpServletResponse.SC_OK);
1831                     response.setHeader("content-type", "application/json");
1832                     try{
1833                         response.getOutputStream().close();
1834                     } catch (IOException e){
1835                         LOGGER.error(e);
1836                     }
1837                     loggingContext.transactionEnded();
1838                     auditLogger.info("Success");
1839                     PolicyLogger.audit("Transaction Ended Successfully");
1840                     return;
1841                 } else if (pdpId != null) {
1842                     // Request is related to a PDP
1843                     if (pdpGroup == null) {
1844                         // Request is for the (unspecified) group containing a given PDP
1845                         loggingContext.setServiceName("AC:PAP.getPDP");
1846                         OnapPDP pdp = null;
1847                         try{
1848                             pdp = papEngine.getPDP(pdpId);
1849                         }catch(PAPException e){
1850                             LOGGER.error(e);
1851                         }
1852                         // convert response object to JSON and include in the response
1853                         mapperWriteValue(new ObjectMapper(), response,  pdp);
1854                         if (LOGGER.isDebugEnabled()) {
1855                             LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1856                         }
1857                         response.setStatus(HttpServletResponse.SC_OK);
1858                         response.setHeader("content-type", "application/json");
1859                         try{
1860                             response.getOutputStream().close();
1861                         } catch (IOException e){
1862                             LOGGER.error(e);
1863                         }
1864                         loggingContext.transactionEnded();
1865                         auditLogger.info("Success");
1866                         PolicyLogger.audit("Transaction Ended Successfully");
1867                         return;
1868                     } else {
1869                         // Request is for the group containing a given PDP
1870                         loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1871                         OnapPDPGroup group =null;
1872                         try{
1873                             OnapPDP pdp = papEngine.getPDP(pdpId);
1874                             group = papEngine.getPDPGroup((OnapPDP) pdp);
1875                         }catch(PAPException e){
1876                             LOGGER.error(e);
1877                         }
1878                         // convert response object to JSON and include in the response
1879                         mapperWriteValue(new ObjectMapper(), response,  group);
1880                         if (LOGGER.isDebugEnabled()) {
1881                             LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1882                         }
1883                         response.setStatus(HttpServletResponse.SC_OK);
1884                         response.setHeader("content-type", "application/json");
1885                         try{
1886                             response.getOutputStream().close();
1887                         } catch (IOException e){
1888                             LOGGER.error(e);
1889                         }
1890                         loggingContext.transactionEnded();
1891                         auditLogger.info("Success");
1892                         PolicyLogger.audit("Transaction Ended Successfully");
1893                         return;
1894                     }
1895                 } else {
1896                     // request is for top-level properties about all groups
1897                     loggingContext.setServiceName("AC:PAP.getAllGroups");
1898                     Set<OnapPDPGroup> groups = null;
1899                     try {
1900                         groups = papEngine.getOnapPDPGroups();
1901                     } catch(PAPException e) {
1902                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1903                         loggingContext.transactionEnded();
1904                         PolicyLogger.audit("Transaction Failed - See Error.log");
1905                         setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1906                         return;
1907                     }
1908                     // convert response object to JSON and include in the response
1909                     mapperWriteValue(new ObjectMapper(), response,  groups);
1910                     if (LOGGER.isDebugEnabled()) {
1911                         LOGGER.debug("GET All groups req");
1912                     }
1913                     response.setStatus(HttpServletResponse.SC_OK);
1914                     response.setHeader("content-type", "application/json");
1915                     try{
1916                         response.getOutputStream().close();
1917                     } catch (IOException e){
1918                         LOGGER.error(e);
1919                     }
1920                     loggingContext.transactionEnded();
1921                     auditLogger.info("Success");
1922                     PolicyLogger.audit("Transaction Ended Successfully");
1923                     return;
1924                 }
1925             }
1926             // for all other GET operations the group must exist before the operation can be done
1927             OnapPDPGroup group = null;
1928             try{
1929                 group = papEngine.getGroup(groupId);
1930             } catch(PAPException e){
1931                 LOGGER.error(e);
1932             }
1933             if (group == null) {
1934                 String message = "Unknown groupId '" + groupId + "'";
1935                 //for fixing Header Manipulation of Fortify issue
1936                 if(!message.matches(REGEX)){
1937                     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1938                     response.addHeader("error",ADD_GROUP_ERROR);
1939                     response.addHeader("message", "Group Id is not valid");
1940                     return;
1941                 }
1942                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1943                 loggingContext.transactionEnded();
1944                 PolicyLogger.audit("Transaction Failed - See Error.log");
1945                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1946                 return;
1947             }
1948             // Figure out which request this is based on the parameters
1949             String policyId = request.getParameter("policyId");
1950             if (policyId != null) {
1951                 // retrieve a policy
1952                 loggingContext.setServiceName("AC:PAP.getPolicy");
1953                 // convert response object to JSON and include in the response
1954                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1955                 loggingContext.transactionEnded();
1956                 PolicyLogger.audit("Transaction Failed - See Error.log");
1957                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1958             } else {
1959                 // No other parameters, so return the identified Group
1960                 loggingContext.setServiceName("AC:PAP.getGroup");
1961                 // convert response object to JSON and include in the response
1962                 mapperWriteValue(new ObjectMapper(), response,  group);
1963                 if (LOGGER.isDebugEnabled()) {
1964                     LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1965                 }
1966                 response.setStatus(HttpServletResponse.SC_OK);
1967                 response.setHeader("content-type", "application/json");
1968                 try{
1969                     response.getOutputStream().close();
1970                 } catch (IOException e){
1971                     LOGGER.error(e);
1972                 }
1973                 loggingContext.transactionEnded();
1974                 auditLogger.info("Success");
1975                 PolicyLogger.audit("Transaction Ended Successfully");
1976                 return;
1977             }
1978             // Currently there are no other GET calls from the AC.
1979             // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP.
1980             // Other GETs that could be called:
1981             //                          Specific Group  (groupId=<groupId>)
1982             //                          A Policy                (groupId=<groupId> policyId=<policyId>)
1983             //                          A PDP                   (groupId=<groupId> pdpId=<pdpId>)
1984             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1985             loggingContext.transactionEnded();
1986             PolicyLogger.audit("Transaction Failed - See Error.log");
1987             setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1988         } catch (PAPException e) {
1989             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1990             loggingContext.transactionEnded();
1991             PolicyLogger.audit("Transaction Failed - See Error.log");
1992             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1993             return;
1994         }
1995     }
1996
1997     /**
1998      * Requests from the Admin Console to create new items or update existing ones
1999      *
2000      * @param request
2001      * @param response
2002      * @param groupId
2003      * @param loggingContext
2004      * @throws ServletException
2005      * @throws IOException
2006      */
2007     private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2008         PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
2009         try {
2010             // for PUT operations the group may or may not need to exist before the operation can be done
2011             OnapPDPGroup group = papEngine.getGroup(groupId);
2012             // determine the operation needed based on the parameters in the request
2013             // for remaining operations the group must exist before the operation can be done
2014             if (group == null) {
2015                 String message = "Unknown groupId '" + groupId + "'";
2016                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2017                 loggingContext.transactionEnded();
2018                 PolicyLogger.audit("Transaction Failed - See Error.log");
2019                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
2020                 return;
2021             }
2022             if (request.getParameter("policy") != null) {
2023                 //        group=<groupId> policy=<policyId> contents=policy file               <= Create new policy file in group dir, or replace it if it already exists (do not touch properties)
2024                 loggingContext.setServiceName("AC:PAP.putPolicy");
2025                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!!  ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
2026                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2027                 loggingContext.transactionEnded();
2028                 PolicyLogger.audit("Transaction Failed - See Error.log");
2029                 auditLogger.info("Success");
2030                 PolicyLogger.audit("Transaction Ended Successfully");
2031                 return;
2032             } else if (request.getParameter("pdpId") != null) {
2033                 // ARGS:        group=<groupId> pdpId=<pdpId/URL>          <= create a new PDP or Update an Existing one
2034                 String pdpId = request.getParameter("pdpId");
2035                 if (papEngine.getPDP(pdpId) == null) {
2036                     loggingContext.setServiceName("AC:PAP.createPDP");
2037                 } else {
2038                     loggingContext.setServiceName("AC:PAP.updatePDP");
2039                 }
2040                 // get the request content into a String
2041                 String json = null;
2042                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2043                 try{
2044                     Scanner scanner = new Scanner(request.getInputStream());
2045                     scanner.useDelimiter("\\A");
2046                     json =  scanner.hasNext() ? scanner.next() : "";
2047                     scanner.close();
2048                 }catch(IOException e){
2049                     LOGGER.error(e);
2050                 }
2051                 LOGGER.info("JSON request from AC: " + json);
2052                 // convert Object sent as JSON into local object
2053                 ObjectMapper mapper = new ObjectMapper();
2054                 Object objectFromJSON = null;
2055                 try {
2056                     objectFromJSON = mapper.readValue(json, StdPDP.class);
2057                 } catch(Exception e) {
2058                     LOGGER.error(e);
2059                 }
2060                 if (pdpId == null ||
2061                         objectFromJSON == null ||
2062                         ! (objectFromJSON instanceof StdPDP) ||
2063                         ((StdPDP)objectFromJSON).getId() == null ||
2064                         ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
2065                     PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
2066                     loggingContext.transactionEnded();
2067                     PolicyLogger.audit("Transaction Failed - See Error.log");
2068                     setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
2069                 }
2070                 StdPDP pdp = (StdPDP) objectFromJSON;
2071                 if(pdp != null){
2072                     OnapPDP oPDP = null;
2073                     try{
2074                         oPDP = papEngine.getPDP(pdpId);
2075                     }catch (PAPException e){
2076                         LOGGER.error(e);
2077                     }
2078                     if (oPDP == null) {
2079                         // this is a request to create a new PDP object
2080                         try{
2081                             acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(),
2082                                     pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
2083                         } catch(Exception e){
2084                             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2085                                     +"pdp="+ (pdp.getId()) +",to group="+group.getId());
2086                             throw new PAPException(e.getMessage());
2087                         }
2088                         try{
2089                             papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
2090                         }catch(PAPException e){
2091                             LOGGER.error(e);
2092                         }
2093                     } else {
2094                         try{
2095                             acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
2096                         } catch(Exception e){
2097                             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
2098                                     +"pdp="+ pdp.getId());
2099                             throw new PAPException(e.getMessage());
2100                         }
2101                         // this is a request to update the pdp
2102                         try{
2103                             papEngine.updatePDP(pdp);
2104                         }catch(PAPException e){
2105                             LOGGER.error(e);
2106                         }
2107                     }
2108                     response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2109                     if (LOGGER.isDebugEnabled()) {
2110                         LOGGER.debug("PDP '" + pdpId + "' created/updated");
2111                     }
2112                     // adjust the group's state including the new PDP
2113                     ((StdPDPGroup)group).resetStatus();
2114                     // tell the Admin Consoles there is a change
2115                     loggingContext.metricStarted();
2116                     notifyAC();
2117                     loggingContext.metricEnded();
2118                     PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2119                     // this might affect the PDP, so notify it of the change
2120                     pdpChanged(pdp, loggingContext);
2121                     loggingContext.metricStarted();
2122                     acPutTransaction.commitTransaction();
2123                     loggingContext.metricEnded();
2124                     PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2125                     loggingContext.transactionEnded();
2126                     auditLogger.info("Success");
2127                     PolicyLogger.audit("Transaction Ended Successfully");
2128                     return;
2129                 }else{
2130                     try{
2131                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2132                                 +"pdp=null" + ",to group="+group.getId());
2133                         throw new PAPException("PDP is null");
2134                     } catch(Exception e){
2135                         throw new PAPException("PDP is null" + e.getMessage() +e);
2136                     }
2137                 }
2138             } else if (request.getParameter("pipId") != null) {
2139                 //                group=<groupId> pipId=<pipEngineId> contents=pip properties              <= add a PIP to pip config, or replace it if it already exists (lenient operation)
2140                 loggingContext.setServiceName("AC:PAP.putPIP");
2141                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2142                 loggingContext.transactionEnded();
2143                 PolicyLogger.audit("Transaction Failed - See Error.log");
2144                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2145                 return;
2146             } else {
2147                 // Assume that this is an update of an existing PDP Group
2148                 // ARGS:        group=<groupId>         <= Update an Existing Group
2149                 loggingContext.setServiceName("AC:PAP.updateGroup");
2150                 // get the request content into a String
2151                 String json = null;
2152                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2153                 try{
2154                     Scanner scanner = new Scanner(request.getInputStream());
2155                     scanner.useDelimiter("\\A");
2156                     json =  scanner.hasNext() ? scanner.next() : "";
2157                     scanner.close();
2158                 }catch(IOException e){
2159                     LOGGER.error(e);
2160                 }
2161                 LOGGER.info("JSON request from AC: " + json);
2162                 // convert Object sent as JSON into local object
2163                 ObjectMapper mapper = new ObjectMapper();
2164                 Object objectFromJSON = null;
2165                 try {
2166                     objectFromJSON  = mapper.readValue(json, StdPDPGroup.class);
2167                 } catch(Exception e) {
2168                     LOGGER.error(e);
2169                 }
2170                 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
2171                         ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
2172                     PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
2173                     loggingContext.transactionEnded();
2174                     PolicyLogger.audit("Transaction Failed - See Error.log");
2175                     setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
2176                 }
2177                 // The Path on the PAP side is not carried on the RESTful interface with the AC
2178                 // (because it is local to the PAP)
2179                 // so we need to fill that in before submitting the group for update
2180                 if(objectFromJSON != null){
2181                     ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
2182                 }
2183                 try{
2184                     if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
2185                         acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
2186                     } else {
2187                         acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
2188                     }
2189                 } catch(Exception e){
2190                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
2191                             +"group="+group.getId());
2192                     LOGGER.error(e);
2193                     throw new PAPException(e.getMessage());
2194                 }
2195
2196                 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
2197                 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
2198                 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
2199                     LOGGER.debug("Precheck Successful.");
2200                 }
2201                 try{
2202                     papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2203                 }catch(PAPException e){
2204                     LOGGER.error(e);
2205                 }
2206                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2207                 if (LOGGER.isDebugEnabled()) {
2208                     LOGGER.debug("Group '" + group.getId() + "' updated");
2209                 }
2210                 loggingContext.metricStarted();
2211                 acPutTransaction.commitTransaction();
2212                 loggingContext.metricEnded();
2213                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2214                 // tell the Admin Consoles there is a change
2215                 loggingContext.metricStarted();
2216                 notifyAC();
2217                 loggingContext.metricEnded();
2218                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2219                 // Group changed, which might include changing the policies
2220                 groupChanged(group, loggingContext);
2221                 loggingContext.transactionEnded();
2222                 auditLogger.info("Success");
2223                 PolicyLogger.audit("Transaction Ended Successfully");
2224                 return;
2225             }
2226         } catch (PAPException e) {
2227             LOGGER.debug(e);
2228             acPutTransaction.rollbackTransaction();
2229             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2230             loggingContext.transactionEnded();
2231             PolicyLogger.audit("Transaction Failed - See Error.log");
2232             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2233             return;
2234         }
2235     }
2236
2237     /**
2238      * Requests from the Admin Console to delete/remove items
2239      *
2240      * @param request
2241      * @param response
2242      * @param groupId
2243      * @param loggingContext
2244      * @throws ServletException
2245      * @throws IOException
2246      */
2247     private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2248         PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2249         try {
2250             // for all DELETE operations the group must exist before the operation can be done
2251             loggingContext.setServiceName("AC:PAP.delete");
2252             OnapPDPGroup group = papEngine.getGroup(groupId);
2253             if (group == null) {
2254                 String message = "Unknown groupId '" + groupId + "'";
2255                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2256                 loggingContext.transactionEnded();
2257                 PolicyLogger.audit("Transaction Failed - See Error.log");
2258                 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2259                 return;
2260             }
2261             // determine the operation needed based on the parameters in the request
2262             if (request.getParameter("policy") != null) {
2263                 //        group=<groupId> policy=<policyId>  [delete=<true|false>]       <= delete policy file from group
2264                 loggingContext.setServiceName("AC:PAP.deletePolicy");
2265                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2266                 loggingContext.transactionEnded();
2267                 PolicyLogger.audit("Transaction Failed - See Error.log");
2268                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2269                 return;
2270             } else if (request.getParameter("pdpId") != null) {
2271                 // ARGS:        group=<groupId> pdpId=<pdpId>                  <= delete PDP
2272                 String pdpId = request.getParameter("pdpId");
2273                 OnapPDP pdp = papEngine.getPDP(pdpId);
2274                 try{
2275                     removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2276                 } catch(Exception e){
2277                     throw new PAPException(e);
2278                 }
2279                 try{
2280                     papEngine.removePDP((OnapPDP) pdp);
2281                 }catch(PAPException e){
2282                     LOGGER.error(e);
2283                 }
2284                 // adjust the status of the group, which may have changed when we removed this PDP
2285                 ((StdPDPGroup)group).resetStatus();
2286                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2287                 loggingContext.metricStarted();
2288                 notifyAC();
2289                 loggingContext.metricEnded();
2290                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2291                 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2292                 pdpChanged(pdp, loggingContext);
2293                 loggingContext.metricStarted();
2294                 removePdpOrGroupTransaction.commitTransaction();
2295                 loggingContext.metricEnded();
2296                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2297                 loggingContext.transactionEnded();
2298                 auditLogger.info("Success");
2299                 PolicyLogger.audit("Transaction Ended Successfully");
2300                 return;
2301             } else if (request.getParameter("pipId") != null) {
2302                 //        group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2303                 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2304                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2305                 loggingContext.transactionEnded();
2306                 PolicyLogger.audit("Transaction Failed - See Error.log");
2307                 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2308                 return;
2309             } else {
2310                 // ARGS:      group=<groupId> movePDPsToGroupId=<movePDPsToGroupId>            <= delete a group and move all its PDPs to the given group
2311                 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2312                 OnapPDPGroup moveToGroup = null;
2313                 if (moveToGroupId != null) {
2314                     try{
2315                         moveToGroup = papEngine.getGroup(moveToGroupId);
2316                     }catch(PAPException e){
2317                         LOGGER.error(e);
2318                     }
2319                 }
2320                 // get list of PDPs in the group being deleted so we can notify them that they got changed
2321                 Set<OnapPDP> movedPDPs = new HashSet<>();
2322                 movedPDPs.addAll(group.getOnapPdps());
2323                 // do the move/remove
2324                 try{
2325                     removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2326                 } catch(Exception e){
2327                     PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2328                     throw new PAPException(e.getMessage());
2329                 }
2330                 try{
2331                     papEngine.removeGroup(group, moveToGroup);
2332                 }catch(PAPException e){
2333                     LOGGER.error(e);
2334                 }
2335                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2336                 loggingContext.metricStarted();
2337                 notifyAC();
2338                 loggingContext.metricEnded();
2339                 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2340                 // notify any PDPs in the removed set that their config may have changed
2341                 for (OnapPDP pdp : movedPDPs) {
2342                     pdpChanged(pdp, loggingContext);
2343                 }
2344                 loggingContext.metricStarted();
2345                 removePdpOrGroupTransaction.commitTransaction();
2346                 loggingContext.metricEnded();
2347                 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2348                 loggingContext.transactionEnded();
2349                 auditLogger.info("Success");
2350                 PolicyLogger.audit("Transaction Ended Successfully");
2351                 return;
2352             }
2353         } catch (PAPException e) {
2354             removePdpOrGroupTransaction.rollbackTransaction();
2355             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2356             loggingContext.transactionEnded();
2357             PolicyLogger.audit("Transaction Failed - See Error.log");
2358             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2359             return;
2360         }
2361     }
2362
2363     /**
2364      * Heartbeat thread - periodically check on PDPs' status
2365      *
2366      * Heartbeat with all known PDPs.
2367      *
2368      * Implementation note:
2369      *
2370      * The PDPs are contacted Sequentially, not in Parallel.
2371      *
2372      * If we did this in parallel using multiple threads we would simultaneously use
2373      *          - 1 thread and
2374      *          - 1 connection
2375      * for EACH PDP.
2376      * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2377      * when user changes occur.
2378      * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2379      *
2380      * The Sequential operation does a heartbeat request to each PDP one at a time.
2381      * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2382      * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2383      * it could take a long time to cycle through all of the PDPs.
2384      * That means that this may not notice a PDP being down in a predictable time.
2385      */
2386     private class Heartbeat implements Runnable {
2387         private PAPPolicyEngine papEngine;
2388         private Set<OnapPDP> pdps = new HashSet<>();
2389         private int heartbeatInterval;
2390         private int heartbeatTimeout;
2391
2392         public volatile boolean isRunning = false;
2393
2394         public synchronized boolean isRunning() {
2395             return this.isRunning;
2396         }
2397
2398         public synchronized void terminate() {
2399             this.isRunning = false;
2400         }
2401
2402         public Heartbeat(PAPPolicyEngine papEngine2) {
2403             papEngine = papEngine2;
2404             this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2405             this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2406         }
2407
2408         @Override
2409         public void run() {
2410             // Set ourselves as running
2411             synchronized(this) {
2412                 this.isRunning = true;
2413             }
2414             HashMap<String, URL> idToURLMap = new HashMap<>();
2415             try {
2416                 while (this.isRunning()) {
2417                     // Wait the given time
2418                     Thread.sleep(heartbeatInterval);
2419                     // get the list of PDPs (may have changed since last time)
2420                     pdps.clear();
2421                     synchronized(papEngine) {
2422                         try {
2423                             for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2424                                 for (OnapPDP p : g.getOnapPdps()) {
2425                                     pdps.add(p);
2426                                 }
2427                             }
2428                         } catch (PAPException e) {
2429                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2430                         }
2431                     }
2432                     // Check for shutdown
2433                     if (this.isRunning() == false) {
2434                         LOGGER.info("isRunning is false, getting out of loop.");
2435                         break;
2436                     }
2437                     // try to get the summary status from each PDP
2438                     boolean changeSeen = false;
2439                     for (OnapPDP pdp : pdps) {
2440                         // Check for shutdown
2441                         if (this.isRunning() == false) {
2442                             LOGGER.info("isRunning is false, getting out of loop.");
2443                             break;
2444                         }
2445                         // the id of the PDP is its url (though we add a query parameter)
2446                         URL pdpURL = idToURLMap.get(pdp.getId());
2447                         if (pdpURL == null) {
2448                             // haven't seen this PDP before
2449                             String fullURLString = null;
2450                             try {
2451                                 // Check PDP ID
2452                                 if(CheckPDP.validateID(pdp.getId())){
2453                                     fullURLString = pdp.getId() + "?type=hb";
2454                                     pdpURL = new URL(fullURLString);
2455                                     idToURLMap.put(pdp.getId(), pdpURL);
2456                                 }
2457                             } catch (MalformedURLException e) {
2458                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2459                                 continue;
2460                             }
2461                         }
2462                         // Do a GET with type HeartBeat
2463                         String newStatus = "";
2464                         HttpURLConnection connection = null;
2465                         try {
2466                             // Open up the connection
2467                             if(pdpURL != null){
2468                                 connection = (HttpURLConnection)pdpURL.openConnection();
2469                                 // Setup our method and headers
2470                                 connection.setRequestMethod("GET");
2471                                 connection.setConnectTimeout(heartbeatTimeout);
2472                                 // Authentication
2473                                 String encoding = CheckPDP.getEncoding(pdp.getId());
2474                                 if(encoding !=null){
2475                                     connection.setRequestProperty("Authorization", "Basic " + encoding);
2476                                 }
2477                                 // Do the connect
2478                                 connection.connect();
2479                                 if (connection.getResponseCode() == 204) {
2480                                     newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2481                                     if (LOGGER.isDebugEnabled()) {
2482                                         LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2483                                     }
2484                                 } else {
2485                                     // anything else is an unexpected result
2486                                     newStatus = PDPStatus.Status.UNKNOWN.toString();
2487                                     PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2488                                 }
2489                             }
2490                         } catch (UnknownHostException e) {
2491                             newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2492                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2493                         } catch (SocketTimeoutException e) {
2494                             newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2495                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2496                         } catch (ConnectException e) {
2497                             newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2498                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2499                         } catch (Exception e) {
2500                             newStatus = PDPStatus.Status.UNKNOWN.toString();
2501                             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2502                         } finally {
2503                             // cleanup the connection
2504                             if(connection != null)
2505                                 connection.disconnect();
2506                         }
2507                         if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2508                             if (LOGGER.isDebugEnabled()) {
2509                                 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"'  new Status='" + newStatus + "'");
2510                             }
2511                             try {
2512                                 setPDPSummaryStatus(pdp, newStatus);
2513                             } catch (PAPException e) {
2514                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2515                             }
2516                             changeSeen = true;
2517                         }
2518                     }
2519                     // Check for shutdown
2520                     if (this.isRunning() == false) {
2521                         LOGGER.info("isRunning is false, getting out of loop.");
2522                         break;
2523                     }
2524                     // if any of the PDPs changed state, tell the ACs to update
2525                     if (changeSeen) {
2526                         notifyAC();
2527                     }
2528                 }
2529             } catch (InterruptedException e) {
2530                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted.  Shutting down");
2531                 this.terminate();
2532                 Thread.currentThread().interrupt();
2533             }
2534         }
2535     }
2536
2537     /*
2538      * HELPER to change Group status when PDP status is changed
2539      * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2540      */
2541     private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2542         setPDPSummaryStatus(pdp, newStatus.toString());
2543     }
2544
2545     private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2546         synchronized(papEngine) {
2547             StdPDPStatus status = new StdPDPStatus();
2548             status.setStatus(PDPStatus.Status.valueOf(newStatus));
2549             ((StdPDP)pdp).setStatus(status);
2550             // now adjust the group
2551             StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2552             // if the PDP was just deleted it may transiently exist but not be in a group
2553             if (group != null) {
2554                 group.resetStatus();
2555             }
2556         }
2557     }
2558
2559     /*
2560      * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2561      * in the PDP group directories
2562      */
2563     @Override
2564     public void changed() {
2565         // all PDPs in all groups need to be updated/sync'd
2566         Set<OnapPDPGroup> groups;
2567         try {
2568             groups = papEngine.getOnapPDPGroups();
2569         } catch (PAPException e) {
2570             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2571             throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2572         }
2573         for (OnapPDPGroup group : groups) {
2574             groupChanged(group);
2575         }
2576     }
2577
2578     public void changed(ONAPLoggingContext loggingContext) {
2579         // all PDPs in all groups need to be updated/sync'd
2580         Set<OnapPDPGroup> groups;
2581         try {
2582             groups = papEngine.getOnapPDPGroups();
2583         } catch (PAPException e) {
2584             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2585             throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2586         }
2587         for (OnapPDPGroup group : groups) {
2588             groupChanged(group, loggingContext);
2589         }
2590     }
2591
2592     @Override
2593     public void groupChanged(OnapPDPGroup group) {
2594         // all PDPs within one group need to be updated/sync'd
2595         for (OnapPDP pdp : group.getOnapPdps()) {
2596             pdpChanged(pdp);
2597         }
2598     }
2599
2600     public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
2601         // all PDPs within one group need to be updated/sync'd
2602         for (OnapPDP pdp : group.getOnapPdps()) {
2603             pdpChanged(pdp, loggingContext);
2604         }
2605     }
2606
2607     @Override
2608      public void pdpChanged(OnapPDP pdp) {
2609         // kick off a thread to do an event notification for each PDP.
2610         // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2611         // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2612         Thread t = new Thread(new UpdatePDPThread(pdp));
2613         if(CheckPDP.validateID(pdp.getId())){
2614             t.start();
2615         }
2616     }
2617
2618      public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2619         // kick off a thread to do an event notification for each PDP.
2620         // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2621         // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2622         Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
2623         if(CheckPDP.validateID(pdp.getId())){
2624             t.start();
2625         }
2626     }
2627
2628     private class UpdatePDPThread implements Runnable {
2629         private OnapPDP pdp;
2630         private String requestId;
2631         private ONAPLoggingContext loggingContext;
2632
2633         public UpdatePDPThread(OnapPDP pdp) {
2634             this.pdp = pdp;
2635         }
2636
2637         public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2638             this.pdp = pdp;
2639             if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
2640                     this.requestId = loggingContext.getRequestID();
2641             }
2642             this.loggingContext = loggingContext;
2643         }
2644
2645         public void run() {
2646             // send the current configuration to one PDP
2647             HttpURLConnection connection = null;
2648             // get a new logging context for the thread
2649             try {
2650                 if (this.loggingContext == null) {
2651                      loggingContext = new ONAPLoggingContext(baseLoggingContext);
2652                 }
2653             } catch (Exception e) {
2654                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2655                 // Since this is a server-side error, it probably does not reflect a problem on the client,
2656                 // so do not change the PDP status.
2657                 return;
2658             }
2659             try {
2660                 loggingContext.setServiceName("PAP:PDP.putConfig");
2661                 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2662                 if ((requestId == null) || (requestId == "")) {
2663                     UUID requestID = UUID.randomUUID();
2664                     loggingContext.setRequestID(requestID.toString());
2665                     PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one:  " + loggingContext.getRequestID());
2666                 } else {
2667                     loggingContext.setRequestID(requestId);
2668                     PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread):  " + loggingContext.getRequestID());
2669                 }
2670                 loggingContext.transactionStarted();
2671                 // the Id of the PDP is its URL
2672                 if (LOGGER.isDebugEnabled()) {
2673                     LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2674                 }
2675                 //TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
2676                 //TODO          (need to change "cache=", implying getting some input saying which to change)
2677                 URL url = new URL(pdp.getId() + "?cache=all");
2678                 // Open up the connection
2679                 connection = (HttpURLConnection)url.openConnection();
2680                 // Setup our method and headers
2681                 connection.setRequestMethod("PUT");
2682                 // Authentication
2683                 String encoding = CheckPDP.getEncoding(pdp.getId());
2684                 if(encoding !=null){
2685                     connection.setRequestProperty("Authorization", "Basic " + encoding);
2686                 }
2687                 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2688                 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2689                 connection.setInstanceFollowRedirects(true);
2690                 connection.setDoOutput(true);
2691                 try (OutputStream os = connection.getOutputStream()) {
2692                     OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2693                     // if the PDP was just deleted, there is no group, but we want to send an update anyway
2694                     if (group == null) {
2695                         // create blank properties files
2696                         Properties policyProperties = new Properties();
2697                         policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2698                         policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2699                         policyProperties.store(os, "");
2700                         Properties pipProps = new Properties();
2701                         pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2702                         pipProps.store(os, "");
2703                     } else {
2704                         // send properties from the current group
2705                         group.getPolicyProperties().store(os, "");
2706                         Properties policyLocations = new Properties();
2707                         for (PDPPolicy policy : group.getPolicies()) {
2708                             policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2709                         }
2710                         policyLocations.store(os, "");
2711                         group.getPipConfigProperties().store(os, "");
2712                     }
2713                 } catch (Exception e) {
2714                     PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2715                     // Since this is a server-side error, it probably does not reflect a problem on the client,
2716                     // so do not change the PDP status.
2717                     return;
2718                 }
2719                 // Do the connect
2720                 loggingContext.metricStarted();
2721                 connection.connect();
2722                 loggingContext.metricEnded();
2723                 PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
2724                 if (connection.getResponseCode() == 204) {
2725                     LOGGER.info("Success. We are configured correctly.");
2726                     loggingContext.transactionEnded();
2727                     auditLogger.info("Success. PDP is configured correctly.");
2728                     PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2729                     setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2730                 } else if (connection.getResponseCode() == 200) {
2731                     LOGGER.info("Success. PDP needs to update its configuration.");
2732                     loggingContext.transactionEnded();
2733                     auditLogger.info("Success. PDP needs to update its configuration.");
2734                     PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2735                     setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2736                 } else {
2737                     LOGGER.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2738                     loggingContext.transactionEnded();
2739                     auditLogger.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2740                     PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2741                     setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2742                 }
2743             } catch (Exception e) {
2744                 LOGGER.debug(e);
2745                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2746                 loggingContext.transactionEnded();
2747                 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2748                 try {
2749                     setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2750                 } catch (PAPException e1) {
2751                     LOGGER.debug(e1);
2752                     PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2753                     PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2754                 }
2755             } finally {
2756                 // cleanup the connection
2757                 if(connection != null){
2758                     connection.disconnect();
2759                 }
2760                 // tell the AC to update it's status info
2761                 notifyAC();
2762             }
2763         }
2764     }
2765
2766     /*
2767      * RESTful Interface from PAP to ACs notifying them of changes
2768      */
2769     private void notifyAC() {
2770         // kick off a thread to do one event notification for all registered ACs
2771         // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2772         // as part of processing this message on their end.
2773         Thread t = new Thread(new NotifyACThread());
2774         t.start();
2775     }
2776
2777     private class NotifyACThread implements Runnable {
2778         public void run() {
2779             List<String> disconnectedACs = new ArrayList<>();
2780             // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2781             // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2782             for (String acURL : adminConsoleURLStringList) {
2783                 HttpURLConnection connection = null;
2784                 try {
2785                     acURL += "?PAPNotification=true";
2786                     //TODO - Currently we just tell AC that "Something changed" without being specific.  Do we want to tell it which group/pdp changed?
2787                     //TODO - If so, put correct parameters into the Query string here
2788                     acURL += "&objectType=all" + "&action=update";
2789                     if (LOGGER.isDebugEnabled()) {
2790                         LOGGER.debug("creating url for id '" + acURL + "'");
2791                     }
2792                     //TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
2793                     //TODO              (need to change "cache=", implying getting some input saying which to change)
2794                     URL url = new URL(acURL );
2795                     // Open up the connection
2796                     connection = (HttpURLConnection)url.openConnection();
2797                     // Setup our method and headers
2798                     connection.setRequestMethod("PUT");
2799                     connection.setRequestProperty("Content-Type", "text/x-java-properties");
2800                     // Adding this in. It seems the HttpUrlConnection class does NOT
2801                     // properly forward our headers for POST re-direction. It does so
2802                     // for a GET re-direction.
2803                     // So we need to handle this ourselves.
2804                     //TODO - is this needed for a PUT?  seems better to leave in for now?
2805                     connection.setInstanceFollowRedirects(false);
2806                     // Do not include any data in the PUT because this is just a
2807                     // notification to the AC.
2808                     // The AC will use GETs back to the PAP to get what it needs
2809                     // to fill in the screens.
2810                     // Do the connect
2811                     connection.connect();
2812                     if (connection.getResponseCode() == 204) {
2813                         LOGGER.info("Success. We updated correctly.");
2814                     } else {
2815                         LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
2816                     }
2817
2818                 } catch (Exception e) {
2819                     PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2820                     disconnectedACs.add(acURL);
2821                 } finally {
2822                     // cleanup the connection
2823                     if(connection != null)
2824                         connection.disconnect();
2825                 }
2826             }
2827             // remove any ACs that are no longer connected
2828             if (!disconnectedACs.isEmpty()) {
2829                 adminConsoleURLStringList.removeAll(disconnectedACs);
2830             }
2831         }
2832     }
2833
2834     private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2835         LOGGER.info("Test request received");
2836         try {
2837             im.evaluateSanity();
2838             //If we make it this far, all is well
2839             String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2840             LOGGER.info(message);
2841             loggingContext.transactionEnded();
2842             PolicyLogger.audit("Transaction Failed - See Error.log");
2843             response.setStatus(HttpServletResponse.SC_OK);
2844             return;
2845         }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
2846             String submsg;
2847             if (e instanceof ForwardProgressException) {
2848                 submsg = " is not making forward progress.";
2849             } else if (e instanceof AdministrativeStateException) {
2850                 submsg = " Administrative State is LOCKED.";
2851             } else {
2852                 submsg = " Standby Status is NOT PROVIDING SERVICE.";
2853             }
2854
2855             String message = "GET:/pap/test called and PAP " + papResourceName + submsg
2856                     + " Exception Message: " + e.getMessage();
2857             LOGGER.info(message, e);
2858             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2859             loggingContext.transactionEnded();
2860             PolicyLogger.audit("Transaction Failed - See Error.log");
2861             setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2862             return;
2863         }catch (Exception e) {
2864             //A subsystem is not making progress, is locked, standby or is not responding
2865             String eMsg = e.getMessage();
2866             if(eMsg == null){
2867                 eMsg = "No Exception Message";
2868             }
2869             String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2870                     + " Exception Message: " + eMsg;
2871             LOGGER.info(message, e);
2872             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2873             loggingContext.transactionEnded();
2874             PolicyLogger.audit("Transaction Failed - See Error.log");
2875             //Get the specific list of subsystems that failed
2876             String ssFailureList = null;
2877             for(String failedSS : papDependencyGroupsFlatArray){
2878                 if(eMsg.contains(failedSS)){
2879                     if(ssFailureList == null){
2880                         ssFailureList = failedSS;
2881                     }else{
2882                         ssFailureList = ssFailureList.concat(","+failedSS);
2883                     }
2884                 }
2885             }
2886             if(ssFailureList == null){
2887                 ssFailureList = "UnknownSubSystem";
2888             }
2889             response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2890             setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2891             return;
2892         }
2893     }
2894
2895     /*
2896      * Authorizing the PEP Requests.
2897      */
2898     private boolean authorizeRequest(HttpServletRequest request) {
2899         String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2900         // Check if the Client is Authorized.
2901         if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2902             return true;
2903         }else{
2904             return false;
2905         }
2906     }
2907
2908     private static void loadWebapps() throws PAPException{
2909         if(actionHome == null || configHome == null){
2910             Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2911             //Sanity Check
2912             if (webappsPath == null) {
2913                 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2914                 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2915             }
2916             Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2917             Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2918             if (Files.notExists(webappsPathConfig)) {
2919                 try {
2920                     Files.createDirectories(webappsPathConfig);
2921                 } catch (IOException e) {
2922                     PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2923                             + webappsPathConfig.toAbsolutePath().toString());
2924                 }
2925             }
2926             if (Files.notExists(webappsPathAction)) {
2927                 try {
2928                     Files.createDirectories(webappsPathAction);
2929                 } catch (IOException e) {
2930                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2931                             + webappsPathAction.toAbsolutePath().toString(), e);
2932                 }
2933             }
2934             actionHome = webappsPathAction.toString();
2935             configHome = webappsPathConfig.toString();
2936         }
2937     }
2938
2939     public static String getConfigHome(){
2940         try {
2941             loadWebapps();
2942         } catch (PAPException e) {
2943             LOGGER.debug(e);
2944             return null;
2945         }
2946         return configHome;
2947     }
2948
2949     private static void setConfigHome(){
2950         configHome = getConfigHome();
2951     }
2952
2953     public static String getActionHome(){
2954         try {
2955             loadWebapps();
2956         } catch (PAPException e) {
2957             LOGGER.debug(e);
2958             return null;
2959         }
2960         return actionHome;
2961     }
2962
2963     private static void setActionHome(){
2964         actionHome = getActionHome();
2965     }
2966
2967     public static EntityManagerFactory getEmf() {
2968         return emf;
2969     }
2970
2971     public IntegrityAudit getIa() {
2972         return ia;
2973     }
2974
2975     public static String getPDPFile(){
2976         return XACMLPapServlet.pdpFile;
2977     }
2978
2979     public static String getPersistenceUnit(){
2980         return PERSISTENCE_UNIT;
2981     }
2982
2983     public static PAPPolicyEngine getPAPEngine(){
2984         return papEngine;
2985     }
2986
2987     public static PolicyDBDaoTransaction getDbDaoTransaction(){
2988         return policyDBDao.getNewTransaction();
2989     }
2990     public static String getPapDbDriver() {
2991         return papDbDriver;
2992     }
2993
2994     public static void setPapDbDriver(String papDbDriver) {
2995         XACMLPapServlet.papDbDriver = papDbDriver;
2996     }
2997
2998     public static String getPapDbUrl() {
2999         return papDbUrl;
3000     }
3001
3002     public static void setPapDbUrl(String papDbUrl) {
3003         XACMLPapServlet.papDbUrl = papDbUrl;
3004     }
3005
3006     public static String getPapDbUser() {
3007         return papDbUser;
3008     }
3009
3010     public static void setPapDbUser(String papDbUser) {
3011         XACMLPapServlet.papDbUser = papDbUser;
3012     }
3013
3014     public static String getPapDbPassword() {
3015         return papDbPassword;
3016     }
3017
3018     public static void setPapDbPassword(String papDbPassword) {
3019         XACMLPapServlet.papDbPassword = papDbPassword;
3020     }
3021
3022     public static String getMsOnapName() {
3023         return msOnapName;
3024     }
3025
3026     public static void setMsOnapName(String msOnapName) {
3027         XACMLPapServlet.msOnapName = msOnapName;
3028     }
3029
3030     public static String getMsPolicyName() {
3031         return msPolicyName;
3032     }
3033
3034     public static void setMsPolicyName(String msPolicyName) {
3035         XACMLPapServlet.msPolicyName = msPolicyName;
3036     }
3037 }