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